import { test } from "node:test"; import assert from "node:assert/strict"; import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { FAKE_KEY, errorTurn, startFakeAnthropic, textTurn, toolTurn, } from "../../testing/llm/fakeAnthropic.mjs"; import { AnthropicClient, AnthropicError, ApiKeyError, CancelledError, backoffMs, isClaudeModel, isStrictModel, prepareBody, readApiKey, redact, textOf, } from "./anthropic"; import { Meter } from "./meter"; const noSleep = async () => {}; async function keyFile(content: string, mode: number) { const dir = await mkdtemp(path.join(os.tmpdir(), "llm-key-")); const file = path.join(dir, "anthropic.env"); await writeFile(file, content); await chmod(file, mode); return { file, done: () => rm(dir, { recursive: true, force: true }) }; } test("isClaudeModel / isStrictModel", () => { assert.equal(isClaudeModel("claude-sonnet-5-5"), true); assert.equal(isClaudeModel("qwen3:8b"), false); assert.equal(isStrictModel("claude-sonnet-5-5"), true); assert.equal(isStrictModel("claude-opus-5-5"), true); assert.equal(isStrictModel("claude-sonnet-5"), false); assert.equal(isStrictModel("claude-haiku-4-5"), false); }); test("readApiKey: the environment first", () => { assert.equal(readApiKey({ env: { ANTHROPIC_API_KEY: " k-from-env " }, apiKeyFile: "/nonexistent" }), "k-from-env"); }); test("readApiKey: a mode-600 file, quotes and an export prefix tolerated", async () => { const f = await keyFile(`# comment\nexport ANTHROPIC_API_KEY="${FAKE_KEY}"\n`, 0o600); try { assert.equal(readApiKey({ env: {}, apiKeyFile: f.file }), FAKE_KEY); } finally { await f.done(); } }); test("readApiKey: refused when group or others can read the file; missing file; no line; nothing configured", async () => { const open = await keyFile(`ANTHROPIC_API_KEY=${FAKE_KEY}\n`, 0o644); const noLine = await keyFile(`OTHER=1\n`, 0o600); try { assert.throws(() => readApiKey({ env: {}, apiKeyFile: open.file }), (e: Error) => { assert.ok(e instanceof ApiKeyError); assert.match(e.message, /chmod 600/); assert.ok(!e.message.includes(FAKE_KEY)); return true; }); assert.throws(() => readApiKey({ env: {}, apiKeyFile: noLine.file }), /has no ANTHROPIC_API_KEY= line/); assert.throws(() => readApiKey({ env: {}, apiKeyFile: "/nonexistent/anthropic.env" }), /no API key/); assert.throws(() => readApiKey({ env: {} }), /no API key/); } finally { await open.done(); await noLine.done(); } }); test("redact: the key and any long run of it", () => { assert.equal(redact(`bad key ${FAKE_KEY}!`, FAKE_KEY), "bad key [redacted]!"); assert.ok(!redact(`echo ${FAKE_KEY.slice(4, 24)}`, FAKE_KEY).includes(FAKE_KEY.slice(8, 24))); }); test("messages: the key only in x-api-key; top-level cache_control plus a system breakpoint", async () => { const api = await startFakeAnthropic({ turns: [textTurn("hello")] }); try { const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); const res = await client.messages({ model: "claude-sonnet-5", max_tokens: 100, system: "Be brief.", messages: [{ role: "user", content: "hi" }] }); assert.equal(textOf(res), "hello"); const h = api.requestHeaders[0]; assert.equal(h["x-api-key"], api.key); assert.equal(h["anthropic-version"], "2023-06-01"); const body = api.requests[0]; assert.deepEqual(body.cache_control, { type: "ephemeral" }); assert.deepEqual(body.system, [{ type: "text", text: "Be brief.", cache_control: { type: "ephemeral" } }]); assert.ok(!JSON.stringify(body).includes(api.key)); } finally { await api.close(); } }); test("messages: cacheTtl 1h on both breakpoints; the meter prices writes at 2x", async () => { const api = await startFakeAnthropic({ turns: [textTurn("a", { usage: { input_tokens: 0, output_tokens: 0, cache_creation_input_tokens: 1_000_000 } })], }); try { const meter = new Meter(); const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, cacheTtl: "1h" }); await client.messages({ model: "claude-sonnet-5", max_tokens: 10, system: "S", messages: [{ role: "user", content: "x" }] }, { meter }); assert.deepEqual(api.requests[0].cache_control, { type: "ephemeral", ttl: "1h" }); assert.deepEqual(api.requests[0].system[0].cache_control, { type: "ephemeral", ttl: "1h" }); assert.equal(meter.usd, 4); // $2/M × 2 } finally { await api.close(); } }); test("messages: a strict model loses temperature, gets thinking between_tools; a forced tool_choice is refused unsent", async () => { const api = await startFakeAnthropic({ turns: [textTurn("ok")] }); try { const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); await client.messages({ model: "claude-sonnet-5-5", max_tokens: 10, temperature: 0.2, thinking: { type: "disabled" }, messages: [{ role: "user", content: "x" }], }); const body = api.requests[0]; assert.equal("temperature" in body, false); assert.deepEqual(body.thinking, { type: "between_tools" }); await assert.rejects( client.messages({ model: "claude-sonnet-5-5", max_tokens: 10, tool_choice: { type: "tool", name: "answer" }, messages: [{ role: "user", content: "x" }], }), /forced tool_choice/, ); assert.equal(api.requests.length, 1); // Opus 5.5 keeps its own thinking default; a `disabled` it would refuse is dropped. assert.equal("thinking" in prepareBody({ model: "claude-opus-5-5", thinking: { type: "disabled" } }, "5m"), false); } finally { await api.close(); } }); test("messages: 429 with retry-after, then 529 with backoff, then success", async () => { const api = await startFakeAnthropic({ turns: [ errorTurn(429, "rate_limit_error", "slow down", { "retry-after": "7" }), errorTurn(529, "overloaded_error", "overloaded"), textTurn("third time"), ], }); try { const slept: number[] = []; const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: async (ms) => void slept.push(ms), }); const res = await client.messages({ model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }); assert.equal(textOf(res), "third time"); assert.deepEqual(slept, [7000, backoffMs(1)]); assert.equal(api.requests.length, 3); } finally { await api.close(); } }); test("messages: retries are bounded; a 400 is not retried", async () => { const api = await startFakeAnthropic({ turns: [ errorTurn(503, "api_error", "down"), errorTurn(503, "api_error", "down"), errorTurn(503, "api_error", "down"), errorTurn(400, "invalid_request_error", "messages: bad"), ], }); try { const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: noSleep, maxRetries: 2 }); const body = { model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }; await assert.rejects(client.messages(body), (e: AnthropicError) => { assert.equal(e.status, 503); assert.equal(e.retryable, true); return true; }); assert.equal(api.requests.length, 3); await assert.rejects(client.messages(body), (e: AnthropicError) => { assert.equal(e.status, 400); assert.equal(e.errorType, "invalid_request_error"); assert.match(e.message, /messages: bad/); return true; }); assert.equal(api.requests.length, 4); } finally { await api.close(); } }); test("messages: a model that refuses temperature is asked once more without it", async () => { const api = await startFakeAnthropic({ turns: [errorTurn(400, "invalid_request_error", "temperature: not supported on this model"), textTurn("fine")], }); try { const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: noSleep }); const res = await client.messages({ model: "claude-opus-5", max_tokens: 10, temperature: 0.2, messages: [{ role: "user", content: "x" }] }); assert.equal(textOf(res), "fine"); assert.equal(api.requests[0].temperature, 0.2); assert.equal("temperature" in api.requests[1], false); } finally { await api.close(); } }); test("messages: the signal aborts the in-flight request", async () => { const api = await startFakeAnthropic({ turns: [async () => (await new Promise((r) => setTimeout(r, 400)), textTurn("late"))], }); try { const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); const ac = new AbortController(); setTimeout(() => ac.abort(), 50); await assert.rejects( client.messages({ model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }, { signal: ac.signal }), (e) => e instanceof CancelledError, ); } finally { await new Promise((r) => setTimeout(r, 400)); await api.close(); } }); test("messages: a tool turn comes back as content blocks", async () => { const api = await startFakeAnthropic({ turns: [toolTurn("lookup", { q: "oven" })] }); try { const client = new AnthropicClient({ baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } }); const res = await client.messages({ model: "claude-sonnet-5", max_tokens: 10, messages: [{ role: "user", content: "x" }] }); assert.equal(res.stop_reason, "tool_use"); assert.equal(res.content[0].type, "tool_use"); assert.deepEqual(client.describe(), { baseUrl: api.url, cacheTtl: "5m", maxRetries: 5 }); } finally { await api.close(); } });