diff --git a/CHANGELOG.md b/CHANGELOG.md index 73c8ac4..34a9d90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 2.9.10 + +### Fixed + +- **`claude-sonnet-4-6` ofrecia cuatro niveles de pensamiento inertes.** Es un modelo sin thinking en + este backend (solo los ids con `thinking` reciben presupuesto) y el camino de request descarta + cualquier `thinkingConfig` del cliente, asi que las cuatro variantes no hacian nada. Se quitaron en + vez de dejarlas mintiendo; volver a ponerlas exige un id que piense de verdad. +- **Cualquier error que mencionara "model turn" abortaba la sesion.** La deteccion usaba un + `includes("model turn")` suelto, asi que un timeout o un 429 con esa frase mataba la sesion y + mostraba el aviso de recuperacion sin recuperar nada. Ahora solo matchea la redaccion real del + backend. +- **`http.response` en v2 desencolaba la entrada de otra peticion.** El desencolado no filtraba por + URL ni provider, asi que otra llamada HTTP de la misma sesion se llevaba el trabajo pendiente de + Antigravity. Ahora se compara la URL normalizada en ambos lados. +- **`MAX_WARMUP_RETRIES` no limitaba nada** porque el contador solo devolvia 0 o 1; el tope nunca se + alcanzaba. +- **Claves de cache de firmas** no cubrian `gemini-4` ni los niveles `-xhigh` / `-max`, y el borrado + de `cachedContent` se llevaba por delante el legitimo. + +Dieciseis pruebas nuevas. Suite: 49 archivos, 1238 pruebas. + ## 2.9.9 ### Fixed diff --git a/README.md b/README.md index a2f61b4..97d0b97 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ complaint, which is why it stays documented for setups that ship a working one. | Model | Variants | Description | |---|---|---| | `antigravity-gemini-3.8-flash` | `low`, `medium`, `high` | **Gemini 3.8 Flash** — the default; 1M context | -| `antigravity-claude-sonnet-4-6` | `low`, `medium`, `high`, `max` | Claude Sonnet 4.6 — retiring; grant accounts already get "switch to Claude Sonnet 5.5" | +| `antigravity-claude-sonnet-4-6` | — | Claude Sonnet 4.6 — retiring; grant accounts already get "switch to Claude Sonnet 5.5". Non-thinking: it has no tiers | | `antigravity-claude-opus-4-6-thinking` | `low`, `medium`, `high`, `max` | Claude Opus 4.6 with extended thinking; 200k context | | `antigravity-gpt-oss-120b-medium` | `low`, `medium`, `high` | GPT-OSS 120B, open weights | | `antigravity-gemini-4-argon` | `low`, `medium`, `high` | **Gemini 4 Argon** — registered by `model_discovery` when the account holds the grant | diff --git a/package.json b/package.json index 9af42f9..29db3bb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-antigravity-auth", - "version": "2.9.9", + "version": "2.9.10", "description": "Google Antigravity IDE OAuth auth plugin for OpenCode v2 - access Gemini 4 Argon, 3.8 Flash, and Claude models using Google credentials", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/plugin.ts b/src/plugin.ts index d4f1a85..80103a1 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -72,7 +72,7 @@ function getCapacityBackoffDelay(consecutiveFailures: number): number { const index = Math.min(consecutiveFailures, CAPACITY_BACKOFF_TIERS_MS.length - 1); return CAPACITY_BACKOFF_TIERS_MS[Math.max(0, index)] ?? 5000; } -const warmupAttemptedSessionIds = new Set(); +const warmupAttemptedSessionIds = new Map(); const warmupSucceededSessionIds = new Set(); // Track if this plugin instance is running in a child session (subagent, background task) @@ -175,7 +175,7 @@ function trackWarmupAttempt(sessionId: string): boolean { return false; } if (warmupAttemptedSessionIds.size >= MAX_WARMUP_SESSIONS) { - const first = warmupAttemptedSessionIds.values().next().value; + const first = warmupAttemptedSessionIds.keys().next().value; if (first) { warmupAttemptedSessionIds.delete(first); warmupSucceededSessionIds.delete(first); @@ -185,12 +185,12 @@ function trackWarmupAttempt(sessionId: string): boolean { if (attempts >= MAX_WARMUP_RETRIES) { return false; } - warmupAttemptedSessionIds.add(sessionId); + warmupAttemptedSessionIds.set(sessionId, attempts + 1); return true; } function getWarmupAttemptCount(sessionId: string): number { - return warmupAttemptedSessionIds.has(sessionId) ? 1 : 0; + return warmupAttemptedSessionIds.get(sessionId) ?? 0; } function markWarmupSuccess(sessionId: string): void { @@ -3568,4 +3568,9 @@ export const __testExports = { getHeaderStyleFromUrl, resolveHeaderRoutingDecision, resolveQuotaFallbackHeaderStyle, + MAX_WARMUP_RETRIES, + trackWarmupAttempt, + getWarmupAttemptCount, + markWarmupSuccess, + clearWarmupAttempt, }; diff --git a/src/plugin/config/models.test.ts b/src/plugin/config/models.test.ts index 591568e..8c9d95b 100644 --- a/src/plugin/config/models.test.ts +++ b/src/plugin/config/models.test.ts @@ -43,8 +43,15 @@ describe("OPENCODE_MODEL_DEFINITIONS", () => { }); }); - it("defines (inert) thinking tiers for Claude Sonnet to mirror config intent", () => { - expect(getModel("antigravity-claude-sonnet-4-6").variants).toEqual({ + it("advertises no thinking tiers for Claude Sonnet 4.6, which cannot think", () => { + // Sonnet 4.6 is non-thinking for this backend, so the request path discards any + // thinkingConfig sent for it. Offering tiers used to put four inert entries in + // the picker; they are gone rather than silently ignored (4.1). + expect(getModel("antigravity-claude-sonnet-4-6").variants).toBeUndefined(); + }); + + it("still gives the thinking Claude model its four budget tiers", () => { + expect(getModel("antigravity-claude-opus-4-6-thinking").variants).toEqual({ low: { thinkingConfig: { thinkingBudget: 8192 } }, medium: { thinkingConfig: { thinkingBudget: 16384 } }, high: { thinkingConfig: { thinkingBudget: 24576 } }, diff --git a/src/plugin/config/models.ts b/src/plugin/config/models.ts index 0a26bed..70ad76e 100644 --- a/src/plugin/config/models.ts +++ b/src/plugin/config/models.ts @@ -60,15 +60,11 @@ export const OPENCODE_MODEL_DEFINITIONS: OpencodeModelDefinitions = { name: "Claude Sonnet 4.6 (Antigravity)", limit: { context: 200000, output: 64000 }, modalities: DEFAULT_MODALITIES, - // NOTE: Sonnet is treated as a non-thinking model (isClaudeThinkingModel requires - // "thinking" in the id), so these thinking tiers are currently inert at runtime. - // Kept to mirror the previous opencode.json config intent. - variants: { - low: { thinkingConfig: { thinkingBudget: 8192 } }, - medium: { thinkingConfig: { thinkingBudget: 16384 } }, - high: { thinkingConfig: { thinkingBudget: 24576 } }, - max: { thinkingConfig: { thinkingBudget: 32768 } }, - }, + // No variants on purpose. Sonnet 4.6 is non-thinking for this backend: only ids + // carrying "thinking" get a budget (isClaudeThinkingModel), and the request path + // discards any client-sent thinkingConfig for this model. Advertising tiers here + // put four inert entries in the picker, so they were removed instead of being + // silently ignored. Adding them back needs a backend id that actually thinks. }, "antigravity-claude-opus-4-6-thinking": { name: "Claude Opus 4.6 Thinking (Antigravity)", diff --git a/src/plugin/recovery.test.ts b/src/plugin/recovery.test.ts index 5bb28ef..f57476f 100644 --- a/src/plugin/recovery.test.ts +++ b/src/plugin/recovery.test.ts @@ -18,6 +18,23 @@ describe("detectErrorType", () => { it("returns null for unrelated messages", () => { expect(detectErrorType("Random server error")).toBeNull(); }); + + // Regression: a bare "model turn" substring used to be enough to classify + // any session.error as recoverable, so unrelated failures aborted the + // session and showed a recovery toast without recovering anything. + it("does not treat unrelated mentions of a model turn as recoverable", () => { + expect(detectErrorType("Stopped after the model turn limit was reached")).toBeNull(); + expect(detectErrorType("invalid model turn metadata")).toBeNull(); + expect( + detectErrorType({ error: { message: "Upstream model turn timed out" } }), + ).toBeNull(); + }); + + it("still recovers the Gemini 400 wording with surrounding text", () => { + expect( + detectErrorType({ error: { message: "Request contains unsupported input. Requests ending with a model turn are not supported." } }), + ).toBe("model_turn_end"); + }); }); describe("tool_result_missing detection", () => { diff --git a/src/plugin/recovery.ts b/src/plugin/recovery.ts index 5ece6dd..9654aec 100644 --- a/src/plugin/recovery.ts +++ b/src/plugin/recovery.ts @@ -97,7 +97,16 @@ export function detectErrorType(error: unknown): RecoveryErrorType { // model_turn_end: Gemini rejects histories that end with a model turn holding // a functionCall without a functionResponse (400 "Requests ending with a model // turn are not supported"). Recovered by sanitizing the payload before retry. - if (message.includes("ending with a model turn") || message.includes("model turn")) { + // + // Match only the wording the backend actually rejects with. A bare "model + // turn" substring matched any unrelated failure that happens to mention it + // (timeouts, rate limits), which aborted the live session and showed a + // recovery toast for a payload that was never going to be sanitized. + if ( + message.includes("ending with a model turn") || + message.includes("ends with a model turn") || + message.includes("end with a model turn") + ) { return "model_turn_end"; } diff --git a/src/plugin/request.test.ts b/src/plugin/request.test.ts index 2cf38aa..b5c7f46 100644 --- a/src/plugin/request.test.ts +++ b/src/plugin/request.test.ts @@ -31,6 +31,8 @@ const { hasToolUseInMessages, hasSignedThinkingInMessages, generateSyntheticProjectId, + shouldCacheThinkingSignatures, + modelForSignatureCacheKey, MIN_SIGNATURE_LENGTH, transformStreamingPayload, createStreamingTransformer, @@ -1076,6 +1078,81 @@ it("removes x-api-key header", () => { expect(result.headerStyle).toBe("antigravity"); }); + describe("cached content normalization", () => { + it("keeps a legitimate camelCase cachedContent instead of deleting it", () => { + const result = prepareAntigravityRequest( + "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent", + { + method: "POST", + body: JSON.stringify({ + contents: [{ role: "user", parts: [{ text: "hi" }] }], + cachedContent: "cachedContents/legit-cache-1", + }), + }, + mockAccessToken, + mockProjectId, + ); + + const wrapped = JSON.parse(result.init.body as string); + expect(wrapped.request.cachedContent).toBe("cachedContents/legit-cache-1"); + expect(wrapped.request.cached_content).toBeUndefined(); + }); + + it("normalizes a snake_case cached_content into the canonical camelCase field", () => { + const result = prepareAntigravityRequest( + "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent", + { + method: "POST", + body: JSON.stringify({ + contents: [{ role: "user", parts: [{ text: "hi" }] }], + cached_content: "cachedContents/legit-cache-2", + }), + }, + mockAccessToken, + mockProjectId, + ); + + const wrapped = JSON.parse(result.init.body as string); + expect(wrapped.request.cachedContent).toBe("cachedContents/legit-cache-2"); + expect(wrapped.request.cached_content).toBeUndefined(); + }); + + it("hoists cachedContent out of extra_body and drops the empty extra_body", () => { + const result = prepareAntigravityRequest( + "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent", + { + method: "POST", + body: JSON.stringify({ + contents: [{ role: "user", parts: [{ text: "hi" }] }], + extra_body: { cachedContent: "cachedContents/legit-cache-3" }, + }), + }, + mockAccessToken, + mockProjectId, + ); + + const wrapped = JSON.parse(result.init.body as string); + expect(wrapped.request.cachedContent).toBe("cachedContents/legit-cache-3"); + expect(wrapped.request.extra_body).toBeUndefined(); + }); + + it("omits cachedContent when the request never had one", () => { + const result = prepareAntigravityRequest( + "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent", + { + method: "POST", + body: JSON.stringify({ contents: [{ role: "user", parts: [{ text: "hi" }] }] }), + }, + mockAccessToken, + mockProjectId, + ); + + const wrapped = JSON.parse(result.init.body as string); + expect(wrapped.request.cachedContent).toBeUndefined(); + expect(wrapped.request.cached_content).toBeUndefined(); + }); + }); + describe("Issue #103: model name transformation during quota fallback", () => { it("transforms gemini-3-flash-preview to gemini-3-flash for antigravity headerStyle", () => { const result = prepareAntigravityRequest( @@ -1556,3 +1633,96 @@ describe("T-AGY-TOOLARGS tool schema preservation & SSE streaming regression", ( }); }); }); + +describe("thinking-signature caching for tiered families (4.3b)", () => { + it("caches signatures for the Gemini 4 families, not only Gemini 3", () => { + expect(shouldCacheThinkingSignatures("gemini-3-pro")).toBe(true); + expect(shouldCacheThinkingSignatures("gemini-4-argon-high")).toBe(true); + expect(shouldCacheThinkingSignatures("gemini-4-hydrogen-xhigh")).toBe(true); + expect(shouldCacheThinkingSignatures("antigravity-gemini-4-argon")).toBe(true); + expect(shouldCacheThinkingSignatures("gemini-2.5-flash")).toBe(false); + expect(shouldCacheThinkingSignatures(undefined)).toBe(false); + }); + + it("strips every tier suffix, including -xhigh and -max", () => { + for (const tier of ["minimal", "low", "medium", "high", "xhigh", "max"]) { + expect(modelForSignatureCacheKey(`gemini-4-argon-${tier}`)).toBe("gemini-4-argon"); + expect(modelForSignatureCacheKey(`claude-sonnet-5-5-${tier}`)).toBe("claude-sonnet-5-5"); + } + // Ids without a tier are untouched, and so is a tier-like word inside the name. + expect(modelForSignatureCacheKey("gemini-4-argon")).toBe("gemini-4-argon"); + expect(modelForSignatureCacheKey("gemini-4-argon-high-preview")).toBe("gemini-4-argon-high-preview"); + }); + + it("keeps one signature session key per conversation when the tier changes", () => { + const sessionKeyFor = (model: string, level: string) => { + const result = prepareAntigravityRequest( + `https://generativelanguage.googleapis.com/v1beta/models/antigravity-${model}:streamGenerateContent`, + { + method: "POST", + body: JSON.stringify({ + project: "test-project", + request: { contents: [{ role: "user", parts: [{ text: "hello there" }] }] }, + providerOptions: { google: { thinkingLevel: level } }, + }), + }, + "test-token", + "test-project", + ); + return JSON.parse(result.init.body as string).request.sessionId as string; + }; + + const low = sessionKeyFor("gemini-4-argon", "low"); + const high = sessionKeyFor("gemini-4-argon", "high"); + expect(low).toBe(high); + expect(low).toContain(":gemini-4-argon:"); + + const claudeLow = sessionKeyFor("claude-sonnet-5-5", "low"); + const claudeMax = sessionKeyFor("claude-sonnet-5-5", "max"); + expect(claudeLow).toBe(claudeMax); + expect(claudeLow).toContain(":claude-sonnet-5-5:"); + }); + + it("keeps the tier out of the key on the unwrapped Gemini contents path too", () => { + const sessionKeyFor = (level: string) => { + const result = prepareAntigravityRequest( + "https://generativelanguage.googleapis.com/v1beta/models/antigravity-gemini-4-argon:streamGenerateContent", + { + method: "POST", + body: JSON.stringify({ + contents: [{ role: "user", parts: [{ text: "hello there" }] }], + generationConfig: { thinkingConfig: { includeThoughts: true, thinkingLevel: level } }, + }), + }, + "test-token", + "test-project", + ); + return JSON.parse(result.init.body as string).request.sessionId as string; + }; + + expect(sessionKeyFor("low")).toBe(sessionKeyFor("high")); + expect(sessionKeyFor("low")).toContain(":gemini-4-argon:"); + }); + + it("still separates conversations that differ in model or prompt", () => { + const sessionKey = (model: string, text: string) => { + const result = prepareAntigravityRequest( + `https://generativelanguage.googleapis.com/v1beta/models/antigravity-${model}:streamGenerateContent`, + { + method: "POST", + body: JSON.stringify({ + project: "test-project", + request: { contents: [{ role: "user", parts: [{ text }] }] }, + providerOptions: { google: { thinkingLevel: "high" } }, + }), + }, + "test-token", + "test-project", + ); + return JSON.parse(result.init.body as string).request.sessionId as string; + }; + + expect(sessionKey("gemini-4-argon", "hello there")).not.toBe(sessionKey("gemini-4-argon", "different prompt")); + expect(sessionKey("gemini-4-argon", "hello there")).not.toBe(sessionKey("claude-sonnet-5-5", "hello there")); + }); +}); diff --git a/src/plugin/request.ts b/src/plugin/request.ts index e44e833..1b62485 100644 --- a/src/plugin/request.ts +++ b/src/plugin/request.ts @@ -115,9 +115,22 @@ function buildSignatureSessionKey( function shouldCacheThinkingSignatures(model?: string): boolean { if (typeof model !== "string") return false; const lower = model.toLowerCase(); - // Both Claude and Gemini 3 models require thought signature caching - // for multi-turn conversations with function calling - return lower.includes("claude") || lower.includes("gemini-3"); + // Claude, Gemini 3 and Gemini 4 families require thought signature caching + // for multi-turn conversations with function calling. Gemini 4 tiers live in + // the id suffix (`gemini-4-argon-high`), so the prefix check must cover them. + return lower.includes("claude") || lower.includes("gemini-3") || lower.includes("gemini-4"); +} + +/** + * Model component of the signature cache key. + * + * Tiered families encode the selected tier in the id suffix (`gemini-4-argon-high`, + * `claude-sonnet-5-5-max`), while the conversation and its signatures stay the same. + * Stripping the suffix keeps one cache entry per conversation across tier changes + * instead of orphaning the cached signatures when the user switches effort. + */ +function modelForSignatureCacheKey(model: string): string { + return model.replace(/-(minimal|low|medium|high|xhigh|max)$/i, ""); } function hashConversationSeed(seed: string): string { @@ -976,7 +989,7 @@ export function prepareAntigravityRequest( let tierSuffixLevel = tierThinkingLevel; let signatureSessionKey = buildSignatureSessionKey( PLUGIN_SESSION_ID, - effectiveModel, + modelForSignatureCacheKey(effectiveModel), undefined, resolveProjectKey(projectId), ); @@ -1075,7 +1088,7 @@ export function prepareAntigravityRequest( const conversationKey = resolveConversationKeyFromRequests(requestObjects); // Strip tier suffix from model for cache key to prevent cache misses on tier change // e.g., "claude-opus-4-6-thinking-high" -> "claude-opus-4-6-thinking" - const modelForCacheKey = effectiveModel.replace(/-(minimal|low|medium|high|xhigh|max)$/i, ""); + const modelForCacheKey = modelForSignatureCacheKey(effectiveModel); signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, modelForCacheKey, conversationKey, resolveProjectKey(parsedBody.project)); if (requestObjects.length > 0) { @@ -1353,8 +1366,11 @@ export function prepareAntigravityRequest( requestPayload.cachedContent = cachedContent; } + // Normalize to the single camelCase field the Antigravity backend accepts. + // `cachedContent` itself is legitimate and must survive: only its duplicates + // (snake_case at root, or a copy nested inside `extra_body`) are removed, and + // only after the value has been hoisted above. delete requestPayload.cached_content; - delete requestPayload.cachedContent; if (requestPayload.extra_body && typeof requestPayload.extra_body === "object") { delete (requestPayload.extra_body as Record).cached_content; delete (requestPayload.extra_body as Record).cachedContent; @@ -1532,7 +1548,9 @@ export function prepareAntigravityRequest( } const conversationKey = resolveConversationKey(requestPayload); - signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, effectiveModel, conversationKey, resolveProjectKey(projectId)); + // Same tier-stripped key as the wrapped-body path above, so both paths share one + // cache entry per conversation instead of breaking it when the tier changes. + signatureSessionKey = buildSignatureSessionKey(PLUGIN_SESSION_ID, modelForSignatureCacheKey(effectiveModel), conversationKey, resolveProjectKey(projectId)); // For Claude models, filter out unsigned thinking blocks (required by Claude API) // Attempts to restore signatures from cache for multi-turn conversations @@ -2139,6 +2157,8 @@ export const __testExports = { ensureThinkingBeforeToolUseInContents, ensureThinkingBeforeToolUseInMessages, generateSyntheticProjectId, + shouldCacheThinkingSignatures, + modelForSignatureCacheKey, MIN_SIGNATURE_LENGTH, transformSseLine, transformStreamingPayload, diff --git a/src/plugin/warmup-retry-limit.test.ts b/src/plugin/warmup-retry-limit.test.ts new file mode 100644 index 0000000..e55c998 --- /dev/null +++ b/src/plugin/warmup-retry-limit.test.ts @@ -0,0 +1,83 @@ +import { beforeAll, describe, expect, it, vi } from "vitest"; + +vi.mock("@opencode-ai/plugin", () => ({ + tool: vi.fn(), +})); + +type WarmupHelpers = { + MAX_WARMUP_RETRIES: number; + trackWarmupAttempt: (sessionId: string) => boolean; + getWarmupAttemptCount: (sessionId: string) => number; + markWarmupSuccess: (sessionId: string) => void; + clearWarmupAttempt: (sessionId: string) => void; +}; + +let helpers: WarmupHelpers; + +beforeAll(async () => { + const { __testExports } = await import("../plugin"); + helpers = __testExports as WarmupHelpers; +}); + +describe("thinking warmup retry budget", () => { + it("blocks warmup after MAX_WARMUP_RETRIES attempts in the same session", () => { + const sessionId = "ses-warmup-limit-1"; + const { MAX_WARMUP_RETRIES, trackWarmupAttempt, getWarmupAttemptCount } = helpers; + + expect(MAX_WARMUP_RETRIES).toBeGreaterThan(1); + + for (let attempt = 1; attempt <= MAX_WARMUP_RETRIES; attempt++) { + expect(trackWarmupAttempt(sessionId)).toBe(true); + expect(getWarmupAttemptCount(sessionId)).toBe(attempt); + } + + // The budget is exhausted: further warmups for this session must be refused. + expect(trackWarmupAttempt(sessionId)).toBe(false); + expect(getWarmupAttemptCount(sessionId)).toBe(MAX_WARMUP_RETRIES); + }); + + it("counts attempts independently per session", () => { + const { MAX_WARMUP_RETRIES, trackWarmupAttempt, getWarmupAttemptCount } = helpers; + const first = "ses-warmup-limit-2a"; + const second = "ses-warmup-limit-2b"; + + expect(trackWarmupAttempt(first)).toBe(true); + expect(getWarmupAttemptCount(first)).toBe(1); + expect(getWarmupAttemptCount(second)).toBe(0); + + // Fill the second session's budget, then check it is refused. + for (let attempt = 1; attempt <= MAX_WARMUP_RETRIES; attempt++) { + expect(trackWarmupAttempt(second)).toBe(true); + expect(getWarmupAttemptCount(second)).toBe(attempt); + } + + expect(getWarmupAttemptCount(second)).toBe(MAX_WARMUP_RETRIES); + expect(trackWarmupAttempt(second)).toBe(false); + // Exhausting one session must not consume another session's budget. + expect(trackWarmupAttempt(first)).toBe(true); + }); + + it("reset on failure gives the session a fresh budget", () => { + const sessionId = "ses-warmup-limit-3"; + const { MAX_WARMUP_RETRIES, trackWarmupAttempt, getWarmupAttemptCount, clearWarmupAttempt } = + helpers; + + for (let attempt = 1; attempt <= MAX_WARMUP_RETRIES; attempt++) { + expect(trackWarmupAttempt(sessionId)).toBe(true); + } + expect(trackWarmupAttempt(sessionId)).toBe(false); + + clearWarmupAttempt(sessionId); + expect(getWarmupAttemptCount(sessionId)).toBe(0); + expect(trackWarmupAttempt(sessionId)).toBe(true); + }); + + it("a successful warmup stops further attempts for that session", () => { + const sessionId = "ses-warmup-limit-4"; + const { trackWarmupAttempt, markWarmupSuccess } = helpers; + + expect(trackWarmupAttempt(sessionId)).toBe(true); + markWarmupSuccess(sessionId); + expect(trackWarmupAttempt(sessionId)).toBe(false); + }); +}); diff --git a/src/v2/adapter.ts b/src/v2/adapter.ts index e819db4..ae97ef1 100644 --- a/src/v2/adapter.ts +++ b/src/v2/adapter.ts @@ -554,6 +554,10 @@ export async function setupV2(context: V2Context): Promise/v1internal:`). */ + rewrittenUrl?: string; createdAt: number; } const pendingBySession = new Map(); @@ -584,10 +588,53 @@ export async function setupV2(context: V2Context): Promise pendingBySession.get(sessionID)?.[0]; - const dequeuePending = (sessionID: string): PendingEntry | undefined => { + /** URL a prepared payload will actually be sent to, when it is known. */ + const pendingRequestUrl = (prepared: any): string | undefined => { + const request = prepared?.request; + if (typeof request === "string") return request; + if (request && typeof request.url === "string") return request.url; + return undefined; + }; + + /** + * `new Request(...)` normalizes its URL, so compare normalized forms on both + * sides instead of raw strings. + */ + const normalizePendingUrl = (value: string): string => { + try { + return new URL(value).href; + } catch { + return value; + } + }; + + const describePendingUrls = (entry: PendingEntry): string[] => + [entry.url, entry.rewrittenUrl] + .filter((value): value is string => typeof value === "string" && value.length > 0) + .map(normalizePendingUrl); + + /** + * Dequeues the pending entry that belongs to `url`. + * + * A session can have several requests in flight at once (parallel tool calls, + * subagents sharing the session), so blind FIFO dequeuing handed one + * response another request's prepared payload: the model, the account and the + * recorded usage all came from the wrong call. When the response tells us + * which URL it answers, only that entry is consumed; a URL matching nothing + * leaves the queue untouched instead of stealing somebody else's metadata. + * Without a URL (the retry hook has none) the oldest entry is still used. + */ + const dequeuePending = (sessionID: string, url?: string): PendingEntry | undefined => { const queue = pendingBySession.get(sessionID); if (!queue || queue.length === 0) return undefined; - const entry = queue.shift(); + let index = 0; + if (url) { + const wanted = normalizePendingUrl(url); + const found = queue.findIndex((entry) => describePendingUrls(entry).includes(wanted)); + if (found === -1) return undefined; + index = found; + } + const [entry] = queue.splice(index, 1); if (queue.length === 0) { pendingBySession.delete(sessionID); } @@ -701,6 +748,7 @@ export async function setupV2(context: V2Context): Promise { const sessionKey = event.sessionID ?? "default"; - const entry = dequeuePending(sessionKey); + // The response may or may not carry the request it answers. When it does, + // consume exactly that request's entry: several requests can share one + // session and a blind FIFO dequeue gave each of them somebody else's + // model, account and usage metadata. + const responseUrl = typeof event.request?.url === "string" ? event.request.url : undefined; + const entry = dequeuePending(sessionKey, responseUrl); // Recorded before the `!entry` early return: after a 429 rotation the queue // is empty for the attempt that finally succeeds, and that success is // exactly the one worth counting.