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.17"
version = "2.65.0-vadymhimself.18"
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.17",
"version": "2.65.0-vadymhimself.18",
"identifier": "com.opencodex.desktop",
"build": {
"frontendDist": "../ui",
Expand Down
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.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",
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string, unknown>;
body.model = parsed.modelId;
const body: Record<string, unknown> = { ...structuredClone(source.body) as Record<string, unknown>, model: parsed.modelId };
if (isOAuth) prependClaudeIdentity(body);
if (!Array.isArray(body.messages)) {
throw new Error("validated Anthropic source messages missing");
}
Expand Down
116 changes: 79 additions & 37 deletions src/oauth/anthropic-routing.ts

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions src/oauth/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>): 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"]);

Expand Down
5 changes: 3 additions & 2 deletions src/server/claude-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ import { captureOAuthAccountSelection } from "../oauth/store";
import {
anthropicSessionKeyFromParts,
getAnthropicPoolAccessSnapshot,
anthropicModelFamily,
getAnthropicPoolRetryAfterSeconds,
isAnthropicAccountPoolEnabled,
promoteAnthropicActiveAccount,
Expand Down Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/server/responses/adapter-continuation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */ }
Expand Down
1 change: 1 addition & 0 deletions src/server/responses/adapter-dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */ }
Expand Down
5 changes: 3 additions & 2 deletions src/server/responses/request-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
formatAnthropicProviderForLog,
anthropicSessionKeyFromParts,
resolveAnthropicAccountForSession,
anthropicModelFamily,
getAnthropicPoolRetryAfterSeconds,
hasAnthropicFailoverQuorum,
} from "../../oauth/anthropic-routing";
Expand Down Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src/server/responses/sidecar-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ export async function executeResponsesSidecars(
anthropicSessionKey,
Date.now(),
responseHeaders,
route.modelId,
);
if (!nextAccountId) {
hop.permit?.release();
Expand Down
77 changes: 74 additions & 3 deletions tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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 () => {
Expand Down
55 changes: 55 additions & 0 deletions tests/adapters/anthropic/anthropic-replay-oauth-identity.test.ts
Original file line number Diff line number Diff line change
@@ -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.");
});
});
4 changes: 2 additions & 2 deletions tests/claude-integration/claude-messages-endpoint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
Expand Down Expand Up @@ -2701,7 +2701,7 @@ function routedAnthropicSource(): Record<string, unknown> {
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" } },
],
Expand Down
2 changes: 1 addition & 1 deletion tests/claude-integration/claude-opus-output-limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
Expand Down
2 changes: 1 addition & 1 deletion tests/server/agentradar-account-pin-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading