Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion desktop/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
2 changes: 1 addition & 1 deletion desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
6 changes: 6 additions & 0 deletions fixtures/external/anthropic/README.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions fixtures/external/anthropic/extra-usage-thirdparty-400.txt
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
12 changes: 10 additions & 2 deletions src/images/loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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<RotatedTarget | null>;
/** Optional fail-closed credential recovery. The callback must inspect a clone and return null for unrecognized responses. */
onCredentialError?: (response: Response, signal: AbortSignal) =>
Expand Down Expand Up @@ -707,8 +710,13 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise<Respons
prepared = await fetchOnce(adapter, "rate-limit-429");
}
// 429 key-failover parity with web-search / normal routed path.
while (prepared.response.status === 429 && deps.on429) {
const rotated = await deps.on429(prepared.response.headers.get("retry-after"), prepared.response.headers, iterParsed);
// An Anthropic out-of-extra-usage 400 also reaches the hook; only a 400 body is peeked, and
// the peeked response replays it, so a 400 that does not rotate surfaces unchanged.
while (deps.on429) {
const gate = await peekAnthropicPoolRotation(prepared.response, signal);
prepared.response = gate.response;
if (!gate.trigger) break;
const rotated = await deps.on429(prepared.response.headers.get("retry-after"), prepared.response.headers, iterParsed, gate.trigger);
if (!rotated) break;
try { void prepared.response.body?.cancel().catch(() => {}); } catch { /* already closed */ }
adapter = rotatedAdapterOf(rotated);
Expand Down
67 changes: 67 additions & 0 deletions src/oauth/anthropic-pool-rotation.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> {
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) };
}
26 changes: 21 additions & 5 deletions src/oauth/anthropic-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -47,6 +48,14 @@ export type AnthropicRateLimitHeaders = Pick<Headers, "get">;
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;
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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"}`
Expand Down Expand Up @@ -823,15 +839,15 @@ 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})`);
return null;
}

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;
}
Expand Down
6 changes: 4 additions & 2 deletions src/providers/key-failover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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(() => {
Expand Down
17 changes: 15 additions & 2 deletions src/server/responses/adapter-continuation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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 */ }
Expand Down
16 changes: 14 additions & 2 deletions src/server/responses/adapter-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<ReturnType<typeof peekAnthropicPoolRotation>>;
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,
Expand All @@ -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 */ }
Expand Down
Loading
Loading