commit 43b21d3c37d16d6c8b9a5063aac06f12e48acf1a
parent c721c02f1041b22a26054b6698bca74a61f7a624
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 10:32:48 -0400
common: release 27 S1 — the Claude API client, ollama, the meter and structured answers
common/lib/llm/: prices (longest prefix; cache writes 1.25x/2x), the USD
Meter, AnthropicClient (key from env or a mode-600 file, sent only in
x-api-key and redacted from every error; top-level cache_control plus a
system breakpoint at one TTL; the strict models' rules; bounded retries on
429/5xx/529 with retry-after; abortable), ollamaChat (stream false, think
false, num_ctx clamped to 12k, the 8k prompt refused before sending,
done:false a fault, tools both ways) with unloadOllama, and structuredAnswer
on either provider. Tests against the S0 fakes.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 1479 insertions(+), 0 deletions(-)
diff --git a/common/lib/llm/anthropic.test.ts b/common/lib/llm/anthropic.test.ts
@@ -0,0 +1,247 @@
+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();
+ }
+});
diff --git a/common/lib/llm/anthropic.ts b/common/lib/llm/anthropic.ts
@@ -0,0 +1,340 @@
+// 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";
+
+export type AnthropicConfig = {
+ apiKeyFile?: string;
+ baseUrl?: string;
+ cacheTtl?: CacheTtl;
+ fetch?: typeof fetch;
+ sleep?: (ms: number) => Promise<void>;
+ maxRetries?: number;
+ // Where ANTHROPIC_API_KEY is looked up (tests pass {}); default process.env.
+ env?: Record<string, string | undefined>;
+ // 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;
+}
+
+// ─── 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<void> {
+ 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<string, unknown>, ttl: CacheTtl): Record<string, unknown> {
+ const model = String(body.model ?? "");
+ const cc = cacheControl(ttl);
+ const out: Record<string, unknown> = { 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 readonly cfg: AnthropicConfig;
+ #key: string | undefined;
+
+ constructor(cfg: AnthropicConfig) {
+ 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();
+ }
+
+ private key(): string {
+ this.#key ??= readApiKey(this.cfg);
+ return this.#key;
+ }
+
+ private fail(message: string, o: ConstructorParameters<typeof AnthropicError>[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<string, unknown>,
+ o: { meter?: Meter; signal?: AbortSignal } = {},
+ ): Promise<MessagesResponse> {
+ 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 });
+ }
+}
diff --git a/common/lib/llm/config.ts b/common/lib/llm/config.ts
@@ -0,0 +1,24 @@
+// Which provider a model runs on, and the config for both (release 27). This
+// module reads no settings: the caller (an editor job, S6) passes everything in.
+
+import { isClaudeModel, type AnthropicConfig } from "./anthropic";
+import type { OllamaConfig } from "./ollama";
+
+export type LlmConfig = { anthropic?: AnthropicConfig; ollama?: OllamaConfig };
+
+export type Provider = "api" | "local";
+
+// A Claude model goes to the API; anything else is a local model on ollama.
+export function providerOf(model: string): Provider {
+ return isClaudeModel(model) ? "api" : "local";
+}
+
+export function anthropicConfigOf(llm: LlmConfig, model: string): AnthropicConfig {
+ if (!llm.anthropic) throw new Error(`${model} runs on the Claude API, and no API config was given`);
+ return llm.anthropic;
+}
+
+export function ollamaConfigOf(llm: LlmConfig, model: string): OllamaConfig {
+ if (!llm.ollama?.baseUrl) throw new Error(`${model} runs on ollama, and no ollama URL was given`);
+ return llm.ollama;
+}
diff --git a/common/lib/llm/meter.test.ts b/common/lib/llm/meter.test.ts
@@ -0,0 +1,73 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { priceOf, PRICES } from "./prices";
+import { Meter } from "./meter";
+
+const close = (a: number, b: number) => assert.ok(Math.abs(a - b) < 1e-9, `${a} ≈ ${b}`);
+
+test("priceOf: the longest prefix wins", () => {
+ assert.deepEqual(priceOf("claude-opus-5-5"), PRICES["claude-opus-5-5"]);
+ assert.deepEqual(priceOf("claude-opus-5"), PRICES["claude-opus-5"]);
+ assert.deepEqual(priceOf("claude-sonnet-5-5-20261001"), PRICES["claude-sonnet-5-5"]);
+ assert.deepEqual(priceOf("claude-fable-5-1"), PRICES["claude-fable-5-1"]);
+ assert.deepEqual(priceOf("claude-fable-5"), PRICES["claude-fable-5"]);
+});
+
+test("priceOf: an unknown Claude model is priced as Opus 5; a local model is free", () => {
+ assert.deepEqual(priceOf("claude-unheard-of-9"), PRICES["claude-opus-5"]);
+ assert.deepEqual(priceOf("qwen3:8b"), { input: 0, output: 0, cacheReadMult: 0 });
+});
+
+test("Meter: input, output, cache writes at 1.25x (5m) and reads at the model's multiplier", () => {
+ const m = new Meter();
+ // Sonnet 5.5: $2 in, $10 out, reads 0.05x.
+ const usd = m.add("claude-sonnet-5-5", {
+ input_tokens: 1_000_000,
+ output_tokens: 100_000,
+ cache_creation_input_tokens: 1_000_000,
+ cache_read_input_tokens: 1_000_000,
+ });
+ close(usd, 2 + 1 + 2 * 1.25 + 2 * 0.05);
+ close(m.usd, usd);
+});
+
+test("Meter: writes at 2x when the run's TTL is 1h, or by the API's split when it reports one", () => {
+ const m = new Meter();
+ close(m.add("claude-sonnet-5", { cache_creation_input_tokens: 1_000_000 }, { cacheTtl: "1h" }), 4);
+ close(m.add("claude-sonnet-5", { cache_creation_input_tokens: 1_000_000 }), 2.5);
+ // The split wins over the TTL hint.
+ close(
+ m.add(
+ "claude-sonnet-5",
+ {
+ cache_creation_input_tokens: 1_000_000,
+ cache_creation: { ephemeral_5m_input_tokens: 500_000, ephemeral_1h_input_tokens: 500_000 },
+ },
+ { cacheTtl: "1h" },
+ ),
+ 0.5 * 2 * 1.25 + 0.5 * 2 * 2,
+ );
+});
+
+test("Meter: over() against the cap, never without one; summary per model", () => {
+ const capped = new Meter({ maxUsd: 1 });
+ capped.add("claude-sonnet-5", { output_tokens: 85_000 }); // $0.85
+ assert.equal(capped.over(0.85), true);
+ assert.equal(capped.over(), false);
+ capped.add("claude-sonnet-5", { output_tokens: 15_000 });
+ assert.equal(capped.over(), true);
+ const free = new Meter();
+ free.add("claude-opus-5", { output_tokens: 1_000_000 });
+ assert.equal(free.over(), false);
+
+ const m = new Meter();
+ m.add("qwen3:8b", { input_tokens: 5000, output_tokens: 200 });
+ m.add("claude-sonnet-5", { input_tokens: 100, cache_read_input_tokens: 300, output_tokens: 10 });
+ const s = m.summary();
+ assert.equal(s.byModel["qwen3:8b"].usd, 0);
+ assert.equal(s.byModel["qwen3:8b"].calls, 1);
+ assert.equal(s.byModel["claude-sonnet-5"].cacheHit, 0.75);
+ // The summary is a copy.
+ s.byModel["qwen3:8b"].calls = 99;
+ assert.equal(m.summary().byModel["qwen3:8b"].calls, 1);
+});
diff --git a/common/lib/llm/meter.ts b/common/lib/llm/meter.ts
@@ -0,0 +1,98 @@
+// A running token and estimated-USD tally across every call of a run (release
+// 27), on either provider: a local model's calls are counted and cost nothing.
+
+import { CACHE_WRITE_MULT, priceOf, type CacheTtl } from "./prices";
+
+// The Messages API's `usage`; ollama's counts map onto input/output.
+export type Usage = {
+ input_tokens?: number;
+ output_tokens?: number;
+ cache_creation_input_tokens?: number | null;
+ cache_read_input_tokens?: number | null;
+ // The write split by TTL, when the API reports it.
+ cache_creation?: { ephemeral_5m_input_tokens?: number; ephemeral_1h_input_tokens?: number } | null;
+ [k: string]: unknown;
+};
+
+export type ModelTally = {
+ calls: number;
+ input: number;
+ cacheWrite: number;
+ cacheRead: number;
+ output: number;
+ usd: number;
+ // cache reads over all input (input + writes + reads), 0..1
+ cacheHit: number;
+};
+
+const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
+const round = (v: number, places = 6) => Math.round(v * 10 ** places) / 10 ** places;
+
+export class Meter {
+ // The cap `over()` measures against; mutable, so a caller may extend a run
+ // (a bounded repair round) without a second meter.
+ maxUsd: number | undefined;
+ private total = 0;
+ private readonly byModel: Record<string, ModelTally> = {};
+
+ constructor(o: { maxUsd?: number } = {}) {
+ this.maxUsd = o.maxUsd;
+ }
+
+ get usd(): number {
+ return this.total;
+ }
+
+ // Adds one call's usage and returns its USD. Cache writes the API does not
+ // split by TTL are priced at `cacheTtl` (the run's one TTL; default 5m).
+ add(model: string, usage: Usage, o: { cacheTtl?: CacheTtl } = {}): number {
+ const p = priceOf(model);
+ const input = n(usage.input_tokens);
+ const output = n(usage.output_tokens);
+ const write = n(usage.cache_creation_input_tokens);
+ const read = n(usage.cache_read_input_tokens);
+ const split = usage.cache_creation ?? null;
+ let write1h: number;
+ if (split && (split.ephemeral_1h_input_tokens !== undefined || split.ephemeral_5m_input_tokens !== undefined))
+ write1h = Math.min(write, n(split.ephemeral_1h_input_tokens));
+ else write1h = o.cacheTtl === "1h" ? write : 0;
+ const write5m = write - write1h;
+ const usd =
+ (input * p.input +
+ write5m * p.input * CACHE_WRITE_MULT["5m"] +
+ write1h * p.input * CACHE_WRITE_MULT["1h"] +
+ read * p.input * p.cacheReadMult +
+ output * p.output) /
+ 1e6;
+ this.total += usd;
+ const m = (this.byModel[model] ??= {
+ calls: 0,
+ input: 0,
+ cacheWrite: 0,
+ cacheRead: 0,
+ output: 0,
+ usd: 0,
+ cacheHit: 0,
+ });
+ m.calls += 1;
+ m.input += input;
+ m.cacheWrite += write;
+ m.cacheRead += read;
+ m.output += output;
+ m.usd = round(m.usd + usd);
+ const all = m.input + m.cacheWrite + m.cacheRead;
+ m.cacheHit = all ? round(m.cacheRead / all, 3) : 0;
+ return usd;
+ }
+
+ // True once the spend reaches `frac` of the cap; never without a cap.
+ over(frac = 1): boolean {
+ return this.maxUsd !== undefined && this.total >= this.maxUsd * frac;
+ }
+
+ summary(): { usd: number; byModel: Record<string, ModelTally> } {
+ const byModel: Record<string, ModelTally> = {};
+ for (const [k, v] of Object.entries(this.byModel)) byModel[k] = { ...v };
+ return { usd: round(this.total), byModel };
+ }
+}
diff --git a/common/lib/llm/ollama.test.ts b/common/lib/llm/ollama.test.ts
@@ -0,0 +1,134 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ faultReply,
+ jsonReply,
+ reply,
+ startFakeOllama,
+ toolCallsReply,
+} from "../../testing/llm/fakeOllama.mjs";
+import {
+ estimateTokens,
+ NUM_CTX_MAX,
+ ollamaChat,
+ OllamaError,
+ OllamaFaultError,
+ promptEstimate,
+ PromptTooLargeError,
+ toOllamaTools,
+ toolCallsOf,
+ unloadOllama,
+} from "./ollama";
+
+test("estimateTokens: 3.5 characters a token, over a string or the JSON of a value", () => {
+ assert.equal(estimateTokens("x".repeat(35)), 10);
+ assert.equal(estimateTokens({ a: 1 }), Math.ceil(JSON.stringify({ a: 1 }).length / 3.5));
+});
+
+test("ollamaChat: stream false, think false on a thinking model, num_ctx clamped to 12k, the format passed", async () => {
+ const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] }), reply("plain")] });
+ try {
+ const cfg = { baseUrl: ol.url + "/", numCtx: 32_768, temperature: 0.2 };
+ const schema = { type: "object", properties: { terms: { type: "array" } } };
+ const r = await ollamaChat(cfg, { model: "qwen3:8b", messages: [{ role: "user", content: "hi" }], format: schema });
+ assert.deepEqual(JSON.parse(r.message.content), { terms: ["oven"] });
+ assert.ok(r.promptTokens > 0 && r.evalTokens > 0);
+ const body = ol.requests[0];
+ assert.equal(body.stream, false);
+ assert.equal(body.think, false);
+ assert.equal(body.options.num_ctx, NUM_CTX_MAX);
+ assert.equal(body.options.temperature, 0.2);
+ assert.deepEqual(body.format, schema);
+ // A model with no reasoning mode is not sent `think` at all.
+ await ollamaChat(cfg, { model: "qwen2.5:7b", messages: [{ role: "user", content: "hi" }] });
+ assert.equal("think" in ol.requests[1], false);
+ } finally {
+ await ol.close();
+ }
+});
+
+test("ollamaChat: a prompt over the cap is refused BEFORE it is sent", async () => {
+ const ol = await startFakeOllama({ turns: [reply("never")] });
+ try {
+ const big = "word ".repeat(8000); // ~11.4k tokens at 3.5 chars
+ await assert.rejects(
+ ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: big }] }),
+ (e) => e instanceof PromptTooLargeError && e.estimate > 8000,
+ );
+ // A lower cap from the caller is honoured; a higher one is clamped to 8k.
+ await assert.rejects(
+ ollamaChat({ baseUrl: ol.url, promptCapTokens: 300 }, { model: "qwen3:8b", messages: [{ role: "user", content: "x".repeat(2000) }] }),
+ PromptTooLargeError,
+ );
+ await assert.rejects(
+ ollamaChat({ baseUrl: ol.url, promptCapTokens: 50_000 }, { model: "qwen3:8b", messages: [{ role: "user", content: big }] }),
+ PromptTooLargeError,
+ );
+ assert.equal(ol.requests.length, 0);
+ } finally {
+ await ol.close();
+ }
+});
+
+test("ollamaChat: done:false is a GPU fault, an HTTP error is an error", async () => {
+ const ol = await startFakeOllama({ turns: [faultReply()] });
+ try {
+ await assert.rejects(
+ ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }] }),
+ (e) => e instanceof OllamaFaultError && /GPU fault/.test(e.message),
+ );
+ await assert.rejects(
+ ollamaChat({ baseUrl: ol.url }, { model: "llama-none", messages: [{ role: "user", content: "x" }] }),
+ (e) => e instanceof OllamaError && e.status === 404,
+ );
+ } finally {
+ await ol.close();
+ }
+});
+
+test("tools both ways: AgentTool → function; tool_calls (object or string arguments) → name + input", async () => {
+ const ol = await startFakeOllama({
+ turns: [
+ toolCallsReply([{ name: "lookup", arguments: { q: "oven" } }]),
+ () => ({
+ message: { role: "assistant", content: "", tool_calls: [{ function: { name: "lookup", arguments: '{"q":"tile"}' } }] },
+ done: true,
+ }),
+ ],
+ });
+ try {
+ const tools = toOllamaTools([
+ { name: "lookup", description: "Look it up.", inputSchema: { type: "object", properties: { q: { type: "string" } } } },
+ ]);
+ assert.deepEqual(tools[0], {
+ type: "function",
+ function: { name: "lookup", description: "Look it up.", parameters: { type: "object", properties: { q: { type: "string" } } } },
+ });
+ const a = await ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }], tools });
+ assert.deepEqual(toolCallsOf(a.message), [{ name: "lookup", input: { q: "oven" } }]);
+ assert.deepEqual(ol.requests[0].tools, tools);
+ const b = await ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }], tools });
+ assert.deepEqual(toolCallsOf(b.message), [{ name: "lookup", input: { q: "tile" } }]);
+ } finally {
+ await ol.close();
+ }
+});
+
+test("unloadOllama: keep_alive 0", async () => {
+ const ol = await startFakeOllama({ turns: [reply("x")] });
+ try {
+ await ollamaChat({ baseUrl: ol.url }, { model: "qwen3:8b", messages: [{ role: "user", content: "x" }] });
+ assert.deepEqual(ol.loaded(), ["qwen3:8b"]);
+ await unloadOllama({ baseUrl: ol.url }, "qwen3:8b");
+ assert.deepEqual(ol.unloads, ["qwen3:8b"]);
+ assert.deepEqual(ol.loaded(), []);
+ await assert.rejects(unloadOllama({ baseUrl: ol.url }, "nope:1b"), /404/);
+ } finally {
+ await ol.close();
+ }
+});
+
+test("promptEstimate counts messages, tools and format", () => {
+ const m = [{ role: "user", content: "x".repeat(350) }];
+ assert.ok(promptEstimate({ messages: m, tools: [{ a: "y".repeat(350) }] }) > promptEstimate({ messages: m }));
+});
diff --git a/common/lib/llm/ollama.ts b/common/lib/llm/ollama.ts
@@ -0,0 +1,215 @@
+// A local model on ollama (release 27): `/api/chat` with tools or a `format`
+// schema, and the unload. The stopgap's local_sweep.chat and agentloop's local
+// loop, with Q0's limits for the 8 GB card (2026-10-11):
+// - `num_ctx` is clamped to 12k;
+// - the prompt is estimated and REFUSED over 8k tokens before it is sent (a
+// 13.8k prompt hung the GPU);
+// - `done: false` is a GPU fault, never an answer;
+// - one JSON answer (`stream: false`), `think: false` on thinking models
+// unless the caller asks for thinking.
+// `digestApps.ts`'s `ollamaDirect` is the digest's own call and is left as it is.
+
+export type OllamaConfig = {
+ baseUrl: string;
+ numCtx?: number;
+ promptCapTokens?: number;
+ fetch?: typeof fetch;
+ temperature?: number;
+ // One request's timeout (default 15 minutes: a cold load plus a long answer).
+ timeoutMs?: number;
+};
+
+export type OllamaToolCall = { function: { name: string; arguments: Record<string, unknown> } };
+
+export type OllamaMessage = {
+ role: string;
+ content: string;
+ tool_calls?: OllamaToolCall[];
+ tool_name?: string;
+ thinking?: string;
+ [k: string]: unknown;
+};
+
+export type OllamaTool = {
+ type: "function";
+ function: { name: string; description: string; parameters: Record<string, unknown> };
+};
+
+export const NUM_CTX_MAX = 12_288;
+export const PROMPT_CAP_TOKENS = 8_000;
+// Q0's estimate: 3.5 characters a token, over the JSON of what is sent — on the
+// safe side of ollama's own count for English transcripts.
+export const CHARS_PER_TOKEN = 3.5;
+
+export function estimateTokens(v: unknown): number {
+ const s = typeof v === "string" ? v : (JSON.stringify(v ?? "") ?? "");
+ return Math.ceil(s.length / CHARS_PER_TOKEN);
+}
+
+// What a chat request is estimated at: its messages, tools and format.
+export function promptEstimate(req: { messages: unknown[]; tools?: unknown[]; format?: unknown }): number {
+ return estimateTokens([req.messages, req.tools ?? null, req.format ?? null]);
+}
+
+export function numCtxOf(cfg: OllamaConfig): number {
+ const v = cfg.numCtx ?? NUM_CTX_MAX;
+ return Math.max(512, Math.min(NUM_CTX_MAX, Math.floor(v)));
+}
+
+export function promptCapOf(cfg: OllamaConfig): number {
+ const v = cfg.promptCapTokens ?? PROMPT_CAP_TOKENS;
+ return Math.max(256, Math.min(PROMPT_CAP_TOKENS, Math.floor(v)));
+}
+
+// Models with a reasoning mode, which take `think`; ollama refuses `think` on
+// the others, so it is sent only to these unless the caller sets it.
+const THINKING_MODELS = /^(qwen3|qwq|deepseek-r1|gpt-oss|magistral|cogito)/;
+
+export class OllamaError extends Error {
+ readonly status: number | undefined;
+ constructor(message: string, status?: number) {
+ super(message);
+ this.name = "OllamaError";
+ this.status = status;
+ }
+}
+
+export class OllamaFaultError extends OllamaError {
+ constructor(model: string) {
+ super(`${model} answered done:false (a GPU fault) — not an answer`);
+ this.name = "OllamaFaultError";
+ }
+}
+
+export class PromptTooLargeError extends OllamaError {
+ readonly estimate: number;
+ readonly cap: number;
+ constructor(estimate: number, cap: number) {
+ super(`prompt ~${estimate} tokens is over the ${cap}-token cap — not sent`);
+ this.name = "PromptTooLargeError";
+ this.estimate = estimate;
+ this.cap = cap;
+ }
+}
+
+const base = (cfg: OllamaConfig) => cfg.baseUrl.replace(/\/+$/, "");
+
+// ollama returns tool-call arguments as an object; some models send a string.
+function normalizeMessage(m: Partial<OllamaMessage> | undefined): OllamaMessage {
+ const out: OllamaMessage = { ...(m ?? {}), role: m?.role ?? "assistant", content: m?.content ?? "" };
+ if (Array.isArray(m?.tool_calls) && m.tool_calls.length) {
+ out.tool_calls = m.tool_calls.map((c) => {
+ let args: unknown = c?.function?.arguments ?? {};
+ if (typeof args === "string") {
+ try {
+ args = JSON.parse(args);
+ } catch {
+ args = {};
+ }
+ }
+ return {
+ function: {
+ name: String(c?.function?.name ?? ""),
+ arguments: args && typeof args === "object" && !Array.isArray(args) ? (args as Record<string, unknown>) : {},
+ },
+ };
+ });
+ } else delete out.tool_calls;
+ return out;
+}
+
+export async function ollamaChat(
+ cfg: OllamaConfig,
+ req: {
+ model: string;
+ messages: object[];
+ tools?: object[];
+ format?: object;
+ think?: boolean;
+ signal?: AbortSignal;
+ },
+): Promise<{ message: OllamaMessage; promptTokens: number; evalTokens: number }> {
+ const cap = promptCapOf(cfg);
+ const estimate = promptEstimate(req);
+ if (estimate > cap) throw new PromptTooLargeError(estimate, cap);
+ const think = req.think ?? (THINKING_MODELS.test(req.model) ? false : undefined);
+ const body = {
+ model: req.model,
+ stream: false,
+ ...(think !== undefined ? { think } : {}),
+ messages: req.messages,
+ ...(req.tools?.length ? { tools: req.tools } : {}),
+ ...(req.format ? { format: req.format } : {}),
+ options: {
+ num_ctx: numCtxOf(cfg),
+ ...(cfg.temperature !== undefined ? { temperature: cfg.temperature } : {}),
+ },
+ };
+ const timeout = AbortSignal.timeout(cfg.timeoutMs ?? 900_000);
+ const signal = req.signal ? AbortSignal.any([req.signal, timeout]) : timeout;
+ let res: Response;
+ try {
+ res = await (cfg.fetch ?? fetch)(`${base(cfg)}/api/chat`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ signal,
+ });
+ } catch (err) {
+ if (req.signal?.aborted) throw err;
+ throw new OllamaError(`ollama request failed (${base(cfg)}): ${(err as Error)?.message ?? String(err)}`);
+ }
+ if (!res.ok) {
+ const text = await res.text().catch(() => "");
+ let detail = text;
+ try {
+ detail = (JSON.parse(text) as { error?: string }).error ?? text;
+ } catch {
+ // keep the text
+ }
+ throw new OllamaError(`ollama returned ${res.status}: ${detail.slice(0, 300) || res.statusText}`, res.status);
+ }
+ const out = (await res.json()) as {
+ message?: Partial<OllamaMessage>;
+ done?: boolean;
+ prompt_eval_count?: number;
+ eval_count?: number;
+ };
+ if (!out.done) throw new OllamaFaultError(req.model);
+ return {
+ message: normalizeMessage(out.message),
+ promptTokens: typeof out.prompt_eval_count === "number" ? out.prompt_eval_count : estimate,
+ evalTokens: typeof out.eval_count === "number" ? out.eval_count : 0,
+ };
+}
+
+// Frees the card: `keep_alive: 0` with nothing to answer.
+export async function unloadOllama(cfg: OllamaConfig, model: string): Promise<void> {
+ const res = await (cfg.fetch ?? fetch)(`${base(cfg)}/api/generate`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ model, keep_alive: 0 }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (!res.ok) {
+ const text = await res.text().catch(() => "");
+ throw new OllamaError(`ollama unload of ${model} returned ${res.status}: ${text.slice(0, 300)}`, res.status);
+ }
+ await res.body?.cancel().catch(() => {});
+}
+
+// ─── Tools, both ways ───
+
+export function toOllamaTools(
+ tools: { name: string; description: string; inputSchema: Record<string, unknown> }[],
+ descriptionChars = 600,
+): OllamaTool[] {
+ return tools.map((t) => ({
+ type: "function",
+ function: { name: t.name, description: t.description.slice(0, descriptionChars), parameters: t.inputSchema },
+ }));
+}
+
+export function toolCallsOf(message: OllamaMessage): { name: string; input: Record<string, unknown> }[] {
+ return (message.tool_calls ?? []).map((c) => ({ name: c.function.name, input: c.function.arguments }));
+}
diff --git a/common/lib/llm/prices.ts b/common/lib/llm/prices.ts
@@ -0,0 +1,40 @@
+// What a Claude model costs, for the USD meter (release 27). An ESTIMATE: the
+// Console's usage page is the truth.
+//
+// USD per million tokens: input, output, and the cache-read multiplier of the
+// input price, from the prompt-caching page's table (2026-10-12). Cache writes
+// bill 1.25x input (5-minute TTL) or 2x (1-hour). The longest matching prefix
+// wins; an unknown Claude model is priced as Opus 5 (the dearer guess), and a
+// model that is not Claude (a local one on ollama) costs nothing.
+
+export type Price = { input: number; output: number; cacheReadMult: number };
+
+export type CacheTtl = "5m" | "1h";
+
+// The cache-WRITE multiplier of the input price, per TTL.
+export const CACHE_WRITE_MULT: Record<CacheTtl, number> = { "5m": 1.25, "1h": 2 };
+
+export const PRICES: Readonly<Record<string, Price>> = {
+ "claude-fable-5-1": { input: 10, output: 50, cacheReadMult: 0.025 },
+ "claude-mythos-5-1": { input: 10, output: 50, cacheReadMult: 0.025 },
+ "claude-fable-5": { input: 10, output: 50, cacheReadMult: 0.1 },
+ "claude-mythos-5": { input: 10, output: 50, cacheReadMult: 0.1 },
+ "claude-opus-5-5": { input: 4, output: 20, cacheReadMult: 0.05 },
+ "claude-opus-5": { input: 5, output: 25, cacheReadMult: 0.1 },
+ "claude-opus-4": { input: 5, output: 25, cacheReadMult: 0.1 },
+ "claude-sonnet-5-5": { input: 2, output: 10, cacheReadMult: 0.05 },
+ "claude-sonnet-5": { input: 2, output: 10, cacheReadMult: 0.1 },
+ "claude-sonnet-4": { input: 3, output: 15, cacheReadMult: 0.1 },
+ // Up to 100k input tokens a request; more bills 5x (not modelled here).
+ "claude-haiku-5-5": { input: 0.1, output: 0.5, cacheReadMult: 0.1 },
+ "claude-haiku-4-5": { input: 1, output: 5, cacheReadMult: 0.1 },
+};
+
+const FREE: Price = { input: 0, output: 0, cacheReadMult: 0 };
+const BY_LENGTH = Object.keys(PRICES).sort((a, b) => b.length - a.length);
+
+export function priceOf(model: string): Price {
+ if (!model.startsWith("claude-")) return FREE;
+ for (const prefix of BY_LENGTH) if (model.startsWith(prefix)) return PRICES[prefix];
+ return PRICES["claude-opus-5"];
+}
diff --git a/common/lib/llm/structured.test.ts b/common/lib/llm/structured.test.ts
@@ -0,0 +1,172 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ startFakeAnthropic,
+ textTurn,
+ thinkingBlock,
+ toolUseBlock,
+ turn,
+ textBlock,
+} from "../../testing/llm/fakeAnthropic.mjs";
+import { faultReply, jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs";
+import { closeSchema, structuredAnswer, StructuredAnswerError } from "./structured";
+import { PromptTooLargeError } from "./ollama";
+import { Meter } from "./meter";
+import { providerOf } from "./config";
+
+const schema = {
+ type: "object",
+ properties: { terms: { type: "array", items: { type: "string" } }, note: { type: "object", properties: { why: { type: "string" } } } },
+ required: ["terms"],
+};
+
+test("providerOf: Claude → api, anything else → local", () => {
+ assert.equal(providerOf("claude-sonnet-5-5"), "api");
+ assert.equal(providerOf("qwen3:8b"), "local");
+});
+
+test("closeSchema: additionalProperties false and every property required, nested", () => {
+ const c = closeSchema(schema) as any;
+ assert.equal(c.additionalProperties, false);
+ assert.deepEqual(c.required, ["terms", "note"]);
+ assert.equal(c.properties.note.additionalProperties, false);
+ assert.deepEqual(c.properties.note.required, ["why"]);
+ assert.equal((schema as any).additionalProperties, undefined); // not mutated
+});
+
+test("Claude, a non-strict model: the answer tool forced", async () => {
+ const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["oven"] })])] });
+ try {
+ const meter = new Meter();
+ const out = await structuredAnswer<{ terms: string[] }>({
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ model: "claude-haiku-4-5",
+ system: "Plan searches.",
+ user: "Ovens?",
+ schema,
+ meter,
+ });
+ assert.deepEqual(out, { terms: ["oven"] });
+ const body = api.requests[0];
+ assert.deepEqual(body.tool_choice, { type: "tool", name: "answer" });
+ assert.equal(body.tools[0].strict, undefined);
+ assert.equal("temperature" in body, false);
+ assert.ok(meter.usd > 0);
+ } finally {
+ await api.close();
+ }
+});
+
+test("Claude, Sonnet 5.5: a strict tool with tool_choice auto; one re-ask, append-only after a thinking block", async () => {
+ const api = await startFakeAnthropic({
+ turns: [
+ turn([thinkingBlock("hmm"), textBlock("I think ovens.")]),
+ turn([toolUseBlock("answer", { terms: ["oven"], note: { why: "asked" } })]),
+ ],
+ });
+ try {
+ const out = await structuredAnswer({
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ model: "claude-sonnet-5-5",
+ system: "Plan searches.",
+ user: "Ovens?",
+ schema,
+ });
+ assert.deepEqual(out, { terms: ["oven"], note: { why: "asked" } });
+ const [first, second] = api.requests;
+ assert.deepEqual(first.tool_choice, { type: "auto" });
+ assert.equal(first.tools[0].strict, true);
+ assert.equal(first.tools[0].input_schema.additionalProperties, false);
+ assert.deepEqual(first.thinking, { type: "between_tools" });
+ assert.match(first.messages[0].content, /calling the `answer` tool/);
+ // The re-ask appends the answer as it came (the fake checks the signature).
+ assert.equal(second.messages.length, 3);
+ assert.equal(second.messages[1].content[0].type, "thinking");
+ assert.match(second.messages[2].content, /Call the `answer` tool/);
+ } finally {
+ await api.close();
+ }
+});
+
+test("Claude, Sonnet 5.5: no answer after the re-ask is an error", async () => {
+ const api = await startFakeAnthropic({ turns: [textTurn("no"), textTurn("still no")] });
+ try {
+ await assert.rejects(
+ structuredAnswer({
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ model: "claude-sonnet-5-5",
+ system: "s",
+ user: "u",
+ schema,
+ }),
+ StructuredAnswerError,
+ );
+ assert.equal(api.requests.length, 2);
+ } finally {
+ await api.close();
+ }
+});
+
+test("Claude: a model that refuses the forced tool_choice falls back to the strict way", async () => {
+ const api = await startFakeAnthropic({
+ strictModels: ["claude-opus-5"],
+ turns: [turn([toolUseBlock("answer", { terms: ["tile"] })])],
+ });
+ try {
+ const out = await structuredAnswer({
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: async () => {} } },
+ model: "claude-opus-5",
+ system: "s",
+ user: "u",
+ schema,
+ });
+ assert.deepEqual(out, { terms: ["tile"] });
+ assert.equal(api.requests.length, 2);
+ assert.deepEqual(api.requests[1].tool_choice, { type: "auto" });
+ } finally {
+ await api.close();
+ }
+});
+
+test("ollama: format-constrained JSON; a GPU fault retried once; the meter counts tokens at $0", async () => {
+ const ol = await startFakeOllama({ turns: [faultReply(), jsonReply({ terms: ["oven"] })] });
+ try {
+ const meter = new Meter();
+ const out = await structuredAnswer({
+ llm: { ollama: { baseUrl: ol.url } },
+ model: "qwen3:8b",
+ system: "s",
+ user: "u",
+ schema,
+ meter,
+ });
+ assert.deepEqual(out, { terms: ["oven"] });
+ assert.equal(ol.requests.length, 2);
+ assert.deepEqual(ol.requests[1].format, schema);
+ assert.equal(ol.requests[1].think, false);
+ assert.equal(meter.usd, 0);
+ assert.equal(meter.summary().byModel["qwen3:8b"].calls, 1);
+ } finally {
+ await ol.close();
+ }
+});
+
+test("ollama: an answer that is not JSON twice is an error; an oversized prompt is never sent", async () => {
+ const ol = await startFakeOllama({ turns: [reply("prose"), reply("more prose")] });
+ try {
+ const llm = { ollama: { baseUrl: ol.url } };
+ await assert.rejects(structuredAnswer({ llm, model: "qwen3:8b", system: "s", user: "u", schema }), /not JSON/);
+ await assert.rejects(
+ structuredAnswer({ llm, model: "qwen3:8b", system: "s", user: "w ".repeat(20_000), schema }),
+ PromptTooLargeError,
+ );
+ assert.equal(ol.requests.length, 2);
+ } finally {
+ await ol.close();
+ }
+});
+
+test("a provider without its config is a clear error", async () => {
+ await assert.rejects(structuredAnswer({ llm: {}, model: "qwen3:8b", system: "s", user: "u", schema }), /no ollama URL/);
+ await assert.rejects(structuredAnswer({ llm: {}, model: "claude-sonnet-5", system: "s", user: "u", schema }), /no API config/);
+});
diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts
@@ -0,0 +1,136 @@
+// One JSON answer matching a schema, on either provider (release 27; the
+// stopgap's claude_api.chat_json and local_sweep.chat).
+//
+// Claude: a single tool `answer` carries the schema. Most models are forced to
+// call it. A strict model (no forced tool_choice) gets a STRICT tool with a
+// closed schema and tool_choice auto plus an instruction, and is re-asked once
+// if it answers without calling it. A non-strict model whose forced call is
+// refused (a 400 naming tool_choice) falls back to the strict way.
+// ollama: constrained decoding through `format`, retried once on a GPU fault or
+// an answer that is not JSON. A prompt over the cap is refused, never sent.
+
+import { extractJsonObject } from "../parseStdoutJson";
+import {
+ AnthropicClient,
+ AnthropicError,
+ isStrictModel,
+ toolUsesOf,
+ type ContentBlock,
+ type MessagesResponse,
+} from "./anthropic";
+import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config";
+import type { Meter } from "./meter";
+import { ollamaChat, OllamaError, PromptTooLargeError } from "./ollama";
+
+export const ANSWER_TOOL = "answer";
+const ASK = "Answer by calling the `answer` tool.";
+const REASK = "Call the `answer` tool with your answer now.";
+
+export class StructuredAnswerError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "StructuredAnswerError";
+ }
+}
+
+// Strict tool use: `additionalProperties: false` on every object and every
+// property required.
+export function closeSchema<T>(schema: T): T {
+ if (Array.isArray(schema)) return schema.map((s) => closeSchema(s)) as T;
+ if (!schema || typeof schema !== "object") return schema;
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(schema as Record<string, unknown>)) out[k] = closeSchema(v);
+ if (out.type === "object") {
+ out.additionalProperties = false;
+ out.required = Object.keys((out.properties as Record<string, unknown>) ?? {});
+ }
+ return out as T;
+}
+
+type Opts = {
+ llm: LlmConfig;
+ model: string;
+ system: string;
+ user: string;
+ schema: object;
+ meter?: Meter;
+ signal?: AbortSignal;
+ maxTokens?: number;
+};
+
+export async function structuredAnswer<T>(o: Opts): Promise<T> {
+ return providerOf(o.model) === "api" ? claudeAnswer<T>(o) : localAnswer<T>(o);
+}
+
+async function claudeAnswer<T>(o: Opts): Promise<T> {
+ const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model));
+ const strict = isStrictModel(o.model);
+ try {
+ return await claudeTry<T>(client, o, strict);
+ } catch (err) {
+ if (!strict && err instanceof AnthropicError && err.status === 400 && /tool_choice/.test(err.message))
+ return claudeTry<T>(client, o, true);
+ throw err;
+ }
+}
+
+async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): Promise<T> {
+ const tool = {
+ name: ANSWER_TOOL,
+ description: "Give the answer.",
+ input_schema: strict ? closeSchema(o.schema) : o.schema,
+ ...(strict ? { strict: true } : {}),
+ };
+ let messages: { role: string; content: string | ContentBlock[] }[] = [
+ { role: "user", content: strict ? `${o.user}\n\n${ASK}` : o.user },
+ ];
+ let res: MessagesResponse | undefined;
+ for (let attempt = 0; attempt < (strict ? 2 : 1); attempt++) {
+ res = await client.messages(
+ {
+ model: o.model,
+ max_tokens: o.maxTokens ?? 4096,
+ system: o.system,
+ messages,
+ tools: [tool],
+ tool_choice: strict ? { type: "auto" } : { type: "tool", name: ANSWER_TOOL },
+ },
+ { meter: o.meter, signal: o.signal },
+ );
+ const call = toolUsesOf(res).find((b) => b.name === ANSWER_TOOL);
+ if (call && call.input && typeof call.input === "object") return call.input as T;
+ // Append-only: the re-ask follows the answer as it came.
+ messages = [...messages, { role: "assistant", content: res.content }, { role: "user", content: REASK }];
+ }
+ throw new StructuredAnswerError(`${o.model}: no structured answer (stop_reason ${res?.stop_reason ?? "none"})`);
+}
+
+async function localAnswer<T>(o: Opts): Promise<T> {
+ const cfg = ollamaConfigOf(o.llm, o.model);
+ let last = "";
+ for (let attempt = 0; attempt < 2; attempt++) {
+ let reply: Awaited<ReturnType<typeof ollamaChat>>;
+ try {
+ reply = await ollamaChat(cfg, {
+ model: o.model,
+ messages: [
+ { role: "system", content: o.system },
+ { role: "user", content: o.user },
+ ],
+ format: o.schema,
+ signal: o.signal,
+ });
+ } catch (err) {
+ if (err instanceof PromptTooLargeError || o.signal?.aborted) throw err;
+ if (!(err instanceof OllamaError) || (err.status !== undefined && err.status < 500)) throw err;
+ last = err.message;
+ continue;
+ }
+ o.meter?.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens });
+ const content = reply.message.content ?? "";
+ const value = content.trim() ? extractJsonObject(content) : null;
+ if (value !== null && typeof value === "object") return value as T;
+ last = content.trim() ? "the answer is not JSON" : "an empty answer";
+ }
+ throw new StructuredAnswerError(`${o.model}: no structured answer (${last})`);
+}