// The Claude Messages API over HTTPS with an API key (release 27; the stopgap's // claude_api.py). Not a Claude Code session: billed to the Console account. // // The key: $ANTHROPIC_API_KEY, else `apiKeyFile` (a line ANTHROPIC_API_KEY=…, // mode 600 — refused when group or others can read it). It is read here and // sent only in the `x-api-key` header. It is never logged, put in an error, an // event or a transcript: every message this module throws passes `redact`. // // Every request carries the top-level `cache_control` (the API moves that // breakpoint forward each turn) plus one on the system prompt, both at the // client's one TTL — a 1h breakpoint may not follow a 5m one. // // The strict models (Sonnet 5.5 first; see STRICT_MODELS) answer a 400 to a // non-default `temperature`, a forced `tool_choice` and `thinking: disabled`, and // sign their thinking blocks over the history before them, so their // conversations stay append-only. This client drops `temperature` for them, // refuses a forced `tool_choice` before sending, and asks Sonnet 5.5 for // `thinking: {type: "between_tools"}`. import { readFileSync, statSync } from "node:fs"; import os from "node:os"; import type { CacheTtl } from "./prices"; import type { Meter, Usage } from "./meter"; import { assertLocalOnlyAllowsApi } from "./localOnly"; export type AnthropicConfig = { apiKeyFile?: string; baseUrl?: string; cacheTtl?: CacheTtl; fetch?: typeof fetch; sleep?: (ms: number) => Promise; maxRetries?: number; // Where ANTHROPIC_API_KEY is looked up (tests pass {}); default process.env. env?: Record; // One request's timeout, retries apart (default 10 minutes). timeoutMs?: number; }; export type ContentBlock = { type: string; [k: string]: unknown }; export type TextBlock = { type: "text"; text: string }; export type ToolUseBlock = { type: "tool_use"; id: string; name: string; input: unknown }; export type MessagesResponse = { id: string; type: "message"; role: "assistant"; model: string; content: ContentBlock[]; stop_reason: string | null; stop_sequence?: string | null; usage: Usage; }; export const DEFAULT_BASE_URL = "https://api.anthropic.com"; export const ANTHROPIC_VERSION = "2023-06-01"; export const DEFAULT_MAX_RETRIES = 5; // Models with Sonnet 5.5's rules: no sampling parameters, no forced tool use, // preserved (signed) thinking. Opus 5.5 and Fable/Mythos 5.1 share the last two. export const STRICT_MODELS = ["claude-sonnet-5-5", "claude-opus-5-5", "claude-fable-5-1", "claude-mythos-5-1"]; export function isClaudeModel(model: string): boolean { return model.startsWith("claude-"); } export function isStrictModel(model: string): boolean { return STRICT_MODELS.some((m) => model.startsWith(m)); } // The thinking setting a model is sent: Sonnet 5.5 refuses `disabled`, and // `between_tools` is its lowest setting. Other models keep their default. export function thinkingFor(model: string): { type: string } | undefined { return model.startsWith("claude-sonnet-5-5") ? { type: "between_tools" } : undefined; } export function cacheControl(ttl: CacheTtl = "5m"): { type: "ephemeral"; ttl?: "1h" } { return ttl === "1h" ? { type: "ephemeral", ttl: "1h" } : { type: "ephemeral" }; } export function textOf(res: { content?: ContentBlock[] }): string { return (res.content ?? []) .filter((b) => b.type === "text" && typeof b.text === "string") .map((b) => b.text as string) .join(""); } export function toolUsesOf(res: { content?: ContentBlock[] }): ToolUseBlock[] { return (res.content ?? []).filter((b): b is ToolUseBlock & ContentBlock => b.type === "tool_use"); } // ─── The key ─── export class ApiKeyError extends Error { constructor(message: string) { super(message); this.name = "ApiKeyError"; } } const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p); export function readApiKey(cfg: AnthropicConfig): string { const env = cfg.env ?? process.env; const fromEnv = (env.ANTHROPIC_API_KEY ?? "").trim(); if (fromEnv) return fromEnv; if (!cfg.apiKeyFile) throw new ApiKeyError("no API key: set ANTHROPIC_API_KEY, or configure the API key file"); const file = expandHome(cfg.apiKeyFile); let mode: number; try { mode = statSync(file).mode; } catch { throw new ApiKeyError( `no API key: set ANTHROPIC_API_KEY, or put a line ANTHROPIC_API_KEY=… in ${file} (chmod 600)`, ); } if (mode & 0o077) throw new ApiKeyError(`${file} is readable by others — chmod 600 it first`); let text: string; try { text = readFileSync(file, "utf8"); } catch { throw new ApiKeyError(`${file} could not be read`); } for (const raw of text.split("\n")) { const line = raw.trim().replace(/^export\s+/, ""); if (!line.startsWith("ANTHROPIC_API_KEY=")) continue; const key = line .slice("ANTHROPIC_API_KEY=".length) .trim() .replace(/^(["'])(.*)\1$/, "$2") .trim(); if (key) return key; } throw new ApiKeyError(`${file} has no ANTHROPIC_API_KEY= line`); } // Replace every occurrence of the key (and of a long-enough piece of it) in a // text: the last line of defence for anything that leaves this module. export function redact(text: string, key: string | undefined): string { if (!key || key.length < 8) return text; let out = text.split(key).join("[redacted]"); // A server or a proxy may echo a truncated key; hide any 16-char run of it. if (key.length >= 24) for (let i = 0; i + 16 <= key.length; i += 8) out = out.split(key.slice(i, i + 16)).join("[redacted]"); return out; } // A text with the configured key taken out, whatever route the text went to // (the model log's records: a local prompt is scrubbed of it too). No key // configured, or one that does not read: the text as it is. export function keyRedactor(cfg: AnthropicConfig | undefined): (text: string) => string { if (!cfg) return (t) => t; let key: string | undefined; try { key = readApiKey(cfg); } catch { key = undefined; } return (t) => redact(t, key); } // ─── Errors ─── export class AnthropicError extends Error { readonly status: number | undefined; readonly errorType: string | undefined; readonly retryable: boolean; constructor(message: string, o: { status?: number; errorType?: string; retryable?: boolean } = {}) { super(message); this.name = "AnthropicError"; this.status = o.status; this.errorType = o.errorType; this.retryable = o.retryable ?? false; } } export class CancelledError extends Error { constructor() { super("cancelled"); this.name = "CancelledError"; } } const RETRY_STATUSES = new Set([408, 429, 500, 502, 503, 504, 529]); const isRetryStatus = (s: number) => RETRY_STATUSES.has(s) || s >= 500; // retry-after: seconds (possibly fractional) or an HTTP date; capped at 2 min. function retryAfterMs(value: string | null): number | undefined { if (!value) return undefined; const secs = Number(value); let ms = Number.isFinite(secs) ? secs * 1000 : Date.parse(value) - Date.now(); if (!Number.isFinite(ms) || ms < 0) return undefined; ms = Math.min(ms, 120_000); return ms; } export const backoffMs = (attempt: number) => Math.min(60_000, 5_000 * 2 ** attempt); function abortableSleep(ms: number, signal?: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal?.aborted) return reject(new CancelledError()); const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(t); reject(new CancelledError()); }; signal?.addEventListener("abort", onAbort, { once: true }); }); } // ─── The request body ─── // The body as sent: top-level cache_control, the system prompt as a block with // its own breakpoint, and the strict models' rules. Exported for tests. export function prepareBody(body: Record, ttl: CacheTtl): Record { const model = String(body.model ?? ""); const cc = cacheControl(ttl); const out: Record = { cache_control: cc, ...body }; if (typeof out.system === "string" && out.system) out.system = [{ type: "text", text: out.system, cache_control: cc }]; if (isStrictModel(model)) { delete out.temperature; const tc = out.tool_choice as { type?: string } | undefined; if (tc && (tc.type === "tool" || tc.type === "any")) throw new AnthropicError( `${model} refuses a forced tool_choice; use a strict tool with tool_choice auto`, { status: 400, errorType: "client_refused" }, ); const thinking = thinkingFor(model); const asked = out.thinking as { type?: string } | undefined; if (thinking && (!asked || asked.type === "disabled")) out.thinking = thinking; else if (asked?.type === "disabled") delete out.thinking; } return out; } // ─── The client ─── export class AnthropicClient { readonly cacheTtl: CacheTtl; readonly maxRetries: number; private readonly url: string; // Private (#) so neither inspect() nor JSON shows the config: its `env` may // hold the key. readonly #cfg: AnthropicConfig; #key: string | undefined; constructor(cfg: AnthropicConfig) { // LOCAL ONLY (./localOnly.ts): refused before anything — no key read, no // request. Read from process.env, never cfg.env (that one is the KEY's // environment, and is {} for a non-Anthropic base URL). assertLocalOnlyAllowsApi(); this.#cfg = cfg; this.cacheTtl = cfg.cacheTtl ?? "5m"; this.maxRetries = cfg.maxRetries ?? DEFAULT_MAX_RETRIES; this.url = (cfg.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "") + "/v1/messages"; } // The config without anything secret, for logs and records. describe(): { baseUrl: string; cacheTtl: CacheTtl; maxRetries: number } { return { baseUrl: this.url.replace(/\/v1\/messages$/, ""), cacheTtl: this.cacheTtl, maxRetries: this.maxRetries }; } toJSON() { return this.describe(); } // A text with this client's key taken out (the model log's records): the // key itself never leaves the client. redactText(text: string): string { return redact(text, this.#key); } private key(): string { this.#key ??= readApiKey(this.#cfg); return this.#key; } private fail(message: string, o: ConstructorParameters[1] = {}): AnthropicError { return new AnthropicError(redact(message, this.#key), o); } // POST /v1/messages with retries on 429/5xx/529 (retry-after, else backoff). // A 400 is not retried, except once without `temperature` when the model // refuses one. `signal` aborts the in-flight request and any wait. async messages( body: Record, o: { meter?: Meter; signal?: AbortSignal } = {}, ): Promise { // Again here, the last point before the network (a client made before the // flag was set is refused too). assertLocalOnlyAllowsApi(); const key = this.key(); let sent = prepareBody(body, this.cacheTtl); const doFetch = this.#cfg.fetch ?? fetch; const sleep = this.#cfg.sleep; const wait = async (ms: number) => { if (sleep) await sleep(ms); else await abortableSleep(ms, o.signal); if (o.signal?.aborted) throw new CancelledError(); }; let last = ""; let retries = 0; for (;;) { if (o.signal?.aborted) throw new CancelledError(); const timeout = AbortSignal.timeout(this.#cfg.timeoutMs ?? 600_000); const signal = o.signal ? AbortSignal.any([o.signal, timeout]) : timeout; let res: Response; try { res = await doFetch(this.url, { method: "POST", headers: { "x-api-key": key, "anthropic-version": ANTHROPIC_VERSION, "content-type": "application/json", }, body: JSON.stringify(sent), signal, }); } catch (err) { if (o.signal?.aborted) throw new CancelledError(); last = `request failed: ${(err as Error)?.message ?? String(err)}`; if (retries >= this.maxRetries) break; await wait(backoffMs(retries++)); continue; } if (res.ok) { let parsed: MessagesResponse; try { parsed = (await res.json()) as MessagesResponse; } catch { throw this.fail("Claude API: the response is not JSON", { status: res.status }); } if (o.meter) o.meter.add(String(sent.model), parsed.usage ?? {}, { cacheTtl: this.cacheTtl }); return parsed; } const raw = await res.text().catch(() => ""); let errorType: string | undefined; let detail = raw; try { const j = JSON.parse(raw) as { error?: { type?: string; message?: string } }; errorType = j.error?.type; detail = j.error?.message ?? raw; } catch { // not JSON: keep the text } detail = detail.slice(0, 600); last = `HTTP ${res.status}${errorType ? ` ${errorType}` : ""}: ${detail}`; if (res.status === 400 && /temperature/.test(detail) && "temperature" in sent) { const { temperature: _dropped, ...rest } = sent; sent = rest; // a model that fixes its own sampling continue; } if (isRetryStatus(res.status) && retries < this.maxRetries) { await wait(retryAfterMs(res.headers.get("retry-after")) ?? backoffMs(retries)); retries++; continue; } throw this.fail(`Claude API ${last}`, { status: res.status, errorType, retryable: isRetryStatus(res.status), }); } throw this.fail(`Claude API: gave up after ${retries} retries (${last})`, { retryable: true }); } }