diff --git a/src/constants.ts b/src/constants.ts index 1d2a20e..efcf08e 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -90,7 +90,7 @@ export function setAntigravityVersion(version: string): void { * signature that the backend requires for Gemini 3.7/3.8 Flash. Kept current by * `initAntigravityCliVersion()`; see docs/ANTIGRAVITY_API_SPEC.md. */ -export const ANTIGRAVITY_CLI_VERSION_FALLBACK = "1.5.14"; +export const ANTIGRAVITY_CLI_VERSION_FALLBACK = "1.5.17"; /** * Build id (`cl`) reported by each CLI version in its client signature. @@ -101,6 +101,9 @@ export const ANTIGRAVITY_CLI_VERSION_FALLBACK = "1.5.14"; * version than the one this plugin was written against. */ const ANTIGRAVITY_CLI_BUILDS: Record = { + // Build id taken from the artifact agy itself downloads: + // antigravity-cli/1.5.17-4823843970351104/linux-x64/cli_linux_x64.tar.gz + "1.5.17": "4823843970351104", "1.5.14": "1027820220", "1.5.8": "962369648", }; diff --git a/src/plugin.test.ts b/src/plugin.test.ts index 48e627d..9322727 100644 --- a/src/plugin.test.ts +++ b/src/plugin.test.ts @@ -126,7 +126,7 @@ vi.mock("./plugin/stats", () => ({ }, })); -import { createAntigravityPlugin, verifyAccountAccess } from "./plugin"; +import { createAntigravityPlugin, verifyAccountAccess, extractToSSuspensionReason } from "./plugin"; function createMockClient() { return { @@ -254,6 +254,38 @@ describe("v1 plugin empty response retry (2.3)", () => { }); }); +describe("extractToSSuspensionReason", () => { + it("recognizes the account-level Terms of Service suspension", () => { + const body = JSON.stringify({ + error: { + code: 403, + message: "This service has been disabled in this account for violation of Terms of Service. Please submit an appeal to continue using this product.", + status: "PERMISSION_DENIED", + }, + }); + + const reason = extractToSSuspensionReason(body); + expect(reason).toContain("violation of Terms of Service"); + }); + + it("does not treat a validation_required 403 as a suspension", () => { + const body = JSON.stringify({ + error: { + code: 403, + message: "Validation Required", + details: [{ reason: "VALIDATION_REQUIRED", metadata: { validation_url: "https://accounts.google.com/verify" } }], + }, + }); + + expect(extractToSSuspensionReason(body)).toBeUndefined(); + }); + + it("ignores rate-limit and quota bodies", () => { + const body = JSON.stringify({ error: { code: 429, message: "Individual quota reached" } }); + expect(extractToSSuspensionReason(body)).toBeUndefined(); + }); +}); + describe("verifyAccountAccess (3.3)", () => { afterEach(() => { vi.restoreAllMocks(); diff --git a/src/plugin.ts b/src/plugin.ts index 458a63b..b31eee2 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -446,6 +446,31 @@ function extractVerificationErrorDetails(bodyText: string): { }; } +/** + * 403 signature for an account-level Terms of Service suspension. + * + * Distinct from `validation_required`: there is no verification URL, and no + * amount of retrying clears it. The backend answers this for every model on the + * account, so the account has to leave rotation instead of being retried. + */ +export function extractToSSuspensionReason(bodyText: string): string | undefined { + if (!bodyText) { + return undefined; + } + const decoded = decodeEscapedText(bodyText); + const match = decoded + .split("\n") + .map((line) => line.trim()) + .find((line) => + /violation of terms of service/i.test(line) || + /service has been disabled in this account/i.test(line), + ); + if (!match) { + return undefined; + } + return match.slice(0, 300); +} + export async function verifyAccountAccess( account: { refreshToken: string; @@ -605,8 +630,40 @@ type VerificationStoredAccount = { verificationRequiredAt?: number; verificationRequiredReason?: string; verificationUrl?: string; + suspended?: boolean; + suspendedAt?: number; + suspendedReason?: string; }; +/** + * Persists a ToS suspension in the raw storage record. Mirrors + * `markStoredAccountVerificationRequired` so a crash right after the 403 does + * not put the suspended account back in rotation on the next start. + */ +function markStoredAccountSuspended(account: VerificationStoredAccount, reason: string): boolean { + let changed = false; + const normalizedReason = reason.trim(); + + if (account.suspended !== true) { + account.suspended = true; + changed = true; + } + if (account.suspendedAt === undefined) { + account.suspendedAt = Date.now(); + changed = true; + } + if (normalizedReason && account.suspendedReason !== normalizedReason) { + account.suspendedReason = normalizedReason; + changed = true; + } + if (account.enabled !== false) { + account.enabled = false; + changed = true; + } + + return changed; +} + function markStoredAccountVerificationRequired( account: VerificationStoredAccount, reason: string, @@ -2308,6 +2365,37 @@ export const createAntigravityPlugin = (providerId: string) => async ( if (response.status === 403) { const errorBodyText = await response.clone().text().catch(() => ""); + const suspensionReason = extractToSSuspensionReason(errorBodyText); + + if (suspensionReason) { + accountManager.markAccountSuspended(account.index, suspensionReason); + try { + const stored = await loadAccounts(); + const target = stored?.accounts[account.index]; + if (stored && target && markStoredAccountSuspended(target, suspensionReason)) { + await saveAccounts(stored); + } + } catch (persistError) { + pushDebug(`suspension persist failed: ${String(persistError)}`); + } + + const label = account.email || `Account ${account.index + 1}`; + if (accountManager.shouldShowAccountToast(account.index, 60000)) { + await showToast( + `[WARN] ${label} is suspended (Terms of Service). Removed from rotation; appeal at support.google.com.`, + "warning", + ); + accountManager.markToastShown(account.index); + } + + pushDebug(`tos-suspension: disabled account ${account.index} (${suspensionReason})`); + getHealthTracker().recordFailure(account.index); + + lastFailure = createFailureContext(response); + shouldSwitchAccount = true; + break; + } + const extracted = extractVerificationErrorDetails(errorBodyText); if (extracted.validationRequired) { @@ -2706,9 +2794,11 @@ export const createAntigravityPlugin = (providerId: string) => async ( while (true) { const now = Date.now(); const existingAccounts = existingStorage.accounts.map((acc, idx) => { - let status: 'active' | 'rate-limited' | 'expired' | 'verification-required' | 'unknown' = 'unknown'; + let status: 'active' | 'rate-limited' | 'expired' | 'verification-required' | 'suspended' | 'unknown' = 'unknown'; - if (acc.verificationRequired) { + if (acc.suspended) { + status = 'suspended'; + } else if (acc.verificationRequired) { status = 'verification-required'; } else { const rateLimits = acc.rateLimitResetTimes; @@ -2738,6 +2828,8 @@ export const createAntigravityPlugin = (providerId: string) => async ( status, isCurrentAccount: idx === (existingStorage.activeIndex ?? 0), enabled: acc.enabled !== false, + suspended: acc.suspended === true, + suspendedReason: acc.suspendedReason, }; }); @@ -2750,7 +2842,11 @@ export const createAntigravityPlugin = (providerId: string) => async ( for (const res of results) { const label = res.email || `Account ${res.index + 1}`; - const disabledStr = res.disabled ? " (disabled)" : ""; + const disabledStr = res.suspended + ? " (suspended: Terms of Service)" + : res.disabled + ? " (disabled)" + : ""; console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`); console.log(` ${label}${disabledStr}`); console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`); diff --git a/src/plugin/accounts.test.ts b/src/plugin/accounts.test.ts index 013f233..d69dc95 100644 --- a/src/plugin/accounts.test.ts +++ b/src/plugin/accounts.test.ts @@ -2065,6 +2065,65 @@ describe("AccountManager", () => { vi.useRealTimers(); }); + it("reports a Terms of Service suspension instead of a plain disable", () => { + const stored: AccountStorageV4 = { + version: 4, + accounts: [ + { email: "banned@example.com", refreshToken: "rb", addedAt: 1, lastUsed: 0, enabled: false, suspended: true, suspendedReason: "violation of Terms of Service" }, + ], + activeIndex: 0, + }; + + const manager = new AccountManager(undefined, stored); + const reasons = manager.getAllBlockedReasons("gemini"); + + expect(reasons[0]?.reason).toContain("suspended"); + expect(reasons[0]?.reason).toContain("violation of Terms of Service"); + expect(reasons[0]?.waitMs).toBeNull(); + }); + + it("keeps a suspended account out of rotation even if the file says enabled", () => { + const stored: AccountStorageV4 = { + version: 4, + accounts: [ + { email: "banned@example.com", refreshToken: "rb", addedAt: 1, lastUsed: 0, enabled: true, suspended: true }, + { email: "healthy@example.com", refreshToken: "rh", addedAt: 1, lastUsed: 0 }, + ], + activeIndex: 0, + }; + + const manager = new AccountManager(undefined, stored); + expect(manager.getAccounts()[0]?.enabled).toBe(false); + expect(manager.getNextForFamily("gemini")?.index).toBe(1); + }); + + it("takes a suspended account out of rotation and restores it on explicit enable", () => { + const stored: AccountStorageV4 = { + version: 4, + accounts: [ + { email: "banned@example.com", refreshToken: "rb", addedAt: 1, lastUsed: 0 }, + { email: "healthy@example.com", refreshToken: "rh", addedAt: 1, lastUsed: 0 }, + ], + activeIndex: 0, + }; + + const manager = new AccountManager(undefined, stored); + expect(manager.markAccountSuspended(0, "violation of Terms of Service")).toBe(true); + + const suspended = manager.getAccounts()[0]; + expect(suspended?.enabled).toBe(false); + expect(suspended?.suspended).toBe(true); + expect(suspended?.suspendedReason).toBe("violation of Terms of Service"); + + const next = manager.getNextForFamily("gemini"); + expect(next?.index).toBe(1); + + expect(manager.setAccountEnabled(0, true)).toBe(true); + const restored = manager.getAccounts()[0]; + expect(restored?.enabled).toBe(true); + expect(restored?.suspended).toBe(false); + }); + it("names the cause when only the model-less family key was marked", () => { vi.useFakeTimers(); vi.setSystemTime(10_000); diff --git a/src/plugin/accounts.ts b/src/plugin/accounts.ts index 34fe851..7ffa0e2 100644 --- a/src/plugin/accounts.ts +++ b/src/plugin/accounts.ts @@ -198,6 +198,10 @@ export interface ManagedAccount { verificationRequiredAt?: number; verificationRequiredReason?: string; verificationUrl?: string; + /** 403 ToS suspension: permanent for this process until the user re-enables it. */ + suspended?: boolean; + suspendedAt?: number; + suspendedReason?: string; /** Counter of consecutive high safety risk evaluations (Account Shield) */ consecutiveHighRiskTriggers?: number; } @@ -464,7 +468,10 @@ export class AccountManager { }, access: matchesFallback ? authFallback?.access : undefined, expires: matchesFallback ? authFallback?.expires : undefined, - enabled: acc.enabled !== false, + // A ToS suspension is permanent until the user lifts it explicitly; + // a stale `enabled: true` on disk must not put the account back in + // rotation. + enabled: acc.enabled !== false && acc.suspended !== true, rateLimitResetTimes: acc.rateLimitResetTimes ?? {}, lastSwitchReason: acc.lastSwitchReason, coolingDownUntil: acc.coolingDownUntil, @@ -479,6 +486,9 @@ export class AccountManager { verificationRequiredAt: acc.verificationRequiredAt, verificationRequiredReason: acc.verificationRequiredReason, verificationUrl: acc.verificationUrl, + suspended: acc.suspended, + suspendedAt: acc.suspendedAt, + suspendedReason: acc.suspendedReason, }; }) .filter((a): a is ManagedAccount => a !== null); @@ -965,6 +975,12 @@ export class AccountManager { } account.enabled = enabled; + // Re-enabling is the user's explicit "try this account again": drop the + // suspension mark so the quota report stops calling it suspended. + if (enabled && account.suspended) { + this.clearAccountSuspension(accountIndex, false); + } + if (!enabled) { for (const family of Object.keys(this.currentAccountIndexByFamily) as ModelFamily[]) { if (this.currentAccountIndexByFamily[family] === accountIndex) { @@ -1029,6 +1045,53 @@ export class AccountManager { return true; } + /** + * Takes an account out of rotation after a 403 "violation of Terms of Service". + * The backend answers that for every model on the account, so retrying costs a + * wasted attempt per request until the user appeals or re-enables it. + */ + markAccountSuspended(accountIndex: number, reason?: string): boolean { + const account = this.accounts[accountIndex]; + if (!account) { + return false; + } + + account.suspended = true; + account.suspendedAt = nowMs(); + const normalizedReason = reason?.trim(); + account.suspendedReason = normalizedReason || undefined; + + if (account.enabled !== false) { + this.setAccountEnabled(accountIndex, false); + } else { + this.requestSaveToDisk(); + } + + return true; + } + + clearAccountSuspension(accountIndex: number, enableAccount = true): boolean { + const account = this.accounts[accountIndex]; + if (!account) { + return false; + } + + const wasSuspended = account.suspended === true; + const hadMetadata = account.suspendedAt !== undefined || account.suspendedReason !== undefined; + + account.suspended = false; + account.suspendedAt = undefined; + account.suspendedReason = undefined; + + if (enableAccount && wasSuspended && account.enabled === false) { + this.setAccountEnabled(accountIndex, true); + } else if (wasSuspended || hadMetadata) { + this.requestSaveToDisk(); + } + + return true; + } + removeAccountByIndex(accountIndex: number): boolean { if (accountIndex < 0 || accountIndex >= this.accounts.length) { return false; @@ -1165,9 +1228,11 @@ export class AccountManager { return this.accounts.map((a, idx) => { const label = a.email || `Account ${idx + 1}`; if (a.enabled === false) { - const reasonStr = a.verificationRequired - ? `verification required (${a.verificationRequiredReason || "visit accounts.google.com"})` - : "account disabled"; + const reasonStr = a.suspended + ? `suspended (${a.suspendedReason || "terms of service violation"})` + : a.verificationRequired + ? `verification required (${a.verificationRequiredReason || "visit accounts.google.com"})` + : "account disabled"; return { email: label, reason: reasonStr, waitMs: null }; } @@ -1271,6 +1336,9 @@ export class AccountManager { verificationRequiredAt: a.verificationRequiredAt, verificationRequiredReason: a.verificationRequiredReason, verificationUrl: a.verificationUrl, + suspended: a.suspended, + suspendedAt: a.suspendedAt, + suspendedReason: a.suspendedReason, })), activeIndex: claudeIndex, activeIndexByFamily: { @@ -1469,6 +1537,7 @@ export class AccountManager { addedAt: a.addedAt, lastUsed: a.lastUsed, enabled: a.enabled, + suspended: a.suspended, })); } diff --git a/src/plugin/quota.ts b/src/plugin/quota.ts index 557f83a..c364d25 100644 --- a/src/plugin/quota.ts +++ b/src/plugin/quota.ts @@ -64,6 +64,8 @@ export interface AccountQuotaResult { status: AccountQuotaStatus; error?: string; disabled?: boolean; + /** 403 Terms of Service suspension: the account cannot serve inference at all. */ + suspended?: boolean; groups?: GroupQuotaDisplay[]; models?: ModelQuotaDisplay[]; cachedQuota?: Partial>; @@ -265,6 +267,7 @@ export async function fetchAccountQuotaDetails( providerId = ANTIGRAVITY_PROVIDER_ID, ): Promise { const disabled = account.enabled === false; + const suspended = account.suspended === true; let auth = buildAuthFromAccount(account); const now = Date.now(); @@ -363,6 +366,7 @@ export async function fetchAccountQuotaDetails( email: account.email, status: disabled ? "disabled" : "ok", disabled, + suspended, groups, cachedQuota, modelCatalog: account.modelCatalog, @@ -381,6 +385,7 @@ export async function fetchAccountQuotaDetails( email: account.email, status: disabled ? "disabled" : "ok", disabled, + suspended, models: [], modelCatalog: account.modelCatalog, updatedAccount, @@ -514,6 +519,7 @@ export async function fetchAccountQuotaDetails( email: account.email, status: disabled ? "disabled" : "ok", disabled, + suspended, groups: groups.length > 0 ? groups : undefined, models, cachedQuota, @@ -731,8 +737,11 @@ export function formatQuotaReportMarkdown(results: AccountQuotaResult[]): string const email = result.email || `account-${result.index + 1}`; const five = formatBucketCells(group?.fiveHour); const week = formatBucketCells(group?.weekly); - const usability = formatUsabilityCells(group); - const name = `${shortEmail(email)}${result.disabled ? " (disabled)" : ""}`; + const usability = result.suspended + ? { usable: "no · suspended".padEnd(16, " "), sortKey: 0 } + : formatUsabilityCells(group); + const suffix = result.suspended ? " (suspended)" : result.disabled ? " (disabled)" : ""; + const name = `${shortEmail(email)}${suffix}`; let line = ""; if (showFiveHour) line += `${five.quota}${five.reset}`; if (showWeekly) line += `${week.quota}${week.reset}`; @@ -746,7 +755,7 @@ export function formatQuotaReportMarkdown(results: AccountQuotaResult[]): string } } else { // Fallback model list format (accounts whose summary endpoint is unavailable). - const familyMap = new Map>(); + const familyMap = new Map>(); for (const result of results) { if (result.status === "error" || !result.models) { @@ -773,6 +782,7 @@ export function formatQuotaReportMarkdown(results: AccountQuotaResult[]): string percentage: model.remainingPercentage, resetIn: model.timeUntilResetFormatted, disabled: result.disabled, + suspended: result.suspended, }); } } @@ -785,7 +795,7 @@ export function formatQuotaReportMarkdown(results: AccountQuotaResult[]): string const accountsList = Array.from(accountMap.entries()).map(([email, info]) => ({ email, ...info })); for (const acc of accountsList.sort((a, b) => b.percentage - a.percentage)) { - output += `${progressBar(acc.percentage).padEnd(18, " ")}${acc.resetIn.padEnd(15, " ")}${shortEmail(acc.email)}${acc.disabled ? " (disabled)" : ""}\n`; + output += `${progressBar(acc.percentage).padEnd(18, " ")}${acc.resetIn.padEnd(15, " ")}${shortEmail(acc.email)}${acc.suspended ? " (suspended)" : acc.disabled ? " (disabled)" : ""}\n`; } output += "```\n"; } diff --git a/src/plugin/stats.ts b/src/plugin/stats.ts index 3a89378..bd6bc7b 100644 --- a/src/plugin/stats.ts +++ b/src/plugin/stats.ts @@ -215,11 +215,21 @@ export class EngineStatsManager { return this.data; } - public formatStatsReport(activeEmail?: string): string { + public formatStatsReport( + activeEmail?: string, + accountStates?: Array<{ email?: string; enabled?: boolean; suspended?: boolean }>, + ): string { this.refreshFromDisk(); const data = this.data; const lines: string[] = []; + const stateByEmail = new Map(); + for (const state of accountStates ?? []) { + if (state.email) { + stateByEmail.set(state.email.toLowerCase(), state); + } + } + lines.push("==================== ANTIGRAVITY ENGINE STATS ===================="); lines.push(""); @@ -240,7 +250,14 @@ export class EngineStatsManager { const health = `${acc.healthScore ?? 100}%`.padEnd(10); const reqs = `${acc.requestsSuccess}/${acc.rateLimits429}/${acc.errorsOther}`.padEnd(20); const isActive = activeEmail && acc.email.toLowerCase() === activeEmail.toLowerCase(); - const status = isActive ? "ACTIVE" : "STANDBY"; + const state = stateByEmail.get(acc.email.toLowerCase()); + const status = state?.suspended + ? "SUSPENDED" + : state?.enabled === false + ? "DISABLED" + : isActive + ? "ACTIVE" + : "STANDBY"; lines.push(`${userPart} ${health}${reqs}${status}`); } } diff --git a/src/plugin/storage.ts b/src/plugin/storage.ts index cce43e0..2178e2f 100644 --- a/src/plugin/storage.ts +++ b/src/plugin/storage.ts @@ -221,6 +221,14 @@ export interface AccountMetadataV3 { verificationRequiredAt?: number; verificationRequiredReason?: string; verificationUrl?: string; + /** + * Set when the backend answers 403 "disabled in this account for violation of + * Terms of Service". This is not a rate limit: retrying only burns attempts, + * so the account is taken out of rotation until the user re-enables it. + */ + suspended?: boolean; + suspendedAt?: number; + suspendedReason?: string; /** Cached soft quota data */ cachedQuota?: Partial>; cachedQuotaUpdatedAt?: number; diff --git a/src/plugin/ui/auth-menu.ts b/src/plugin/ui/auth-menu.ts index 7b75323..d45c27f 100644 --- a/src/plugin/ui/auth-menu.ts +++ b/src/plugin/ui/auth-menu.ts @@ -2,7 +2,7 @@ import { ANSI } from './ansi'; import { select, type MenuItem } from './select'; import { confirm } from './confirm'; -export type AccountStatus = 'active' | 'rate-limited' | 'expired' | 'verification-required' | 'unknown'; +export type AccountStatus = 'active' | 'rate-limited' | 'expired' | 'verification-required' | 'suspended' | 'unknown'; export interface AccountInfo { email?: string; @@ -12,6 +12,8 @@ export interface AccountInfo { status?: AccountStatus; isCurrentAccount?: boolean; enabled?: boolean; + suspended?: boolean; + suspendedReason?: string; } export type AuthMenuAction = @@ -47,6 +49,7 @@ function getStatusBadge(status: AccountStatus | undefined): string { case 'rate-limited': return `${ANSI.yellow}[rate-limited]${ANSI.reset}`; case 'expired': return `${ANSI.red}[expired]${ANSI.reset}`; case 'verification-required': return `${ANSI.red}[needs verification]${ANSI.reset}`; + case 'suspended': return `${ANSI.red}[suspended: ToS]${ANSI.reset}`; default: return ''; } } @@ -67,7 +70,9 @@ export async function showAuthMenu(accounts: AccountInfo[]): Promise { const statusBadge = getStatusBadge(account.status); const currentBadge = account.isCurrentAccount ? ` ${ANSI.cyan}[current]${ANSI.reset}` : ''; - const disabledBadge = account.enabled === false ? ` ${ANSI.red}[disabled]${ANSI.reset}` : ''; + const disabledBadge = account.enabled === false && !account.suspended + ? ` ${ANSI.red}[disabled]${ANSI.reset}` + : ''; const baseLabel = account.email || `Account ${account.index + 1}`; const numbered = `${account.index + 1}. ${baseLabel}`; const fullLabel = `${numbered}${currentBadge}${statusBadge ? ' ' + statusBadge : ''}${disabledBadge}`; diff --git a/src/v2/adapter.ts b/src/v2/adapter.ts index cde6a9e..18136bc 100644 --- a/src/v2/adapter.ts +++ b/src/v2/adapter.ts @@ -1475,7 +1475,7 @@ export async function setupV2(context: V2Context): Promise