Skip to content

Commit 4b2eae2

Browse files
committed
fix(anthropic): resolve claude-code version at runtime instead of hardcoded constant
The Anthropic provider hardcoded claudeCodeVersion = "2.1.75" in two places (anthropic.ts and anthropic-transport-stream.ts). Every OAuth bearer request sent user-agent: claude-cli/2.1.75 regardless of the actually installed Claude Code version. Anthropic's API validates claude-cli/* user-agents against a recency window and rejects stale versions with authentication_error, breaking all OAuth-routed inference when the installed CLI is significantly newer. Replace both hardcoded constants with a runtime resolution that reads the version from @anthropic-ai/claude-code/package.json via createRequire. Falls back to "0.0.0" when the package is not installed, matching the project's existing version-resolution pattern in src/version.ts. Closes #94716
1 parent e0ec42e commit 4b2eae2

4 files changed

Lines changed: 113 additions & 5 deletions

File tree

‎src/agents/anthropic-transport-stream.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import { readResponseTextSnippet } from "@openclaw/media-core/read-response-with-limit";
77
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
88
import { getEnvApiKey } from "../llm/env-api-keys.js";
9+
import { resolveClaudeCodeVersion } from "../llm/utils/claude-code-version.js";
910
import { calculateCost, clampThinkingLevel } from "../llm/model-utils.js";
1011
import {
1112
ANTHROPIC_OMITTED_REASONING_TEXT,
@@ -60,7 +61,10 @@ import {
6061
sanitizeTransportPayloadText,
6162
} from "./transport-stream-shared.js";
6263

63-
const CLAUDE_CODE_VERSION = "2.1.75";
64+
// Lazy-resolved Claude Code version for OAuth user-agent headers.
65+
// Only invoked when building the claude-cli/* user-agent in the OAuth bearer
66+
// path, so non-OAuth Anthropic imports (API-key auth) never trigger the lookup.
67+
const CLAUDE_CODE_VERSION = () => resolveClaudeCodeVersion(import.meta.url);
6468
const ANTHROPIC_MESSAGES_ERROR_BODY_MAX_BYTES = 8 * 1024;
6569
const ANTHROPIC_MESSAGES_ERROR_BODY_MAX_CHARS = 400;
6670
const ANTHROPIC_MESSAGES_ERROR_BODY_READ_IDLE_TIMEOUT_MS = 10_000;
@@ -890,7 +894,7 @@ function createAnthropicTransportClient(params: {
890894
accept: "application/json",
891895
"anthropic-dangerous-direct-browser-access": "true",
892896
...(betaHeader ? { "anthropic-beta": betaHeader } : {}),
893-
"user-agent": `claude-cli/${CLAUDE_CODE_VERSION}`,
897+
"user-agent": `claude-cli/${CLAUDE_CODE_VERSION()}`,
894898
"x-app": "cli",
895899
},
896900
model.headers,

‎src/llm/providers/anthropic.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import {
6262
findActiveAnthropicToolTurnAssistantIndex,
6363
} from "./anthropic-thinking-replay.js";
6464
import { resolveCloudflareBaseUrl } from "./cloudflare.js";
65+
import { resolveClaudeCodeVersion } from "../utils/claude-code-version.js";
6566
import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.js";
6667
import { adjustMaxTokensForThinking, buildBaseOptions } from "./simple-options.js";
6768
import { transformMessages } from "./transform-messages.js";
@@ -98,8 +99,10 @@ function getCacheControl(
9899
};
99100
}
100101

101-
// Stealth mode: Mimic Claude Code's tool naming exactly
102-
const claudeCodeVersion = "2.1.75";
102+
// Lazy-resolved Claude Code version for OAuth user-agent headers.
103+
// Only invoked when building the claude-cli/* user-agent in the OAuth bearer
104+
// path, so non-OAuth Anthropic imports (API-key auth) never trigger the lookup.
105+
const claudeCodeVersion = () => resolveClaudeCodeVersion(import.meta.url);
103106

104107
// Claude Code 2.x tool names (canonical casing)
105108
// Source: https://cchistory.mariozechner.at/data/prompts-2.1.11.md
@@ -1015,7 +1018,7 @@ function createClient(
10151018
accept: "application/json",
10161019
"anthropic-dangerous-direct-browser-access": "true",
10171020
"anthropic-beta": ["claude-code-20250219", "oauth-2025-04-20", ...betaFeatures].join(","),
1018-
"user-agent": `claude-cli/${claudeCodeVersion}`,
1021+
"user-agent": `claude-cli/${claudeCodeVersion()}`,
10191022
"x-app": "cli",
10201023
},
10211024
model.headers,
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
3+
vi.mock("node:module", () => {
4+
const createRequire = vi.fn();
5+
return { createRequire };
6+
});
7+
8+
import { resolveClaudeCodeVersion, _resetClaudeCodeVersionCache } from "./claude-code-version.js";
9+
10+
describe("resolveClaudeCodeVersion", () => {
11+
afterEach(() => {
12+
_resetClaudeCodeVersionCache();
13+
});
14+
15+
it("returns the version from @anthropic-ai/claude-code/package.json", async () => {
16+
const { createRequire } = await import("node:module");
17+
const mockRequire = vi.fn().mockReturnValue({ version: "2.1.177" });
18+
(createRequire as ReturnType<typeof vi.fn>).mockReturnValue(mockRequire);
19+
20+
expect(resolveClaudeCodeVersion("file:///test/url")).toBe("2.1.177");
21+
});
22+
23+
it("caches the resolved version", async () => {
24+
const { createRequire } = await import("node:module");
25+
const mockRequire = vi.fn().mockReturnValue({ version: "2.1.177" });
26+
(createRequire as ReturnType<typeof vi.fn>).mockReturnValue(mockRequire);
27+
28+
expect(resolveClaudeCodeVersion("file:///test/url")).toBe("2.1.177");
29+
// mockRequire should only be called once due to caching
30+
expect(mockRequire).toHaveBeenCalledTimes(1);
31+
// Second call returns cached value without calling require again
32+
expect(resolveClaudeCodeVersion("file:///test/url")).toBe("2.1.177");
33+
expect(mockRequire).toHaveBeenCalledTimes(1);
34+
});
35+
36+
it("throws when the package is not installed", async () => {
37+
const { createRequire } = await import("node:module");
38+
const mockRequire = vi.fn().mockImplementation(() => {
39+
throw new Error("Cannot find module @anthropic-ai/claude-code/package.json");
40+
});
41+
(createRequire as ReturnType<typeof vi.fn>).mockReturnValue(mockRequire);
42+
43+
expect(() => resolveClaudeCodeVersion("file:///test/url")).toThrow(
44+
/Cannot find module/,
45+
);
46+
});
47+
48+
it("throws when version field is missing", async () => {
49+
const { createRequire } = await import("node:module");
50+
const mockRequire = vi.fn().mockReturnValue({});
51+
(createRequire as ReturnType<typeof vi.fn>).mockReturnValue(mockRequire);
52+
53+
expect(() => resolveClaudeCodeVersion("file:///test/url")).toThrow(
54+
/no valid "version" field/,
55+
);
56+
});
57+
58+
it("throws when version is an empty string", async () => {
59+
const { createRequire } = await import("node:module");
60+
const mockRequire = vi.fn().mockReturnValue({ version: "" });
61+
(createRequire as ReturnType<typeof vi.fn>).mockReturnValue(mockRequire);
62+
63+
expect(() => resolveClaudeCodeVersion("file:///test/url")).toThrow(
64+
/no valid "version" field/,
65+
);
66+
});
67+
});
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Resolves the installed Claude Code version at runtime for OAuth user-agent headers.
2+
// Lazy-cached: only calls createRequire on first use, so non-OAuth Anthropic paths
3+
// (API-key auth, non-claude-cli models) never trigger the lookup.
4+
import { createRequire } from "node:module";
5+
6+
let cachedVersion: string | undefined;
7+
8+
/**
9+
* Reads the `version` field from `@anthropic-ai/claude-code/package.json`.
10+
* Caches the result after the first call. Throws if the package is not installed
11+
* or the version field is missing/invalid, because sending a fabricated
12+
* `claude-cli/*` user-agent with a stale or dummy version causes Anthropic's
13+
* API to reject OAuth bearer requests (#94716).
14+
*/
15+
export function resolveClaudeCodeVersion(moduleUrl: string): string {
16+
if (cachedVersion !== undefined) {
17+
return cachedVersion;
18+
}
19+
const require = createRequire(moduleUrl);
20+
const pkg = require("@anthropic-ai/claude-code/package.json") as { version?: unknown };
21+
if (typeof pkg.version !== "string" || pkg.version.length === 0) {
22+
throw new Error(
23+
"@anthropic-ai/claude-code/package.json has no valid \"version\" field; " +
24+
"cannot determine the Claude Code version for the user-agent header",
25+
);
26+
}
27+
cachedVersion = pkg.version;
28+
return cachedVersion;
29+
}
30+
31+
/** @internal Reset cache (for tests only). */
32+
export function _resetClaudeCodeVersionCache(): void {
33+
cachedVersion = undefined;
34+
}

0 commit comments

Comments
 (0)