diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 6e8ab282aa7..e7e7510e298 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.17" +version = "2.65.0-vadymhimself.18" dependencies = [ "dbus", "reqwest 0.12.24", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index ada4bc86270..52c49a7e4fe 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.17" +version = "2.65.0-vadymhimself.18" 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 58e1a8da69c..f071b2f8bc2 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.17", + "version": "2.65.0-vadymhimself.18", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", diff --git a/package.json b/package.json index 6e6dfb67219..1a5577b2d5f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.65.0-vadymhimself.17", + "version": "2.65.0-vadymhimself.18", "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/adapters/anthropic.ts b/src/adapters/anthropic.ts index 0a9a05ed35c..33305ccb5a3 100644 --- a/src/adapters/anthropic.ts +++ b/src/adapters/anthropic.ts @@ -17,7 +17,7 @@ import type { OcxUsage, } from "../types"; import { isAllowedToolChoice, namespacedToolName, resolveToolChoiceWireName, toolChoiceToolPredicate } from "../types"; -import { ANTHROPIC_OAUTH_BETA, CLAUDE_CODE_SYSTEM_INSTRUCTION, applyClaudeToolPrefix, stripClaudeToolPrefix } from "../oauth/anthropic"; +import { ANTHROPIC_OAUTH_BETA, CLAUDE_CODE_SYSTEM_INSTRUCTION, applyClaudeToolPrefix, prependClaudeIdentity, stripClaudeToolPrefix } from "../oauth/anthropic"; import { parseComboModelId } from "../combos/identifiers"; import { parseDataUrl } from "./image"; import { enforceAnthropicImageLimits } from "./anthropic-image-guard"; @@ -1213,8 +1213,8 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti if (source && isExactCanonicalAnthropicMessagesUrl(url) && canReplayAnthropicSource(source.body, parsed.modelId, provider)) { - const body = structuredClone(source.body) as Record; - body.model = parsed.modelId; + const body: Record = { ...structuredClone(source.body) as Record, model: parsed.modelId }; + if (isOAuth) prependClaudeIdentity(body); if (!Array.isArray(body.messages)) { throw new Error("validated Anthropic source messages missing"); } diff --git a/src/oauth/anthropic-routing.ts b/src/oauth/anthropic-routing.ts index b23c1bd78c1..ddfbe85031b 100644 --- a/src/oauth/anthropic-routing.ts +++ b/src/oauth/anthropic-routing.ts @@ -183,6 +183,7 @@ export function getAnthropicAccountHealthSnapshot( } export function clearAnthropicAccountCooldown(accountId: string): boolean { + for (const key of upstreamHealth.keys()) if (key.startsWith(`${accountId}\0`)) upstreamHealth.delete(key); return upstreamHealth.delete(accountId); } @@ -208,8 +209,19 @@ export function anthropicSessionAffinitySizeForTests(): number { return sessionAffinity.size; } -function isCooled(accountId: string, now: number): boolean { - return getAnthropicAccountHealthSnapshot(accountId, now) !== null; +/** + * The model family a model-scoped weekly limit names: a 429 whose representative claim is `seven_day_opus` spends + * only the account's Opus allowance, so it cools (account, "opus") and the account keeps serving its other models. + */ +export function anthropicModelFamily(modelId: string | null | undefined): string | undefined { + return /\b(opus|sonnet|haiku|fable)\b/i.exec(modelId ?? "")?.[1]?.toLowerCase(); +} + +const familyKey = (accountId: string, family: string) => `${accountId}\0${family}`; + +function isCooled(accountId: string, now: number, family?: string): boolean { + return getAnthropicAccountHealthSnapshot(accountId, now) !== null + || (family !== undefined && getAnthropicAccountHealthSnapshot(familyKey(accountId, family), now) !== null); } function fiveHourKnown(accountId: string): boolean { @@ -278,13 +290,13 @@ function isPoolCredentialUsable(accountId: string, now: number): boolean { setComboPoolEligibilityProbe((provider, now) => provider === PROVIDER && getEligibleAnthropicAccounts(now).length > 0); -export function getEligibleAnthropicAccounts(now = Date.now()): string[] { +export function getEligibleAnthropicAccounts(now = Date.now(), family?: string): string[] { const set = getAccountSet(PROVIDER); if (!set) return []; return set.accounts .filter(account => account.needsReauth !== true - && !isCooled(account.id, now) + && !isCooled(account.id, now, family) && isPoolCredentialUsable(account.id, now)) .map(account => account.id); } @@ -363,14 +375,16 @@ export function forgetAnthropicFailoverQuorum(): void { } /** Earliest remaining cooldown among cooled Anthropic accounts, for client Retry-After. */ -export function getAnthropicPoolRetryAfterSeconds(now = Date.now()): number | null { +export function getAnthropicPoolRetryAfterSeconds(now = Date.now(), family?: string): number | null { const set = getAccountSet(PROVIDER); if (!set) return null; let earliest: number | null = null; for (const account of set.accounts) { - const snap = getAnthropicAccountHealthSnapshot(account.id, now); - if (!snap?.cooldownUntil) continue; - if (earliest === null || snap.cooldownUntil < earliest) earliest = snap.cooldownUntil; + // An account serves again only once both its own and its family's cooldown are over. + const until = Math.max(getAnthropicAccountHealthSnapshot(account.id, now)?.cooldownUntil ?? 0, + family ? getAnthropicAccountHealthSnapshot(familyKey(account.id, family), now)?.cooldownUntil ?? 0 : 0); + if (!until) continue; + if (earliest === null || until < earliest) earliest = until; } if (earliest === null || earliest <= now) return null; return Math.max(1, Math.ceil((earliest - now) / 1000)); @@ -396,9 +410,9 @@ function compareScoredAccounts(a: ScoredAccount, b: ScoredAccount): number { return a.score - b.score || a.fiveHourTieBreak - b.fiveHourTieBreak; } -function pickLowestUsage(config: OcxConfig, excludeId: string | undefined, now: number): string | null { +function pickLowestUsage(config: OcxConfig, excludeId: string | undefined, now: number, family?: string): string | null { const window = anthropicQuotaWindow(anthropicAccountPoolConfig(config)); - const unfiltered = getEligibleAnthropicAccounts(now).filter(id => id !== excludeId); + const unfiltered = getEligibleAnthropicAccounts(now, family).filter(id => id !== excludeId); const available = window === "weekly" ? unfiltered.filter(id => !exhausted5h(id)) : unfiltered; const eligible = available.length > 0 ? available : unfiltered; if (eligible.length === 0) return null; @@ -467,16 +481,17 @@ function pickAlternateAnthropicAccount( config: OcxConfig, excludeId: string, now: number, + family?: string, ): string | null { const strategy = anthropicPoolStrategy(config); - const eligible = getEligibleAnthropicAccounts(now).filter(id => id !== excludeId); + const eligible = getEligibleAnthropicAccounts(now, family).filter(id => id !== excludeId); if (strategy === "round-robin") { return peekRoundRobinAccount(POOL_KEY_ANTHROPIC, eligible, stickyLimitForPool(config)); } if (strategy === "fill-first") { return pickNextFillFirstAnthropicAccount(config, excludeId, eligible); } - return pickLowestUsage(config, excludeId, now); + return pickLowestUsage(config, excludeId, now, family); } function pruneExpiredAffinity(now: number): void { @@ -529,8 +544,8 @@ function isActiveUnderFillFirstThreshold(config: OcxConfig, accountId: string): * Fill-first: keep eligible active under threshold; otherwise advance to the next * eligible id in stable sorted order after the current active (wrapping). */ -function pickFillFirstAnthropicAccount(config: OcxConfig, now: number): string | null { - const eligible = getEligibleAnthropicAccounts(now); +function pickFillFirstAnthropicAccount(config: OcxConfig, now: number, family?: string): string | null { + const eligible = getEligibleAnthropicAccounts(now, family); if (eligible.length === 0) return null; const set = getAccountSet(PROVIDER); @@ -557,12 +572,13 @@ function pickFillFirstAnthropicAccount(config: OcxConfig, now: number): string | function pickUnboundStrategyAccount( config: OcxConfig, now: number, + family?: string, ): { accountId: string; reason: "round-robin" | "fill-first" } | null { const strategy = anthropicPoolStrategy(config); if (strategy === "quota") return null; if (strategy === "round-robin") { - const eligible = getEligibleAnthropicAccounts(now); + const eligible = getEligibleAnthropicAccounts(now, family); const limit = stickyLimitForPool(config); const picked = peekRoundRobinAccount(POOL_KEY_ANTHROPIC, eligible, limit); if (!picked) return null; @@ -570,7 +586,7 @@ function pickUnboundStrategyAccount( } if (strategy === "fill-first") { - const picked = pickFillFirstAnthropicAccount(config, now); + const picked = pickFillFirstAnthropicAccount(config, now, family); if (!picked) return null; return { accountId: picked, reason: "fill-first" }; } @@ -586,7 +602,9 @@ export function resolveAnthropicAccountForSession( sessionKey: string | null | undefined, config: OcxConfig, now = Date.now(), + modelId?: string | null, ): AnthropicAccountSelection { + const family = anthropicModelFamily(modelId); pruneExpiredAffinity(now); const set = getAccountSet(PROVIDER); if (!set || set.accounts.length === 0) return { accountId: null, reason: "none" }; @@ -617,7 +635,7 @@ export function resolveAnthropicAccountForSession( const exhausted = [quota?.fiveHourPercent, quota?.weeklyPercent, quota?.monthlyPercent, ...(quota?.customWindows ?? []).map(window => window.percent)] .some(percent => typeof percent === "number" && percent >= 100); - if (!exhausted && getEligibleAnthropicAccounts(now).includes(chosen)) { + if (!exhausted && getEligibleAnthropicAccounts(now, family).includes(chosen)) { return { accountId: chosen, reason: "manual" }; } } @@ -626,13 +644,13 @@ export function resolveAnthropicAccountForSession( // Round-robin's pick is arbitrary, so a keyed session always takes its hash seat, ahead of the // in-process binding: warm and fresh processes agree, and a session moved off a spent seat // returns to it in every process once it recovers instead of alternating between processes. - const hashed = strategy === "round-robin" ? sessionHashAccount(key, getEligibleAnthropicAccounts(now)) : null; + const hashed = strategy === "round-robin" ? sessionHashAccount(key, getEligibleAnthropicAccounts(now, family)) : null; if (hashed) return { accountId: hashed, reason: sessionAffinity.get(key)?.accountId === hashed ? "affinity" : "hash" }; if (key) { const affined = sessionAffinity.get(key); if (affined && now - affined.lastUsedAt <= AFFINITY_IDLE_TTL_MS) { const stillThere = set.accounts.some(a => a.id === affined.accountId && a.needsReauth !== true); - if (stillThere && !isCooled(affined.accountId, now) && isPoolCredentialUsable(affined.accountId, now)) { + if (stillThere && !isCooled(affined.accountId, now, family) && isPoolCredentialUsable(affined.accountId, now)) { return { accountId: affined.accountId, reason: "affinity" }; } sessionAffinity.delete(key); @@ -644,21 +662,21 @@ export function resolveAnthropicAccountForSession( // Round-robin only when there is a real new-session key (or active is unusable). if (!key && (strategy === "round-robin" || strategy === "fill-first")) { const activeOk = set.accounts.some(a => a.id === set.activeAccountId && a.needsReauth !== true) - && !isCooled(set.activeAccountId, now) + && !isCooled(set.activeAccountId, now, family) && isPoolCredentialUsable(set.activeAccountId, now); if (activeOk) { return { accountId: set.activeAccountId, reason: "active" }; } } - const strategyPick = pickUnboundStrategyAccount(config, now); + const strategyPick = pickUnboundStrategyAccount(config, now, family); if (strategyPick) { return { accountId: strategyPick.accountId, reason: strategyPick.reason }; } const threshold = anthropicAutoSwitchThreshold(config); const activeOk = set.accounts.some(a => a.id === set.activeAccountId && a.needsReauth !== true) - && !isCooled(set.activeAccountId, now) + && !isCooled(set.activeAccountId, now, family) && isPoolCredentialUsable(set.activeAccountId, now); let accountId: string | null = null; @@ -673,7 +691,7 @@ export function resolveAnthropicAccountForSession( accountId = set.activeAccountId; reason = "active"; } else { - const picked = pickLowestUsage(config, undefined, now); + const picked = pickLowestUsage(config, undefined, now, family); if (picked) { accountId = picked; reason = activeOk && picked === set.activeAccountId ? "active" : "lowest-usage"; @@ -686,7 +704,7 @@ export function resolveAnthropicAccountForSession( accountId = set.activeAccountId; reason = "active"; } else { - const picked = pickLowestUsage(config, set.activeAccountId, now); + const picked = pickLowestUsage(config, set.activeAccountId, now, family); if (picked) { accountId = picked; reason = "only-eligible"; @@ -694,7 +712,7 @@ export function resolveAnthropicAccountForSession( } if (!accountId) { - const anyCooled = set.accounts.some(a => isCooled(a.id, now)); + const anyCooled = set.accounts.some(a => isCooled(a.id, now, family)); return { accountId: null, reason: anyCooled ? "all-cooled" : "none" }; } @@ -734,6 +752,7 @@ export function rotateAnthropicAccountOn429( sessionKey?: string | null, now = Date.now(), rateLimitHeaders?: AnthropicRateLimitHeaders | null, + modelId?: string | null, ): string | null { // 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 @@ -741,21 +760,39 @@ export function rotateAnthropicAccountOn429( // just rate-limited is a different thing: it only ever runs after a refusal, and stranding a // 429 while a second logged-in account sits idle is a defect, not a configuration choice. // Presence is the activation rule, the same one an apiKeyPool of two keys already uses. - if (!isAnthropicAccountPoolEnabled(config) && !hasAnthropicFailoverQuorum(now)) return null; - // Retry-After first: it is the header written FOR this decision. The rejected window's // reset is the fallback, because a 429 that omits Retry-After still carries it -- and // without that fallback such a refusal cools for the 60s default and the exhausted // account is back in the rotation a minute later. + // A model-scoped weekly limit (claim `seven_day_` matching the request's model) cools only that family on + // the account; every other 429 cools the whole account, as before. Its reset is the unified one. + const header = (name: string) => rateLimitHeaders?.get(`anthropic-ratelimit-unified-${name}`)?.trim() || undefined; + const claim = header("representative-claim"); + const requestFamily = anthropicModelFamily(modelId); + const family = requestFamily !== undefined && claim === `seven_day_${requestFamily}` ? requestFamily : undefined; const parsedRetry = parseRetryAfterMs(retryAfterHeader, now); - const resetDerived = parsedRetry === undefined ? parseRateLimitResetMs(rateLimitHeaders, now) : undefined; + const resetDerived = parsedRetry !== undefined ? undefined + : family ? delayUntil(Number(header("reset")) * 1000, now) : parseRateLimitResetMs(rateLimitHeaders, now); const cooldownMs = parsedRetry ?? resetDerived ?? DEFAULT_COOLDOWN_MS; - upstreamHealth.set(failedAccountId, { - cooldownUntil: now + cooldownMs, - cooldownSource: parsedRetry !== undefined - ? "retry-after" - : resetDerived !== undefined ? "reset-derived" : "default", + 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 + // on the account. A rejected window, or a 429 with no unified status at all, still cools as before. + const status = header("status"); + const limited = status === undefined || [status, header("5h-status"), header("7d-status")].includes("rejected"); + const failover = limited && (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 ?? "-"}` + + ` retry-after=${retryAfterHeader?.trim() || "-"} ${unified.join(" ") || "unified=-"}` + + (failover + ? ` cooldown=${Math.ceil(cooldownMs / 1000)}s until ${new Date(now + cooldownMs).toISOString()} (${cooldownSource}) scope=${family ?? "account"}` + : ` cooldown=none (${limited ? "no failover pool" : "request refused, account not limited"})`)); + if (!failover) return null; + upstreamHealth.set(family ? familyKey(failedAccountId, family) : failedAccountId, { cooldownUntil: now + cooldownMs, cooldownSource }); sweepExpiredOnWrite(now); // Unbind only the session that hit the 429; others on the account move on their own next call. const key = normalizeAffinityComponent(sessionKey); @@ -772,13 +809,18 @@ export function rotateAnthropicAccountOn429( // because those dormant values remain in config. The quota picker is the neutral // recovery policy already used by the default strategy. const hashRunnerUp = isAnthropicAccountPoolEnabled(config) && anthropicPoolStrategy(config) === "round-robin" - ? sessionHashAccount(key, getEligibleAnthropicAccounts(now).filter(id => id !== failedAccountId)) + ? sessionHashAccount(key, getEligibleAnthropicAccounts(now, requestFamily).filter(id => id !== failedAccountId)) : null; const next = isAnthropicAccountPoolEnabled(config) - ? hashRunnerUp ?? pickAlternateAnthropicAccount(config, failedAccountId, now) - : pickLowestUsage(config, failedAccountId, now); + ? hashRunnerUp ?? pickAlternateAnthropicAccount(config, failedAccountId, now, requestFamily) + : pickLowestUsage(config, failedAccountId, now, requestFamily); if (!next) { - console.warn("[anthropic-pool] all eligible Anthropic OAuth accounts are in cooldown; returning 429"); + // 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" + + ` (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; } diff --git a/src/oauth/anthropic.ts b/src/oauth/anthropic.ts index d488b6fdb60..3885d67250a 100644 --- a/src/oauth/anthropic.ts +++ b/src/oauth/anthropic.ts @@ -23,6 +23,23 @@ const CODE_MODE_TIMEOUT_MS = 10 * 60_000; // ── OAuth-request requirements applied by the anthropic adapter when authMode==="oauth" ── export const ANTHROPIC_OAUTH_BETA = "claude-code-20250219,oauth-2025-04-20"; export const CLAUDE_CODE_SYSTEM_INSTRUCTION = "You are a Claude agent, built on Anthropic's Claude Agent SDK."; + +const CLAUDE_IDENTITY_LINE = /^You are (Claude Code, Anthropic's official CLI for Claude|a Claude agent, built on Anthropic's Claude Agent SDK)/; + +/** + * OAuth (subscription) credentials expect a Claude Code identity system block. The translated + * path always adds it; a replayed source body from a non-Claude-Code client (e.g. Hermes) has + * none, and upstream answers it 429 "Error". Claude Code's own bodies already carry the line + * (often after its billing-header block), so any identified block counts and nothing is doubled. + */ +export function prependClaudeIdentity(body: Record): void { + const system = typeof body.system === "string" + ? (body.system ? [{ type: "text", text: body.system }] : []) + : Array.isArray(body.system) ? body.system : []; + if (system.some(block => typeof block?.text === "string" && CLAUDE_IDENTITY_LINE.test(block.text.trimStart()))) return; + body.system = [{ type: "text", text: CLAUDE_CODE_SYSTEM_INSTRUCTION }, ...system]; +} + const CLAUDE_TOOL_PREFIX = "custom_"; const ANTHROPIC_BUILTIN_TOOLS = new Set(["web_search", "code_execution", "text_editor", "computer"]); diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index 9b5a5d9df06..d9ba0bdddc4 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -85,6 +85,7 @@ import { captureOAuthAccountSelection } from "../oauth/store"; import { anthropicSessionKeyFromParts, getAnthropicPoolAccessSnapshot, + anthropicModelFamily, getAnthropicPoolRetryAfterSeconds, isAnthropicAccountPoolEnabled, promoteAnthropicActiveAccount, @@ -1769,10 +1770,10 @@ export async function handleClaudeCountTokens( : null, promptCacheKeyIsSharedCohort: translated.cacheKeySource === "system", }); - const selection = resolveAnthropicAccountForSession(sessionKey, config); + const selection = resolveAnthropicAccountForSession(sessionKey, config, Date.now(), route.modelId); if (!selection.accountId) { if (selection.reason === "all-cooled") { - const retryAfter = getAnthropicPoolRetryAfterSeconds(); + const retryAfter = getAnthropicPoolRetryAfterSeconds(Date.now(), anthropicModelFamily(route.modelId)); const response = anthropicErrorResponse( 429, "All Anthropic OAuth accounts are temporarily rate-limited", diff --git a/src/server/responses/adapter-continuation.ts b/src/server/responses/adapter-continuation.ts index 37c0c868c28..19d56b6711a 100644 --- a/src/server/responses/adapter-continuation.ts +++ b/src/server/responses/adapter-continuation.ts @@ -397,6 +397,7 @@ export function createAdapterContinuations( anthropicSessionKey, Date.now(), response.headers, + route.modelId, ); 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 3f098095fd4..1c4c0592aa6 100644 --- a/src/server/responses/adapter-dispatch.ts +++ b/src/server/responses/adapter-dispatch.ts @@ -876,6 +876,7 @@ export async function prepareAdapterExchange( anthropicSessionKey, Date.now(), upstreamResponse.headers, + route.modelId, ); if (!nextAccountId) break; try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ } diff --git a/src/server/responses/request-transport.ts b/src/server/responses/request-transport.ts index 853e1a61266..8aca8e7f8c6 100644 --- a/src/server/responses/request-transport.ts +++ b/src/server/responses/request-transport.ts @@ -17,6 +17,7 @@ import { formatAnthropicProviderForLog, anthropicSessionKeyFromParts, resolveAnthropicAccountForSession, + anthropicModelFamily, getAnthropicPoolRetryAfterSeconds, hasAnthropicFailoverQuorum, } from "../../oauth/anthropic-routing"; @@ -534,10 +535,10 @@ export async function prepareResponsesTransport( } else genericFailoverAccountId = admitted.accountId; if (hasPassiveAccountQuota(route.providerName)) passiveQuotaWriterGeneration = captureConfigGeneration(); } else if (route.providerName === "anthropic" && isAnthropicAccountPoolEnabled(config)) { - const selection = resolveAnthropicAccountForSession(anthropicSessionKey, config); + const selection = resolveAnthropicAccountForSession(anthropicSessionKey, config, Date.now(), route.modelId); if (!selection.accountId) { if (selection.reason === "all-cooled") { - const retryAfterSec = getAnthropicPoolRetryAfterSeconds(); + const retryAfterSec = getAnthropicPoolRetryAfterSeconds(Date.now(), anthropicModelFamily(route.modelId)); return formatErrorResponse( 429, "rate_limit_error", diff --git a/src/server/responses/sidecar-execution.ts b/src/server/responses/sidecar-execution.ts index dcfd225dd66..4cca928cf4b 100644 --- a/src/server/responses/sidecar-execution.ts +++ b/src/server/responses/sidecar-execution.ts @@ -243,6 +243,7 @@ export async function executeResponsesSidecars( anthropicSessionKey, Date.now(), responseHeaders, + route.modelId, ); if (!nextAccountId) { hop.permit?.release(); diff --git a/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts index f1ad70542ea..f73c04dc7b9 100644 --- a/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +++ b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts @@ -4,10 +4,13 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { + anthropicModelFamily, clearAnthropicAccountCooldown, clearAnthropicAccountPoolState, forgetAnthropicFailoverQuorum, getAnthropicAccountHealthSnapshot, + getAnthropicPoolRetryAfterSeconds, + getEligibleAnthropicAccounts, rotateAnthropicAccountOn429, resetAnthropicRoutingForManualSelection, resolveAnthropicAccountForSession, @@ -103,6 +106,75 @@ function drainedFiveHour(resetEpochSeconds: number): Headers { }); } +describe("a model-scoped weekly 429 cools only that model family", () => { + /** A seven_day_opus refusal: the account's Opus allowance is spent, its other models are not. */ + const opusWeekly = (resetEpochSeconds: number) => new Headers({ + "anthropic-ratelimit-unified-status": "rejected", + "anthropic-ratelimit-unified-representative-claim": "seven_day_opus", + "anthropic-ratelimit-unified-reset": String(resetEpochSeconds), + "anthropic-ratelimit-unified-5h-status": "allowed", + "anthropic-ratelimit-unified-7d-status": "allowed", + }); + + test("Opus cools per account, Sonnet keeps the account, and every 429 logs its limit headers", async () => { + const start = Date.now(); + const ids = await seed(2); + const reset = Math.floor(start / 1000) + 3 * 86_400; + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, "s1", start, opusWeekly(reset), "claude-opus-5")).toBe(ids[1]!); + expect(warn.mock.calls.map(c => String(c[0])).find(l => l.startsWith("[anthropic-pool] 429 on "))).toEndWith( + " model=claude-opus-5 retry-after=- 5h-status=allowed 7d-status=allowed representative-claim=seven_day_opus" + + ` reset=${reset} status=rejected cooldown=${3 * 86_400}s until ${new Date(reset * 1000).toISOString()}` + + " (reset-derived) scope=opus"); + } finally { warn.mockRestore(); } + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)).toBeNull(); + expect(getEligibleAnthropicAccounts(start, "opus")).toEqual([ids[1]!]); + expect(getEligibleAnthropicAccounts(start, "sonnet")).toEqual(ids); + + // Both accounts out of Opus: an Opus request is refused with the family's reset, a Sonnet one still routes. + rotateAnthropicAccountOn429(poolEnabled(), ids[1]!, null, "s2", start, opusWeekly(reset), "claude-opus-5"); + expect(resolveAnthropicAccountForSession("s3", poolEnabled(), start, "claude-opus-5").reason).toBe("all-cooled"); + expect(getAnthropicPoolRetryAfterSeconds(start, anthropicModelFamily("claude-opus-5"))).toBe(3 * 86_400); + expect(resolveAnthropicAccountForSession("s4", poolEnabled(), start, "claude-sonnet-5-5").accountId).not.toBeNull(); + clearAnthropicAccountCooldown(ids[0]!); + expect(getEligibleAnthropicAccounts(start, "opus")).toEqual([ids[0]!]); + }); + + test("a five-hour claim on an Opus request still cools the whole account", async () => { + const start = Date.now(); + const ids = await seed(2); + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, "120", null, start, + new Headers({ "anthropic-ratelimit-unified-representative-claim": "five_hour" }), "claude-opus-5"); + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)?.cooldownUntil).toBe(start + 120_000); + expect(getEligibleAnthropicAccounts(start, "sonnet")).toEqual([ids[1]!]); + }); +}); + +describe("a request-shape 429 does not cool the account", () => { + test("an allowed unified status fails only the request, while a header-less 429 still fails over", async () => { + const start = Date.now(); + const ids = await seed(2); + const allowed = new Headers({ + "anthropic-ratelimit-unified-status": "allowed", + "anthropic-ratelimit-unified-5h-status": "allowed", + "anthropic-ratelimit-unified-7d-status": "allowed", + }); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, "30", "s1", start, allowed, "claude-opus-5")).toBeNull(); + expect(rotateAnthropicAccountOn429(poolEnabled(), ids[1]!, null, "s2", start, allowed, "claude-sonnet-5-5")).toBeNull(); + expect(warn.mock.calls.map(c => String(c[0])).filter(l => l.startsWith("[anthropic-pool] 429 on ")) + .every(l => l.endsWith(" cooldown=none (request refused, account not limited)"))).toBe(true); + } finally { warn.mockRestore(); } + expect(ids.map(id => getAnthropicAccountHealthSnapshot(id, start))).toEqual([null, null]); + expect(getEligibleAnthropicAccounts(start, "opus")).toEqual(ids); + // No unified status at all is not evidence of a refusal: the legacy cooldown and failover still apply. + expect(rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, "s3", start, new Headers(), "claude-opus-5")).toBe(ids[1]!); + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)?.cooldownUntil).toBeGreaterThan(start); + }); +}); + describe("Anthropic cooldown honours the stated window", () => { test("a multi-hour Retry-After is not truncated to the guessed-backoff ceiling", async () => { const start = Date.now(); @@ -168,10 +240,9 @@ describe("Anthropic cooldown honours the stated window", () => { "anthropic-ratelimit-unified-5h-reset": String(Math.floor((start + 3 * 60 * 60_000) / 1000)), "anthropic-ratelimit-unified-5h-utilization": "0.04", }); + // A 429 under an allowed status is not a limit at all: the account is not cooled (see the request-shape case). rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, null, start, healthy); - const health = getAnthropicAccountHealthSnapshot(ids[0]!, start); - expect(health?.cooldownUntil).toBe(start + 60_000); - expect(health?.cooldownSource).toBe("default"); + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)).toBeNull(); }); test("both windows rejected cools until the LAST one reopens", async () => { diff --git a/tests/adapters/anthropic/anthropic-replay-oauth-identity.test.ts b/tests/adapters/anthropic/anthropic-replay-oauth-identity.test.ts new file mode 100644 index 00000000000..8fa19b1a3be --- /dev/null +++ b/tests/adapters/anthropic/anthropic-replay-oauth-identity.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, test } from "bun:test"; +import { createAnthropicAdapter as createAnthropicAdapterProduction } from "../../../src/adapters/anthropic"; +import { CLAUDE_CODE_SYSTEM_INSTRUCTION } from "../../../src/oauth/anthropic"; +import { createTestTranslatorBudget, withTestTranslatorBudget } from "../../helpers/translator-budget"; + +const IDENTITY = { type: "text", text: CLAUDE_CODE_SYSTEM_INSTRUCTION }; +const messages = [{ role: "user", content: "Reply with the word ok." }]; + +async function replay(system: unknown, authMode?: "oauth") { + const adapter = withTestTranslatorBudget(createAnthropicAdapterProduction({ + adapter: "anthropic", baseUrl: "https://api.anthropic.com", apiKey: "key", ...(authMode ? { authMode } : {}), + })); + const source = { model: "claude-opus-4-1", max_tokens: 16, ...(system === undefined ? {} : { system }), messages }; + const request = await adapter.buildRequest({ + modelId: "claude-opus-4-1", + context: { messages: [{ role: "user", content: "Reply with the word ok." }] }, + stream: false, + options: { maxOutputTokens: 16 }, + }, { headers: new Headers(), translatorBudget: createTestTranslatorBudget(), anthropicMessagesSource: { body: source, headers: {} } }); + expect(request.anthropicSourceReplay).toBe(true); + return JSON.parse(request.body); +} + +describe("OAuth source replay carries the Claude identity block (ANDREW-CLAUDE-429)", () => { + test("a Hermes-style string system gets the identity block first", async () => { + expect(await replay("You are Hermes Agent.", "oauth")).toEqual({ + model: "claude-opus-4-1", max_tokens: 16, messages, + system: [IDENTITY, { type: "text", text: "You are Hermes Agent." }], + }); + }); + + test("an array system keeps its blocks after the identity block", async () => { + const block = { type: "text", text: "You are Hermes Agent.", cache_control: { type: "ephemeral" } }; + expect((await replay([block], "oauth")).system).toEqual([IDENTITY, block]); + }); + + test("no system becomes the identity block alone", async () => { + expect((await replay(undefined, "oauth")).system).toEqual([IDENTITY]); + }); + + test("an already-identified Claude Code system is not doubled", async () => { + const cc = [ + { type: "text", text: "x-anthropic-billing-header: cc_version=2.1.280" }, + { type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude." }, + { type: "text", text: "project rules" }, + ]; + expect((await replay(cc, "oauth")).system).toEqual(cc); + const sdk = [IDENTITY, { type: "text", text: "rules" }]; + expect((await replay(sdk, "oauth")).system).toEqual(sdk); + }); + + test("an API-key replay stays byte for byte", async () => { + expect((await replay("You are Hermes Agent.")).system).toBe("You are Hermes Agent."); + }); +}); diff --git a/tests/claude-integration/claude-messages-endpoint.test.ts b/tests/claude-integration/claude-messages-endpoint.test.ts index 2eafba2bc00..7f10f77fe5c 100644 --- a/tests/claude-integration/claude-messages-endpoint.test.ts +++ b/tests/claude-integration/claude-messages-endpoint.test.ts @@ -1672,7 +1672,7 @@ test("mapped combo count_tokens uses exact canonical Anthropic counting", async } as OcxConfig); const source = { model: "claude-opus-5", - system: [{ type: "text", text: "system", cache_control: { type: "ephemeral", ttl: "1h" } }], + system: [{ type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude.", cache_control: { type: "ephemeral", ttl: "1h" } }], messages: [{ role: "user", content: [{ type: "text", text: "count this" }] }], tools: [{ name: "Read", description: "read", input_schema: { type: "object", properties: {} } }], metadata: { user_id: "count-session" }, @@ -2701,7 +2701,7 @@ function routedAnthropicSource(): Record { max_tokens: 64000, stream: true, system: [ - { type: "text", text: "identity" }, + { type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude." }, { type: "text", text: "policy", cache_control: { type: "ephemeral", ttl: "1h" } }, { type: "text", text: "tools", cache_control: { type: "ephemeral" } }, ], diff --git a/tests/claude-integration/claude-opus-output-limit.test.ts b/tests/claude-integration/claude-opus-output-limit.test.ts index 2c6d6ced40a..97bd64461eb 100644 --- a/tests/claude-integration/claude-opus-output-limit.test.ts +++ b/tests/claude-integration/claude-opus-output-limit.test.ts @@ -42,7 +42,7 @@ function source(maxTokens = 128_000, serverTool = false) { output_config: { effort: "medium" }, context_management: { edits: [{ type: "clear_thinking_20251015", keep: "all" }] }, metadata: { user_id: "synthetic-replay-test" }, - system: [{ type: "text", text: "Synthetic system", cache_control: { type: "ephemeral" } }], + system: [{ type: "text", text: "You are Claude Code, Anthropic's official CLI for Claude.", cache_control: { type: "ephemeral" } }], messages: [ { role: "user", content: [{ type: "text", text: "Synthetic prompt", cache_control: { type: "ephemeral" } }] }, { role: "system", content: "Synthetic mid-conversation instruction" }, diff --git a/tests/server/agentradar-account-pin-e2e.test.ts b/tests/server/agentradar-account-pin-e2e.test.ts index 59198fd1774..04a7b96bdca 100644 --- a/tests/server/agentradar-account-pin-e2e.test.ts +++ b/tests/server/agentradar-account-pin-e2e.test.ts @@ -167,7 +167,7 @@ test("an AgentRadar account pin serves exactly its own stored account (pin.check codexAccounts: [1, 2].map(n => ({ id: `acct${n}`, email: `c${n}@example.invalid`, isMain: false, chatgptAccountId: `cga${n}` })), }); const rotations = () => ocx.log.split("[anthropic-pool] credential denial on").length - 1; - const failovers429 = () => ocx.log.split("[anthropic-pool] 429 on").length - 1; + const failovers429 = () => ocx.log.split("; failing over to").length - 1; try { // Claude: unpinned control serves the active account; a pin serves exactly its own, both ways, and names it. let r = await msg(ocx);