Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix(sse): bound Antigravity 429 retry loop and lock quota-exhausted accounts for full reset window (#3122)
Ahmet Çetinkaya84b5caeeb946
diff --git a/open-sse/executors/antigravity.ts b/open-sse/executors/antigravity.tsindex 05e2ee598d..791e8cc273 100644--- a/open-sse/executors/antigravity.ts+++ b/open-sse/executors/antigravity.ts@@ -1238,11 +1238,21 @@ export class AntigravityExecutor extends BaseExecutor {}}- if (retryMs && retryMs <= LONG_RETRY_THRESHOLD_MS) {+ // Bounded short-retry: a non-null retryAfterMs ≤ 60s covers nearly every+ // 429 (decide429 returns 2s/5s/60s defaults), so this branch MUST share the+ // per-URL attempt counter. Without the bound a persistent 429 loops forever+ // on the same endpoint/account (urlIndex-- cancels the loop's urlIndex++) and+ // never returns the 429 to the account-fallback layer in chat.ts.+ if (+ retryMs &&+ retryMs <= LONG_RETRY_THRESHOLD_MS &&+ retryAttemptsByUrl[urlIndex] < MAX_AUTO_RETRIES+ ) {+ retryAttemptsByUrl[urlIndex]++;const effectiveRetryMs = Math.min(retryMs, MAX_RETRY_AFTER_MS);log?.debug?.("RETRY",- `${response.status} with Retry-After: ${Math.ceil(effectiveRetryMs / 1000)}s, waiting...`+ `${response.status} retry ${retryAttemptsByUrl[urlIndex]}/${MAX_AUTO_RETRIES} with Retry-After: ${Math.ceil(effectiveRetryMs / 1000)}s, waiting...`);await new Promise((resolve) => setTimeout(resolve, effectiveRetryMs));urlIndex--;diff --git a/open-sse/services/accountFallback.ts b/open-sse/services/accountFallback.tsindex 507e1c2bca..69e069efde 100644--- a/open-sse/services/accountFallback.ts+++ b/open-sse/services/accountFallback.ts@@ -22,7 +22,11 @@ import {getCircuitBreaker,STATE,} from "../../src/shared/utils/circuitBreaker";-import { classify429FromError, type FailureKind } from "../../src/shared/utils/classify429";+import {+ classify429FromError,+ looksLikeQuotaExhausted,+ type FailureKind,+} from "../../src/shared/utils/classify429";import { resolveUseUpstream429BreakerHints } from "../../src/shared/utils/providerHints";type ProviderProfile = {@@ -912,25 +916,33 @@ export function parseRetryFromErrorText(errorText: unknown): number | null {}const match = errorText.match(/reset after (\d+h)?(\d+m)?(\d+s)?/i);- if (!match) {- // Also try the variant without "reset after": "will reset after XhYmZs"- const altMatch = errorText.match(/will reset after (\d+h)?(\d+m)?(\d+s)?/i);- if (!altMatch) return null;- return computeDurationMs(altMatch);+ if (match?.[1] || match?.[2] || match?.[3]) return computeDurationMs(match);++ // Variant without "reset after": "will reset after XhYmZs"+ const altMatch = errorText.match(/will reset after (\d+h)?(\d+m)?(\d+s)?/i);+ if (altMatch?.[1] || altMatch?.[2] || altMatch?.[3]) return computeDurationMs(altMatch);++ // Antigravity / Cloud Code phrasing: "Resets in 164h27m24s".+ const resetsInMatch = errorText.match(/resets? in (\d+h)?(\d+m)?(\d+s)?/i);+ if (resetsInMatch?.[1] || resetsInMatch?.[2] || resetsInMatch?.[3]) {+ return computeDurationMs(resetsInMatch);}- return computeDurationMs(match);+ return null;}/*** Compute total milliseconds from regex match groups (Xh)(Ym)(Zs)+ * Capped at 30 days to prevent adversarial/buggy upstream from locking indefinitely.*/+const MAX_PROVIDER_COOLDOWN_MS = 30 * 24 * 60 * 60 * 1000; // 30 days+function computeDurationMs(match: RegExpMatchArray): number | null {let totalMs = 0;if (match[1]) totalMs += parseInt(match[1], 10) * 3600 * 1000; // hoursif (match[2]) totalMs += parseInt(match[2], 10) * 60 * 1000; // minutesif (match[3]) totalMs += parseInt(match[3], 10) * 1000; // seconds- return totalMs > 0 ? totalMs : null;+ return totalMs > 0 ? Math.min(totalMs, MAX_PROVIDER_COOLDOWN_MS) : null;}function isSubscriptionQuotaText(lower: string): boolean {@@ -960,6 +972,7 @@ export function classifyErrorText(errorText: unknown): RateLimitReasonValue {lower.includes("quota has been exceeded") ||lower.includes("hour quota") ||lower.includes("billing") ||+ looksLikeQuotaExhausted(lower) ||// Issue #2321: Anthropic OAuth (Claude Code Pro/Team) 429 bodies surface// the subscription quota with phrases that contain neither "quota" nor// "billing". Without these patterns the error was classified as adiff --git a/src/shared/utils/classify429.ts b/src/shared/utils/classify429.tsindex 43c41daaa8..81ae985a99 100644--- a/src/shared/utils/classify429.ts+++ b/src/shared/utils/classify429.ts@@ -45,6 +45,14 @@ const QUOTA_PATTERNS: ReadonlyArray<RegExp> = [/plan.*limit/i,/resource.*exhaust/i,/check.*quota/i,+ // Antigravity / Cloud Code quota exhaustion ("Individual quota reached.+ // Contact your administrator to enable overages. Resets in 164h27m24s.").+ // None of the patterns above match it, so the 429 was misclassified as a+ // transient rate-limit and locked for only ~5s instead of the real window.+ // Keep these specific: a bare /quota reached/ would also flag transient+ // per-minute limits like "request quota reached, retry in 60s".+ /individual quota reached/i,+ /enable overages/i,];/**diff --git a/tests/unit/account-fallback-service.test.ts b/tests/unit/account-fallback-service.test.tsindex ce9e2a3286..713a93440e 100644--- a/tests/unit/account-fallback-service.test.ts+++ b/tests/unit/account-fallback-service.test.ts@@ -78,6 +78,70 @@ test("parseRetryFromErrorText parses both compact reset formats", () => {assert.equal(parseRetryFromErrorText("No reset metadata"), null);});+test("parseRetryFromErrorText parses Antigravity 'Resets in XhYmZs' phrasing", () => {+ assert.equal(+ parseRetryFromErrorText(+ "Individual quota reached. Contact your administrator to enable overages. " ++ "Resets in 164h27m24s."+ ),+ (164 * 3600 + 27 * 60 + 24) * 1000+ );+ assert.equal(parseRetryFromErrorText("Resets in 2h7m23s"), 7_643_000);+ assert.equal(parseRetryFromErrorText("Reset in 45m"), 2_700_000);+});++test("parseRetryFromErrorText caps extreme reset windows at 30 days", () => {+ const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000;+ // 100 days → capped to 30+ assert.equal(parseRetryFromErrorText("Resets in 2400h"), thirtyDaysMs);+ // Absurd value → capped+ assert.equal(parseRetryFromErrorText("Resets in 999999h"), thirtyDaysMs);+});++test("checkFallbackError locks Antigravity quota-reached 429 for the full reset window", () => {+ const message =+ "Individual quota reached. Contact your administrator to enable overages. " ++ "Resets in 164h27m24s.";+ const result = checkFallbackError(+ 429,+ message,+ 0,+ "gemini-3-flash-agent",+ "antigravity",+ null,+ makeProfile()+ );++ assert.equal(result.shouldFallback, true);+ assert.equal(result.reason, RateLimitReason.QUOTA_EXHAUSTED);+ assert.equal(result.usedUpstreamRetryHint, true);+ // Full parsed window (≈164.46h), under the 30-day cap — not the generic ~5s rate-limit backoff.+ assert.equal(result.cooldownMs, (164 * 3600 + 27 * 60 + 24) * 1000);+});++test("recordModelLockoutFailure honors a multi-day exactCooldownMs (under 30-day cap)", () => {+ const provider = "antigravity";+ const connectionId = "conn-quota-window";+ const model = "gemini-3-flash-agent";+ const exactCooldownMs = (164 * 3600 + 27 * 60 + 24) * 1000;++ clearModelLock(provider, connectionId, model);+ const lockout = recordModelLockoutFailure(+ provider,+ connectionId,+ model,+ "quota_exhausted",+ 429,+ 0,+ makeProfile(),+ { exactCooldownMs }+ );++ assert.equal(lockout.cooldownMs, exactCooldownMs);+ assert.equal(isModelLocked(provider, connectionId, model), true);+ clearModelLock(provider, connectionId, model);+});+test("checkFallbackError marks deactivated accounts as permanent auth failures", () => {const result = checkFallbackError(401, "This account has been deactivated");assert.equal(result.shouldFallback, true);@@ -86,6 +150,13 @@ test("checkFallbackError marks deactivated accounts as permanent auth failures",assert.ok(result.cooldownMs >= 300 * 24 * 60 * 60 * 1000);});+test("checkFallbackError classifies 'free tier of the model has been exhausted' as quota exhausted", () => {+ const result = checkFallbackError(429, "free tier of the model has been exhausted");+ assert.equal(result.shouldFallback, true);+ assert.equal(result.reason, RateLimitReason.QUOTA_EXHAUSTED);+ assert.equal(result.creditsExhausted, true);+});+test("checkFallbackError treats non-429 exhausted credits as long quota cooldowns", () => {const result = checkFallbackError(402, "credit_balance_too_low");assert.equal(result.shouldFallback, true);diff --git a/tests/unit/classify429.test.ts b/tests/unit/classify429.test.tsindex a57b04e134..1a37a1d720 100644--- a/tests/unit/classify429.test.ts+++ b/tests/unit/classify429.test.ts@@ -35,6 +35,37 @@ test("classify429: 429 with quota keyword in string body returns 'quota_exhausteassert.equal(classify429({ status: 429, body: "plan limit reached" }), "quota_exhausted");});+test("classify429: Antigravity 'Individual quota reached' body returns 'quota_exhausted'", () => {+ const body =+ "Individual quota reached. Contact your administrator to enable overages. " ++ "Resets in 164h27m24s.";+ assert.equal(looksLikeQuotaExhausted(body), true);+ assert.equal(classify429({ status: 429, body }), "quota_exhausted");+ assert.equal(+ classify429({ status: 429, body: { error: { message: body } } }),+ "quota_exhausted"+ );+});++test("classify429: Antigravity quota patterns do not over-match plain rate limits", () => {+ // The new 'quota reached' / 'enable overages' patterns must stay specific —+ // a per-minute rate limit must still classify as a transient rate_limit.+ assert.equal(+ classify429({ status: 429, body: "Too many requests, please slow down." }),+ "rate_limit"+ );+ assert.equal(+ classify429({ status: 429, body: "Rate limit exceeded. Try again in 30s." }),+ "rate_limit"+ );+ // A bare "quota reached" in a transient per-minute limit must NOT be locked as+ // quota_exhausted — only the specific "individual quota reached" wording is.+ assert.equal(+ classify429({ status: 429, body: "Request quota reached, retry in 60s." }),+ "rate_limit"+ );+});+test("classify429: 429 with quota keyword in nested object body returns 'quota_exhausted'", () => {assert.equal(classify429({diff --git a/tests/unit/executor-antigravity.test.ts b/tests/unit/executor-antigravity.test.tsindex e0af44d2af..442a44432c 100644--- a/tests/unit/executor-antigravity.test.ts+++ b/tests/unit/executor-antigravity.test.ts@@ -722,6 +722,54 @@ test("AntigravityExecutor.execute embeds retryAfterMs when the upstream asks for}});+test("AntigravityExecutor.execute bounds a persistent short-retry 429 instead of looping forever", async () => {+ const executor = new AntigravityExecutor();+ const originalFetch = globalThis.fetch;+ const originalSetTimeout = globalThis.setTimeout;+ const calls: string[] = [];+ seedAntigravityVersionCache("2026.04.17-test");++ // "rate limited" classifies as rate_limited → decide429 returns 60s+ // (≤ LONG_RETRY_THRESHOLD_MS), i.e. the short-retry branch. A persistent 429+ // must NOT loop forever on one endpoint — it must exhaust MAX_AUTO_RETRIES per+ // endpoint, advance through every base URL, then return the 429 so the+ // account-fallback layer can switch accounts.+ globalThis.fetch = async (url) => {+ calls.push(String(url));+ return new Response(JSON.stringify({ error: { message: "rate limited" } }), {+ status: 429,+ headers: { "Content-Type": "application/json" },+ });+ };+ globalThis.setTimeout = ((callback) => {+ (callback as () => void)();+ return 0;+ }) as typeof setTimeout;++ try {+ const result = await executor.execute({+ model: "antigravity/gemini-2.5-flash",+ body: { request: { contents: [] } },+ stream: true,+ credentials: { accessToken: "token", projectId: "project-1" },+ log: { debug() {}, warn() {} },+ });++ // Returns the 429 rather than hanging.+ assert.equal(result.response.status, 429);++ // Bounded: 3 endpoints × (1 initial + MAX_AUTO_RETRIES=3) = 12 attempts total.+ assert.equal(calls.length, 12);++ // Tried every distinct base URL before giving up.+ const distinctHosts = new Set(calls.map((u) => new URL(u).host));+ assert.equal(distinctHosts.size, 3);+ } finally {+ globalThis.fetch = originalFetch;+ globalThis.setTimeout = originalSetTimeout;+ }+});+test("AntigravityExecutor.execute tags pre-response stalls with a fallbackable timeout code", async () => {const executor = new AntigravityExecutor();const originalFetch = globalThis.fetch;