diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 4af885c3bf9..2b619e0e9ce 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -2541,7 +2541,7 @@ dependencies = [ [[package]] name = "opencodex-desktop" -version = "2.65.0-vadymhimself.21" +version = "2.65.0-vadymhimself.22" dependencies = [ "dbus", "reqwest 0.12.24", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 750b35a7c88..4a86ea189f7 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodex-desktop" -version = "2.65.0-vadymhimself.21" +version = "2.65.0-vadymhimself.22" description = "OpenCodex desktop shell" authors = ["OpenCodex contributors"] license = "MIT" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 449f00ce963..9ec3e480d78 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCodex", - "version": "2.65.0-vadymhimself.21", + "version": "2.65.0-vadymhimself.22", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", diff --git a/fixtures/external/anthropic/README.md b/fixtures/external/anthropic/README.md new file mode 100644 index 00000000000..259a24262ac --- /dev/null +++ b/fixtures/external/anthropic/README.md @@ -0,0 +1,6 @@ +# Recorded Anthropic answers + +Real samples of what Anthropic sends. A test that needs one of these loads it from here; it never hand-types a shorter or tidier copy. + +- extra-usage-thirdparty-400.txt: REAL CAPTURE, byte-identical copy (git blob 2b121a6ba90f39457e82491079003a6899ca8811) of fixtures/external/anthropic-extra-usage-thirdparty-400.txt in AgentRadarLabs/agentradar-paperclip at commit 615ec8db6987fb7cab5cc3308ae3b6b3f95b8efe (manifest provenance "recorded"). It is a staging gateway log line for an Anthropic HTTP 400 on House inference, captured 2026-11-11: the prefix "Provider error 400: " then Anthropic's raw JSON error envelope, cut by the gateway logger at 200 characters (it ends mid-word at "and k"). It holds no account, org or request id, so nothing was redacted. Tests take the bytes after the prefix and add only the closing quote and braces the cut removed, so the envelope and message text stay as recorded. +- No real "You're out of extra usage" 400 body has been recorded. The paperclip sample of that wording is marked "derived" (not a live capture), so it is not copied here; the tests keep that wording as a typed string until a real one is logged. diff --git a/fixtures/external/anthropic/extra-usage-thirdparty-400.txt b/fixtures/external/anthropic/extra-usage-thirdparty-400.txt new file mode 100644 index 00000000000..2b121a6ba90 --- /dev/null +++ b/fixtures/external/anthropic/extra-usage-thirdparty-400.txt @@ -0,0 +1 @@ +Provider error 400: {"type":"error","error":{"type":"invalid_request_error","message":"Third-party apps now draw from your extra usage, not your plan limits. Add more at claude.ai/settings/usage and k \ No newline at end of file diff --git a/package.json b/package.json index c424be9e366..af5028705d9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.65.0-vadymhimself.21", + "version": "2.65.0-vadymhimself.22", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", diff --git a/src/images/loop.ts b/src/images/loop.ts index 4d68c0eebd0..756df11baa1 100644 --- a/src/images/loop.ts +++ b/src/images/loop.ts @@ -39,6 +39,7 @@ import { submitVideoJob } from "./xai-video-client"; import { downloadVideoToArtifact, createImageBudget, pruneArtifacts } from "./artifacts"; import { IMAGE_GEN_TOOL_NAME, VIDEO_GEN_TOOL_NAME } from "./synthetic-tool"; import type { ImageBridgePlan, VideoBridgePlan } from "./types"; +import { peekAnthropicPoolRotation, type AnthropicPoolRotationTrigger } from "../oauth/anthropic-pool-rotation"; const SSE_HEADERS = { "Content-Type": "text/event-stream", @@ -348,6 +349,8 @@ export interface ImageBridgeDeps { retryAfterHeader: string | null, responseHeaders?: Headers, retryParsed?: OcxParsedRequest, + /** "quota-400": Anthropic's out-of-extra-usage 400, which only an Anthropic pool rotation answers. */ + trigger?: AnthropicPoolRotationTrigger, ) => RotatedTarget | null | Promise; /** Optional fail-closed credential recovery. The callback must inspect a clone and return null for unrecognized responses. */ onCredentialError?: (response: Response, signal: AbortSignal) => @@ -707,8 +710,13 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise {}); } catch { /* already closed */ } adapter = rotatedAdapterOf(rotated); diff --git a/src/oauth/anthropic-pool-rotation.ts b/src/oauth/anthropic-pool-rotation.ts new file mode 100644 index 00000000000..6ac568c4009 --- /dev/null +++ b/src/oauth/anthropic-pool-rotation.ts @@ -0,0 +1,67 @@ +import { readQuotaResetAt } from "../providers/key-failover"; + +/** + * Why an upstream answer may move a request to the next Anthropic pool account. + * + * - `"429"`: a rate or quota limit, the original trigger. + * - `"quota-400"`: Anthropic answers an account whose plan AND extra usage are spent with + * HTTP 400 ("You're out of extra usage", "Third-party apps now draw from your extra usage"), + * not 429. The account is spent; another pool account may not be. + */ +export type AnthropicPoolRotationTrigger = "429" | "quota-400"; + +/** + * Anthropic's spent-extra-usage wordings, anchored at the start of `error.message`. Only the + * start counts: a validation 400 echoes client values (tool ids, model names, text) into its + * message, so a match anywhere else would let one crafted request cool every pool account. + */ +const EXTRA_USAGE_REFUSAL = /^(?:you['\u2019]re out of extra usage|third-party apps now draw from your extra usage)/i; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Whether a 400 body is Anthropic's out-of-extra-usage refusal. It must be Anthropic's JSON error + * envelope (`type: "error"`, `error.type: "invalid_request_error"`) whose `error.message` starts + * with one of the two wordings. Anything else, including a non-JSON body, is a request-shape + * failure that would fail the same way on any account and must not rotate. + */ +export function isQuotaExhaustedBadRequest(status: number, body: string | null | undefined): boolean { + if (status !== 400 || !body) return false; + let payload: unknown; + try { + payload = JSON.parse(body); + } catch { + return false; + } + if (!isRecord(payload) || payload.type !== "error" || !isRecord(payload.error)) return false; + const { type, message } = payload.error; + return type === "invalid_request_error" + && typeof message === "string" + && EXTRA_USAGE_REFUSAL.test(message.trimStart()); +} + +/** The pool-rotation trigger for an upstream status and (for a 400) its body, or null. */ +export function isPoolRotatableStatus( + status: number, + body?: string | null, +): AnthropicPoolRotationTrigger | null { + if (status === 429) return "429"; + return isQuotaExhaustedBadRequest(status, body) ? "quota-400" : null; +} + +/** + * Decide whether `response` should rotate the Anthropic pool. Only a 400 body is read: a bounded + * prefix through the same peek the key-pool 429 path uses, and the returned response replays it, + * so a caller that does not rotate still forwards the error unchanged. Any other status is + * returned untouched. Throws only when `signal` aborts (client cancelled). + */ +export async function peekAnthropicPoolRotation( + response: Response, + signal?: AbortSignal, +): Promise<{ response: Response; trigger: AnthropicPoolRotationTrigger | null }> { + if (response.status !== 400) return { response, trigger: isPoolRotatableStatus(response.status) }; + const peeked = await readQuotaResetAt(response, { signal }); + return { response: peeked.response, trigger: isPoolRotatableStatus(400, peeked.text) }; +} diff --git a/src/oauth/anthropic-routing.ts b/src/oauth/anthropic-routing.ts index f54ca6787d3..78f12cad9e6 100644 --- a/src/oauth/anthropic-routing.ts +++ b/src/oauth/anthropic-routing.ts @@ -36,6 +36,7 @@ import type { OcxAccountPoolQuotaWindow, OcxAccountPoolRotationStrategy, OcxConf import { sweepExpiredOnWrite } from "../lib/state-store-sweeper"; import { setComboPoolEligibilityProbe } from "../combos/failover"; import { retainedUtf8Bytes } from "../lib/admission"; +import type { AnthropicPoolRotationTrigger } from "./anthropic-pool-rotation"; /** * The read side of a `Headers` object, so a caller can pass the live upstream response's @@ -47,6 +48,14 @@ export type AnthropicRateLimitHeaders = Pick; const PROVIDER = "anthropic"; /** Backoff only when upstream supplies no usable deadline. */ const DEFAULT_COOLDOWN_MS = 60_000; +/** + * Fallback cooldown for an out-of-extra-usage 400 that names no reset (no Retry-After, no rejected + * unified window). The account is spent until a human tops up extra usage or the plan window + * resets, so the 60s rate-limit default would only re-send to it every minute for another 400. + * Ten minutes is the cooldown the combo layer already gives the same `insufficient_quota` + * classification (combos/failover.ts MAX_COOLDOWN_MS, provider-scoped), so the two layers agree. + */ +const QUOTA_400_FALLBACK_COOLDOWN_MS = 10 * 60_000; const AFFINITY_IDLE_TTL_MS = 24 * 60 * 60_000; const MAX_AFFINITY_ENTRIES = 2_000; const MAX_AFFINITY_COMPONENT_BYTES = 512; @@ -744,6 +753,10 @@ export function clearAnthropicSessionAffinityForAccount(accountId: string): void * Record a 429 for `failedAccountId`, cool it, unbind the hitting session, and pick a failover * account. Does NOT promote the store active account — caller should promote only after a * successful retry (or token resolve). + * + * `trigger: "quota-400"` is Anthropic's out-of-extra-usage HTTP 400 (see anthropic-pool-rotation.ts). + * It is quota evidence by itself, so the account always cools, for the same reset-derived window a + * quota 429 uses, falling back to QUOTA_400_FALLBACK_COOLDOWN_MS instead of the 60s default. */ export function rotateAnthropicAccountOn429( config: OcxConfig, @@ -753,7 +766,10 @@ export function rotateAnthropicAccountOn429( now = Date.now(), rateLimitHeaders?: AnthropicRateLimitHeaders | null, modelId?: string | null, + trigger: AnthropicPoolRotationTrigger = "429", ): string | null { + const quota400 = trigger === "quota-400"; + const what = quota400 ? "400 out-of-extra-usage" : "429"; // Reactive 429 failover is NOT gated on the pool flag. That flag buys PROACTIVE routing -- // session affinity, quota-ranked new-session selection, autoSwitchThreshold, strategy -- all // of which move a HEALTHY request and stay opt-in. Rotating away from an account upstream has @@ -773,7 +789,7 @@ export function rotateAnthropicAccountOn429( const parsedRetry = parseRetryAfterMs(retryAfterHeader, now); const resetDerived = parsedRetry !== undefined ? undefined : family ? delayUntil(Number(header("reset")) * 1000, now) : parseRateLimitResetMs(rateLimitHeaders, now); - const cooldownMs = parsedRetry ?? resetDerived ?? DEFAULT_COOLDOWN_MS; + const cooldownMs = parsedRetry ?? resetDerived ?? (quota400 ? QUOTA_400_FALLBACK_COOLDOWN_MS : DEFAULT_COOLDOWN_MS); const cooldownSource = parsedRetry !== undefined ? "retry-after" : resetDerived !== undefined ? "reset-derived" : "default"; // A 429 whose unified status says the account is still allowed is not a limit: upstream refused this // request's shape (e.g. a replay without the Claude Code identity). Cooling on it benched every client @@ -783,14 +799,14 @@ export function rotateAnthropicAccountOn429( // account repeats alternates accounts up to ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST times before the // 429 returns (refused calls bill no tokens); pass the tried accounts in if that shows up in the logs. const status = header("status"); - const limited = status === undefined || [status, header("5h-status"), header("7d-status")].includes("rejected"); + const limited = quota400 || status === undefined || [status, header("5h-status"), header("7d-status")].includes("rejected"); const failover = isAnthropicAccountPoolEnabled(config) || hasAnthropicFailoverQuorum(now); // Which limit refused is only in these headers: log every unified one on every 429 (no credential is among them). const unified: string[] = []; (rateLimitHeaders as Headers | null | undefined)?.forEach?.((value, name) => { if (name.startsWith("anthropic-ratelimit-unified-")) unified.push(`${name.slice(28)}=${value}`); }); - console.warn(`[anthropic-pool] 429 on ${formatAnthropicAccountOrdinal(failedAccountId)} model=${modelId ?? "-"}` + console.warn(`[anthropic-pool] ${what} on ${formatAnthropicAccountOrdinal(failedAccountId)} model=${modelId ?? "-"}` + ` retry-after=${retryAfterHeader?.trim() || "-"} ${unified.join(" ") || "unified=-"}` + (failover && limited ? ` cooldown=${Math.ceil(cooldownMs / 1000)}s until ${new Date(now + cooldownMs).toISOString()} (${cooldownSource}) scope=${family ?? "account"}` @@ -823,7 +839,7 @@ export function rotateAnthropicAccountOn429( if (!next) { // Not only cooldowns: an account that needs re-auth or holds no usable credential is not eligible either. const others = getAccountSet(PROVIDER)?.accounts.filter(a => a.id !== failedAccountId) ?? []; - console.warn("[anthropic-pool] no other eligible Anthropic OAuth account; returning 429" + console.warn(`[anthropic-pool] no other eligible Anthropic OAuth account; returning ${quota400 ? "400" : "429"}` + ` (others=${others.length} cooled=${others.filter(a => isCooled(a.id, now, requestFamily)).length}` + ` reauth=${others.filter(a => a.needsReauth === true).length}` + ` unusable=${others.filter(a => !isPoolCredentialUsable(a.id, now)).length})`); @@ -831,7 +847,7 @@ export function rotateAnthropicAccountOn429( } console.warn( - `[anthropic-pool] 429 on ${formatAnthropicAccountOrdinal(failedAccountId)}; failing over to ${formatAnthropicAccountOrdinal(next)}`, + `[anthropic-pool] ${what} on ${formatAnthropicAccountOrdinal(failedAccountId)}; failing over to ${formatAnthropicAccountOrdinal(next)}`, ); return next; } diff --git a/src/providers/key-failover.ts b/src/providers/key-failover.ts index 97339f3a29f..9a49f88f914 100644 --- a/src/providers/key-failover.ts +++ b/src/providers/key-failover.ts @@ -91,7 +91,7 @@ function replayOnlyResponse(response: Response, chunks: readonly Uint8Array[]): export async function readQuotaResetAt( response: Response, nowOrOptions: number | QuotaResetReadOptions = {}, -): Promise<{ at: number | undefined; response: Response }> { +): Promise<{ at: number | undefined; response: Response; text?: string }> { if (!response.body) return { at: undefined, response }; const options = typeof nowOrOptions === "number" ? { now: nowOrOptions } : nowOrOptions; const now = options.now ?? Date.now(); @@ -175,7 +175,9 @@ export async function readQuotaResetAt( }, }); transferred = true; - return { at: parseQuotaResetAt(text, now), response: rebuiltResponse(response, rest) }; + // `text` is the decoded bounded prefix, for callers that classify the body (pool rotation + // on an Anthropic out-of-extra-usage 400) without reading it twice. + return { at: parseQuotaResetAt(text, now), response: rebuiltResponse(response, rest), text }; } catch (error) { const clientAborted = options.signal?.aborted === true; void reader.cancel(error).catch(() => {}).finally(() => { diff --git a/src/server/responses/adapter-continuation.ts b/src/server/responses/adapter-continuation.ts index 19d56b6711a..ab3ec953dd3 100644 --- a/src/server/responses/adapter-continuation.ts +++ b/src/server/responses/adapter-continuation.ts @@ -39,6 +39,7 @@ import { getAnthropicPoolAccessSnapshot, formatAnthropicProviderForLog, } from "../../oauth/anthropic-routing"; +import { peekAnthropicPoolRotation, type AnthropicPoolRotationTrigger } from "../../oauth/anthropic-pool-rotation"; import { GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST, hasEligibleGenericOAuthFailoverTarget, @@ -384,12 +385,23 @@ export function createAdapterContinuations( continue; } } + // Anthropic pool: rotate on a 429 and on the out-of-extra-usage 400 (anthropic-pool-rotation.ts). + let poolRotationTrigger: AnthropicPoolRotationTrigger | null = null; if ( - response.status === 429 - && transportState.anthropicPoolAccountId + transportState.anthropicPoolAccountId && !isNonReplayableResponse(response) && transportState.anthropicPoolFailovers < ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST ) { + try { + const peeked = await peekAnthropicPoolRotation(response, upstream.signal); + response = peeked.response; + poolRotationTrigger = peeked.trigger; + } catch { + yield { type: "error", message: "client closed request during terminal continuation", status: 499 }; + return; + } + } + if (poolRotationTrigger && transportState.anthropicPoolAccountId) { const nextAccountId = rotateAnthropicAccountOn429( config, transportState.anthropicPoolAccountId, @@ -398,6 +410,7 @@ export function createAdapterContinuations( Date.now(), response.headers, route.modelId, + poolRotationTrigger, ); if (nextAccountId) { try { void response.body?.cancel().catch(() => {}); } catch { /* already closed */ } diff --git a/src/server/responses/adapter-dispatch.ts b/src/server/responses/adapter-dispatch.ts index 1c4c0592aa6..0ff223cf47d 100644 --- a/src/server/responses/adapter-dispatch.ts +++ b/src/server/responses/adapter-dispatch.ts @@ -54,6 +54,7 @@ import { getAnthropicPoolAccessSnapshot, formatAnthropicProviderForLog, } from "../../oauth/anthropic-routing"; +import { peekAnthropicPoolRotation } from "../../oauth/anthropic-pool-rotation"; import { GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST, isGenericOAuthFailoverEnabled, @@ -864,11 +865,21 @@ export async function prepareAdapterExchange( // Opt-in Anthropic OAuth account pool (#294): cool the failed account and retry // with another eligible OAuth account (bounded per request). Disabled by default. + // Also on Anthropic's out-of-extra-usage 400: the account is spent, the pool may not be. while ( - upstreamResponse.status === 429 - && transportState.anthropicPoolAccountId + transportState.anthropicPoolAccountId && transportState.anthropicPoolFailovers < ANTHROPIC_POOL_MAX_FAILOVERS_PER_REQUEST ) { + let poolRotation: Awaited>; + try { + poolRotation = await peekAnthropicPoolRotation(upstreamResponse, options.abortSignal); + } catch { + cleanupUpstreamAbort(); + upstream.abort(); + return clientCancelledResponse(); + } + upstreamResponse = poolRotation.response; + if (!poolRotation.trigger) break; const nextAccountId = rotateAnthropicAccountOn429( config, transportState.anthropicPoolAccountId, @@ -877,6 +888,7 @@ export async function prepareAdapterExchange( Date.now(), upstreamResponse.headers, route.modelId, + poolRotation.trigger, ); if (!nextAccountId) break; try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ } diff --git a/src/server/responses/sidecar-execution.ts b/src/server/responses/sidecar-execution.ts index 4cca928cf4b..23f2d7bf65a 100644 --- a/src/server/responses/sidecar-execution.ts +++ b/src/server/responses/sidecar-execution.ts @@ -31,6 +31,7 @@ import { getAnthropicPoolAccessSnapshot, formatAnthropicProviderForLog, } from "../../oauth/anthropic-routing"; +import type { AnthropicPoolRotationTrigger } from "../../oauth/anthropic-pool-rotation"; import { resolveWireProtocolOverride } from "../adapter-resolve"; import { bindRouteReasoningReplayScope, adapterNeedsForcedContinuation } from "./core-replay"; import { rotateAnthropicProviderOnCredentialDenial } from "./anthropic-source-replay"; @@ -168,11 +169,15 @@ export async function executeResponsesSidecars( retryAfter: string | null, responseHeaders?: Headers, retryParsed?: OcxParsedRequest, + trigger: AnthropicPoolRotationTrigger = "429", ): Promise<{ adapter: ProviderAdapter; recoveryKind: AttemptRecoveryKind } | null> => { // Which pool answered decides how the attempt row reads: an account rotation is not a key // rotation, and logging one as the other hides which credential a 429 actually moved off. let recoveryKind: AttemptRecoveryKind = "oauth-account-429"; - const rotated = rotateProviderTransportOn429(config, route.providerName, route.provider, { + // An out-of-extra-usage 400 moves only the Anthropic pool; key pools and the generic OAuth + // roster keep rotating on 429 alone. + const quota400 = trigger === "quota-400"; + const rotated = quota400 ? null : rotateProviderTransportOn429(config, route.providerName, route.provider, { retryAfter, now: Date.now(), attemptedKey: route.provider.apiKey, @@ -186,7 +191,8 @@ export async function executeResponsesSidecars( // unreachable: Anthropic never has a genericFailoverAccountId (isGenericFailoverProvider // excludes it), so its sidecar 429s died on this guard before the Anthropic arm below // could ever be considered. - transportState.genericFailoverAccountId + !quota400 + && transportState.genericFailoverAccountId && transportState.genericFailovers < GENERIC_OAUTH_MAX_FAILOVERS_PER_REQUEST && isGenericOAuthFailoverEnabled(config, route.providerName) ) { @@ -244,6 +250,7 @@ export async function executeResponsesSidecars( Date.now(), responseHeaders, route.modelId, + trigger, ); if (!nextAccountId) { hop.permit?.release(); diff --git a/src/web-search/loop.ts b/src/web-search/loop.ts index 919f875e9d1..ee5536bfa93 100644 --- a/src/web-search/loop.ts +++ b/src/web-search/loop.ts @@ -22,6 +22,7 @@ import { isTranslatorBudgetExceededError } from "../lib/translator-budget"; import { formatWebSearchResults } from "./format-result"; import { parseStreamWithProgress, RoutedModelInactivityError, WebSearchStreamProtocolError } from "./progress-stream"; import { WEB_SEARCH_TOOL_NAME } from "./synthetic-tool"; +import { peekAnthropicPoolRotation, type AnthropicPoolRotationTrigger } from "../oauth/anthropic-pool-rotation"; const SSE_HEADERS = { "Content-Type": "text/event-stream", @@ -360,6 +361,8 @@ export interface WebSearchLoopDeps { retryAfterHeader: string | null, responseHeaders?: Headers, retryParsed?: OcxParsedRequest, + /** "quota-400": Anthropic's out-of-extra-usage 400, which only an Anthropic pool rotation answers. */ + trigger?: AnthropicPoolRotationTrigger, ) => RotatedTarget | null | Promise; /** Optional fail-closed credential recovery. The callback must inspect a clone and return null for unrecognized responses. */ onCredentialError?: (response: Response, signal: AbortSignal) => @@ -619,8 +622,13 @@ export async function runWithWebSearch(deps: WebSearchLoopDeps): Promise): Response { + return Response.json({ type: "error", error: { type, message } }, { status, headers }); +} + +function envelope(type: string, message: string): string { + return JSON.stringify({ type: "error", error: { type, message } }); +} + +function anthropicTextSse(text: string): Response { + return new Response([ + 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_test","type":"message","role":"assistant","model":"claude-opus-5","content":[],"stop_reason":null,"usage":{"input_tokens":3,"output_tokens":0}}}\n\n', + `event: content_block_start\ndata: ${JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } })}\n\n`, + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text } })}\n\n`, + 'event: content_block_stop\ndata: {"type":"content_block_stop","index":0}\n\n', + `event: message_delta\ndata: ${JSON.stringify({ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } })}\n\n`, + 'event: message_stop\ndata: {"type":"message_stop"}\n\n', + ].join(""), { headers: { "content-type": "text/event-stream" } }); +} + +let testDir = ""; +let previousHome: string | undefined; +let isolatedCodexHome: IsolatedCodexHome | null = null; +const originalFetch = globalThis.fetch; + +beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + isolatedCodexHome = installIsolatedCodexHome("ocx-pool-400-"); + testDir = mkdtempSync(join(tmpdir(), "ocx-pool-400-")); + process.env.OPENCODEX_HOME = testDir; + clearRequestLogsForTests(); + clearAnthropicAccountPoolState(); + clearPoolRotationState(); + globalThis.fetch = originalFetch; +}); + +afterEach(() => { + globalThis.fetch = originalFetch; + clearAnthropicAccountPoolState(); + clearPoolRotationState(); + clearRequestLogsForTests(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + isolatedCodexHome?.restore(); + isolatedCodexHome = null; + if (testDir) removeTreeWithRetry(testDir); +}); + +describe("isPoolRotatableStatus", () => { + test("429 always rotates", () => { + expect(isPoolRotatableStatus(429)).toBe("429"); + }); + + test("the recorded fixture is Anthropic's envelope, kept as recorded", () => { + expect(RECORDED_THIRD_PARTY_LINE.startsWith("Provider error 400: {\"type\":\"error\"")).toBe(true); + expect(RECORDED_THIRD_PARTY_BODY.startsWith(RECORDED_THIRD_PARTY_LINE.slice("Provider error 400: ".length))).toBe(true); + expect(JSON.parse(RECORDED_THIRD_PARTY_BODY)).toEqual({ + type: "error", + error: { + type: "invalid_request_error", + message: "Third-party apps now draw from your extra usage, not your plan limits. Add more at claude.ai/settings/usage and k", + }, + }); + }); + + test("the two extra-usage wordings rotate only inside Anthropic's envelope", () => { + expect(isPoolRotatableStatus(400, RECORDED_THIRD_PARTY_BODY)).toBe("quota-400"); + expect(isPoolRotatableStatus(400, envelope("invalid_request_error", OUT_OF_EXTRA_USAGE))).toBe("quota-400"); + // Curly apostrophe, any case, leading whitespace. + expect(isPoolRotatableStatus(400, envelope("invalid_request_error", " You\u2019re out of extra usage."))).toBe("quota-400"); + expect(isPoolRotatableStatus(400, envelope("invalid_request_error", "YOU'RE OUT OF EXTRA USAGE"))).toBe("quota-400"); + // Not JSON: the raw wording, or the recorded gateway log line itself. + expect(isPoolRotatableStatus(400, OUT_OF_EXTRA_USAGE)).toBeNull(); + expect(isPoolRotatableStatus(400, RECORDED_THIRD_PARTY_LINE)).toBeNull(); + }); + + test("MUST-FAIL (a): a 400 that echoes a client value with quota words does not rotate", () => { + const echoed = "messages.1: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_insufficient_quota"; + expect(isPoolRotatableStatus(400, envelope("invalid_request_error", echoed))).toBeNull(); + for (const value of ["toolu_out_of_extra_usage", "You're out of extra usage", "Third-party apps now draw from your extra usage"]) { + expect(isPoolRotatableStatus(400, envelope("invalid_request_error", `tool_use ids were found without tool_result blocks: ${value}`))).toBeNull(); + } + }); + + test("MUST-FAIL (b): the wording anywhere but the start of the message does not rotate", () => { + for (const message of [ + `messages.0.content.0.text: ${OUT_OF_EXTRA_USAGE}`, + "Invalid model: you're out of extra usage", + "The prompt says: Third-party apps now draw from your extra usage, not your plan limits", + "x You're out of extra usage", + ]) { + expect(isPoolRotatableStatus(400, envelope("invalid_request_error", message))).toBeNull(); + } + }); + + test("MUST-FAIL (c): the right wording in the wrong envelope does not rotate", () => { + for (const body of [ + envelope("rate_limit_error", OUT_OF_EXTRA_USAGE), + envelope("api_error", OUT_OF_EXTRA_USAGE), + JSON.stringify({ error: { type: "invalid_request_error", message: OUT_OF_EXTRA_USAGE } }), + JSON.stringify({ type: "invalid_request_error", error: { type: "invalid_request_error", message: OUT_OF_EXTRA_USAGE } }), + JSON.stringify({ type: "error", error: { message: OUT_OF_EXTRA_USAGE } }), + JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: [OUT_OF_EXTRA_USAGE] } }), + JSON.stringify({ type: "error", message: OUT_OF_EXTRA_USAGE }), + JSON.stringify([{ type: "error", error: { type: "invalid_request_error", message: OUT_OF_EXTRA_USAGE } }]), + ]) { + expect(isPoolRotatableStatus(400, body)).toBeNull(); + } + }); + + test("a malformed-request 400 and other statuses do not rotate", () => { + const body = JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: ROLE_ORDER } }); + expect(isPoolRotatableStatus(400, body)).toBeNull(); + expect(isPoolRotatableStatus(400, "")).toBeNull(); + expect(isPoolRotatableStatus(400)).toBeNull(); + // The quota wording only counts on a 400; other statuses keep their own handling. + expect(isPoolRotatableStatus(500, OUT_OF_EXTRA_USAGE)).toBeNull(); + }); + + test("the peek hands back a response that still carries the whole 400 body", async () => { + const peeked = await peekAnthropicPoolRotation(anthropicError(400, "invalid_request_error", ROLE_ORDER)); + expect(peeked.trigger).toBeNull(); + expect(peeked.response.status).toBe(400); + expect(await peeked.response.text()).toContain("roles must alternate"); + }); +}); + +describe("quota-400 cooldown", () => { + async function seedTwoAccounts() { + for (const id of ["a", "b"]) { + await saveCredential("anthropic", { + access: `access-${id}`, + refresh: `refresh-${id}`, + expires: Date.now() + 3_600_000, + accountId: `uuid-${id}`, + email: `${id}@example.test`, + }); + } + const set = getAccountSet("anthropic")!; + const aId = set.accounts.find(acc => acc.credential.accountId === "uuid-a")!.id; + const bId = set.accounts.find(acc => acc.credential.accountId === "uuid-b")!.id; + await setActiveAccount("anthropic", aId); + return { aId, bId }; + } + const config = { + port: 0, + defaultProvider: "anthropic", + providers: { anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "oauth" } }, + anthropicAccountPool: { enabled: true, autoSwitchThreshold: 100 }, + } as OcxConfig; + + test("without a reset it cools for the quota fallback, not the 60s rate-limit default", async () => { + const { aId, bId } = await seedTwoAccounts(); + const now = 1_800_000_000_000; + expect(rotateAnthropicAccountOn429(config, aId, null, "s", now, new Headers(), "claude-opus-5", "quota-400")).toBe(bId); + expect(getAnthropicAccountHealthSnapshot(aId, now)?.cooldownUntil).toBe(now + 10 * 60_000); + // Same call as a plain 429: unchanged 60s default. + clearAnthropicAccountPoolState(); + expect(rotateAnthropicAccountOn429(config, aId, null, "s", now, new Headers(), "claude-opus-5")).toBe(bId); + expect(getAnthropicAccountHealthSnapshot(aId, now)?.cooldownUntil).toBe(now + 60_000); + }); + + test("it cools even when the unified status still reads allowed, and honours a rejected window's reset", async () => { + const { aId } = await seedTwoAccounts(); + const now = 1_800_000_000_000; + const allowed = new Headers({ "anthropic-ratelimit-unified-status": "allowed" }); + rotateAnthropicAccountOn429(config, aId, null, "s", now, allowed, "claude-opus-5", "quota-400"); + expect(getAnthropicAccountHealthSnapshot(aId, now)?.cooldownUntil).toBe(now + 10 * 60_000); + clearAnthropicAccountPoolState(); + const resetAt = now / 1000 + 3 * 3600; + const rejected = new Headers({ + "anthropic-ratelimit-unified-status": "rejected", + "anthropic-ratelimit-unified-5h-status": "rejected", + "anthropic-ratelimit-unified-5h-reset": String(resetAt), + }); + rotateAnthropicAccountOn429(config, aId, null, "s", now, rejected, "claude-opus-5", "quota-400"); + expect(getAnthropicAccountHealthSnapshot(aId, now)?.cooldownUntil).toBe(resetAt * 1000); + }); +}); + +describe("routed /v1/messages through the Anthropic pool", () => { + function seedServer() { + writeFileSync(join(testDir, "auth.json"), JSON.stringify({ + anthropic: { + activeAccountId: "account-a", + accounts: ["a", "b"].map(id => ({ + id: `account-${id}`, + credential: { + access: `synthetic-access-${id}`, + refresh: `synthetic-refresh-${id}`, + expires: 9999999999999, + accountId: `synthetic-account-${id}`, + }, + })), + }, + }), { mode: 0o600 }); + // Hosted-gateway shape: no combo, the pool alone. + saveConfig({ + port: 0, + defaultProvider: "anthropic", + providers: { anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "oauth" } }, + anthropicAccountPool: { enabled: true, autoSwitchThreshold: 100 }, + } as OcxConfig); + } + + async function send(first: () => Response): Promise<{ response: Response; text: string; authorizations: Array }> { + const authorizations: Array = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init); + if (request.url !== "https://api.anthropic.com/v1/messages") throw new Error(`unexpected egress ${request.url}`); + authorizations.push(request.headers.get("authorization")); + return authorizations.length === 1 ? first() : anthropicTextSse("rotated"); + }) as typeof fetch; + seedServer(); + const server = startServer(0); + try { + const response = await originalFetch(new URL("/v1/messages", server.url), { + method: "POST", + headers: { "content-type": "application/json", "x-api-key": "placeholder" }, + body: JSON.stringify({ + model: "claude-opus-5", + max_tokens: 64, + stream: true, + messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }], + }), + }); + return { response, text: await response.text(), authorizations }; + } finally { + await server.stop(true); + } + } + + test("out-of-extra-usage 400 on account A retries on account B and succeeds", async () => { + const { response, text, authorizations } = await send( + () => anthropicError(400, "invalid_request_error", OUT_OF_EXTRA_USAGE), + ); + expect(response.status).toBe(200); + expect(text).toContain("rotated"); + expect(authorizations).toEqual(["Bearer synthetic-access-a", "Bearer synthetic-access-b"]); + const entry = getRequestLogEntries().findLast(row => row.surface === "claude"); + // The log already maps an insufficient_quota failure to 429 (src/lib/errors.ts). + expect(entry?.attempts).toHaveLength(2); + expect(entry?.attempts?.[1]).toMatchObject({ status: 200, recoveryKinds: ["anthropic-oauth-429"] }); + expect(getAnthropicAccountHealthSnapshot("account-a")?.cooldownUntil).toBeGreaterThan(Date.now() + 9 * 60_000); + }); + + test("the recorded third-party-apps extra-usage 400 rotates too", async () => { + const { response, text, authorizations } = await send( + () => new Response(RECORDED_THIRD_PARTY_BODY, { status: 400, headers: { "content-type": "application/json" } }), + ); + expect(response.status).toBe(200); + expect(text).toContain("rotated"); + expect(authorizations).toEqual(["Bearer synthetic-access-a", "Bearer synthetic-access-b"]); + }); + + test("a malformed-request 400 does not rotate and reaches the caller", async () => { + const { response, text, authorizations } = await send( + () => anthropicError(400, "invalid_request_error", ROLE_ORDER), + ); + expect(response.status).toBe(400); + expect(text).toContain("roles must alternate"); + expect(authorizations).toEqual(["Bearer synthetic-access-a"]); + expect(getAnthropicAccountHealthSnapshot("account-a")).toBeNull(); + }); + + test("MUST-FAIL (a), routed: a 400 echoing toolu_insufficient_quota reaches the caller unchanged", async () => { + const message = "messages.1: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_insufficient_quota"; + const { response, text, authorizations } = await send(() => anthropicError(400, "invalid_request_error", message)); + expect(response.status).toBe(400); + // Byte for byte what Anthropic sent: the gateway neither rotated nor rewrote it. + expect(text).toBe(envelope("invalid_request_error", message)); + expect(authorizations).toEqual(["Bearer synthetic-access-a"]); + expect(getAnthropicAccountHealthSnapshot("account-a")).toBeNull(); + }); +});