From 88f32eea438319c869d4a0e030c916ed69e9c248 Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Tue, 10 Nov 2026 10:36:04 +0000 Subject: [PATCH 1/3] feat(llm): claude code headless adapter M20a. A third adapter behind the LlmClient port: claudeCodeClient runs the user's own `claude -p --output-format json --json-schema --system-prompt --tools "" --safe-mode --no-session-persistence`, the user prompt on stdin, and reads structured_output, usage, total_cost_usd and modelUsage into the port's response; every failure maps onto the port's one error type. --safe-mode, never --bare, which drops the OAuth login. findClaudeCode is pure: explicit path, then CLAUDE_CODE_PATH, then PATH, then the known install locations; an explicit path that does not exist never falls through. resolveProvider takes a probe and keeps auto's precedence OpenRouter > Cloudflare > Claude Code: an exported key is deliberate, an installed CLI ambient. Tested against a fake process and a recorded result; no SDK added. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PKCVh1q6FUhWzQi6KYtoTz --- packages/llm/package.json | 2 +- packages/llm/src/claude-code-discovery.ts | 110 +++++ packages/llm/src/claude-code.ts | 467 ++++++++++++++++++ packages/llm/src/index.ts | 26 +- packages/llm/src/providers.ts | 100 +++- .../llm/test/claude-code-discovery.test.ts | 117 +++++ packages/llm/test/claude-code-process.test.ts | 249 ++++++++++ packages/llm/test/claude-code.test.ts | 368 ++++++++++++++ .../test/fixtures/claude-result-sample.json | 1 + packages/llm/test/providers.test.ts | 63 ++- 10 files changed, 1471 insertions(+), 32 deletions(-) create mode 100644 packages/llm/src/claude-code-discovery.ts create mode 100644 packages/llm/src/claude-code.ts create mode 100644 packages/llm/test/claude-code-discovery.test.ts create mode 100644 packages/llm/test/claude-code-process.test.ts create mode 100644 packages/llm/test/claude-code.test.ts create mode 100644 packages/llm/test/fixtures/claude-result-sample.json diff --git a/packages/llm/package.json b/packages/llm/package.json index 8322daa..b4b15a2 100644 --- a/packages/llm/package.json +++ b/packages/llm/package.json @@ -3,7 +3,7 @@ "version": "0.2.0", "license": "MIT", "type": "module", - "description": "Codegraph LLM client: the one package that talks to a model provider (OpenRouter), behind a small client interface with a deterministic fake", + "description": "Codegraph LLM client: the one package that talks to a model provider (OpenRouter, Cloudflare AI Gateway, or Claude Code headless), behind a small client interface with a deterministic fake", "exports": { ".": { "types": "./dist/index.d.ts", diff --git a/packages/llm/src/claude-code-discovery.ts b/packages/llm/src/claude-code-discovery.ts new file mode 100644 index 0000000..7314626 --- /dev/null +++ b/packages/llm/src/claude-code-discovery.ts @@ -0,0 +1,110 @@ +import { posix, win32 } from "node:path"; + +/** + * WHERE THE CLAUDE CODE BINARY IS, decided as a pure function of what the + * caller hands over — an explicit path, the environment, an `exists` probe, + * the platform — so `--dry-run` resolves a provider without spawning and a + * test plants a binary on a fake disk. The search order, first hit wins: + * + * 1. the explicit path (`--claude-path`) + * 2. `CLAUDE_CODE_PATH` + * 3. `claude` in each directory of `PATH` (`claude.exe`, `claude.cmd` too on Windows) + * 4. the install locations the docs name (native installer, legacy local + * install, Homebrew, npm global on Windows) + * + * An explicit path that does not exist is an answer, not a fall-through: + * a user who named a binary gets that path back in the reason, never a + * different binary found elsewhere. + */ + +export const CLAUDE_CODE_PATH_VARIABLE = "CLAUDE_CODE_PATH"; + +export type ClaudeCodeSource = "option" | "env" | "PATH" | "known"; + +export interface ClaudeCodeLocation { + readonly path: string; + readonly source: ClaudeCodeSource; +} + +export interface ClaudeCodeSearch { + /** `--claude-path`, when given. */ + readonly explicit?: string | undefined; + readonly env: Readonly>; + readonly exists: (path: string) => boolean; + /** Defaults to this process's platform; tests pass both. */ + readonly platform?: NodeJS.Platform; +} + +export interface ClaudeCodeDiscovery { + readonly location: ClaudeCodeLocation | undefined; + /** + * Found: how (`found on PATH`, `--claude-path`, `CLAUDE_CODE_PATH`, `found in a known install location`). + * Not found: why — the explicit path that does not exist, or what was searched. + */ + readonly reason: string; +} + +function blank(value: string | undefined): boolean { + return value === undefined || value.trim() === ""; +} + +/** The executable names `claude` may have on this platform, in the order the shell tries them. */ +export function claudeExecutableNames(platform: NodeJS.Platform): readonly string[] { + return platform === "win32" ? ["claude.exe", "claude.cmd", "claude"] : ["claude"]; +} + +/** The directories of `PATH` (`Path` on a Windows record), in order, empty entries dropped. */ +export function pathDirectories(env: Readonly>, platform: NodeJS.Platform): readonly string[] { + const raw = env["PATH"] ?? env["Path"] ?? env["path"] ?? ""; + return raw + .split(platform === "win32" ? ";" : ":") + .map((dir) => dir.trim()) + .filter((dir) => dir !== ""); +} + +/** The install locations the docs name, for this platform — those whose base (home, APPDATA) the environment gives. */ +export function knownClaudeCodePaths(env: Readonly>, platform: NodeJS.Platform): readonly string[] { + if (platform === "win32") { + const home = env["USERPROFILE"]; + const appData = env["APPDATA"]; + return [ + ...(blank(home) ? [] : [win32.join(home!, ".local", "bin", "claude.exe")]), + ...(blank(appData) ? [] : [win32.join(appData!, "npm", "claude.cmd")]), + ]; + } + const home = env["HOME"]; + return [ + ...(blank(home) ? [] : [posix.join(home!, ".local", "bin", "claude"), posix.join(home!, ".claude", "local", "claude")]), + "/opt/homebrew/bin/claude", + "/usr/local/bin/claude", + ]; +} + +export function findClaudeCode(search: ClaudeCodeSearch): ClaudeCodeDiscovery { + const platform = search.platform ?? process.platform; + const path = platform === "win32" ? win32 : posix; + + if (!blank(search.explicit)) { + const explicit = search.explicit!.trim(); + return search.exists(explicit) + ? { location: { path: explicit, source: "option" }, reason: "--claude-path" } + : { location: undefined, reason: `--claude-path ${explicit} does not exist` }; + } + const fromEnv = search.env[CLAUDE_CODE_PATH_VARIABLE]; + if (!blank(fromEnv)) { + const named = fromEnv!.trim(); + return search.exists(named) + ? { location: { path: named, source: "env" }, reason: CLAUDE_CODE_PATH_VARIABLE } + : { location: undefined, reason: `${CLAUDE_CODE_PATH_VARIABLE}=${named} does not exist` }; + } + for (const dir of pathDirectories(search.env, platform)) { + for (const name of claudeExecutableNames(platform)) { + const candidate = path.join(dir, name); + if (search.exists(candidate)) return { location: { path: candidate, source: "PATH" }, reason: "found on PATH" }; + } + } + for (const candidate of knownClaudeCodePaths(search.env, platform)) { + if (search.exists(candidate)) return { location: { path: candidate, source: "known" }, reason: "found in a known install location" }; + } + return { location: undefined, reason: "no claude on PATH or in a known install location" }; +} diff --git a/packages/llm/src/claude-code.ts b/packages/llm/src/claude-code.ts new file mode 100644 index 0000000..64c5f82 --- /dev/null +++ b/packages/llm/src/claude-code.ts @@ -0,0 +1,467 @@ +import { spawn as nodeSpawn } from "node:child_process"; +import { tmpdir } from "node:os"; +import { extractJson } from "./chat.js"; +import { LlmError, isLlmError, isRetryableStatus, type LlmClient, type LlmRequest, type LlmResponse, type LlmUsage } from "./client.js"; +import { withRetry, type RetryOptions } from "./retry.js"; + +/** + * Claude Code's headless mode (`claude -p`) as an `LlmClient`: the adapter for + * a developer whose model is the Claude Code installation on the machine, not + * an API key (PLAN.md §21). + * + * WHAT DIFFERS FROM THE TWO HTTP ADAPTERS, and why there is a third file: + * + * - One call = one process. Nothing here opens a socket: the CLI is spawned + * with its argv as an array (never a shell), reads one prompt, prints one + * `type: "result"` JSON object and exits. `--concurrency N` above the port + * is N processes. + * - The user prompt travels on stdin, never as an argument: a context pack + * with source can exceed Linux's 128 KB per-argument limit. The system + * prompt and the JSON Schema ride as arguments. + * - `--safe-mode`, not `--bare`. `--bare` restricts authentication to + * `ANTHROPIC_API_KEY`, the one case this adapter is not for; `--safe-mode` + * keeps the login and the model and disables every customization + * (CLAUDE.md, hooks, plugins, MCP, output styles). The working directory is + * the OS temp directory, so no CLAUDE.md of the caller's tree is near. + * - `temperature` and `maxTokens` have no headless flag: ignored. + * - Errors are read from the process (spawn failure, exit code, timeout) and + * the result's `api_error_status`, then from the message text; the CLI + * retries its own API errors first, so `withRetry` covers what leaks. + * + * The subprocess is held behind `ClaudeCodeProcess.run` — one function, like + * OpenRouter's transport and Cloudflare's fetch — so every test drives the + * adapter with a fake process, and the default runner itself is tested with a + * fake `spawn`: nothing in the workspace spawns. + * + * The fourth adapter, the Anthropic API with an API key, is a named empty slot + * (PLAN.md §21.6): `anthropic.ts`, one more entry in providers.ts. + */ + +/** Claude Code's alias for the latest Sonnet; a full id (`claude-sonnet-5-5`) pins the fingerprint. */ +export const CLAUDE_CODE_DEFAULT_MODEL = "sonnet"; +export const CLAUDE_CODE_DEFAULT_TIMEOUT_MS = 600_000; +/** After SIGTERM at the timeout or on abort, how long the runner waits before SIGKILL. */ +export const CLAUDE_CODE_KILL_GRACE_MS = 5_000; +/** After the child's exit, how long the runner waits for its pipes to close before destroying them (a descendant may hold them). */ +export const CLAUDE_CODE_DRAIN_GRACE_MS = 1_000; + +export interface ClaudeCodeRun { + readonly command: string; + readonly argv: readonly string[]; + /** The user prompt, written to the child's stdin then closed. */ + readonly stdin: string; + readonly env: Readonly>; + readonly cwd: string; + readonly timeoutMs: number; + readonly signal?: AbortSignal | undefined; +} + +export interface ClaudeCodeOutcome { + readonly stdout: string; + readonly stderr: string; + /** Exit code; null when killed by a signal (or never started). */ + readonly code: number | null; + readonly signal: NodeJS.Signals | null; + /** The spawn failure (ENOENT, EACCES…) when the process never ran. */ + readonly error?: NodeJS.ErrnoException | undefined; + /** True when the runner killed the child at `timeoutMs`. */ + readonly timedOut?: boolean | undefined; +} + +/** The subprocess seam — one function — so tests drive the whole path with recorded outcomes and spawn nothing. */ +export interface ClaudeCodeProcess { + run(run: ClaudeCodeRun): Promise; +} + +export interface ClaudeCodeOptions { + /** The resolved binary (claude-code-discovery.ts); never looked up here. */ + readonly command: string; + /** Defaults to `node:child_process`; tests inject a fake. */ + readonly process?: ClaudeCodeProcess; + /** The child's base environment; defaults to this process's. */ + readonly env?: Readonly>; + /** Defaults to the OS temp directory: no CLAUDE.md of the caller's tree. */ + readonly cwd?: string; + /** Per call; defaults to 600 000 (10 min). */ + readonly timeoutMs?: number; + readonly retry?: RetryOptions; +} + +// --------------------------------------------------------------------------- +// The invocation (PLAN.md §21.1, the argument table) + +/** The `claude -p` argv: one JSON result, the strict schema, no tools, safe mode, nothing persisted. The prompt is NOT here. */ +export function buildClaudeCodeArgv(request: LlmRequest): string[] { + // `temperature` and `maxTokens` have no headless flag: the port's knobs are ignored here, by design. + const effort = request.reasoningEffort === undefined ? [] : ["--effort", request.reasoningEffort === "none" ? "low" : request.reasoningEffort]; + return [ + "-p", + "--output-format", + "json", + "--model", + request.model, + "--json-schema", + JSON.stringify(request.schema.jsonSchema), + "--system-prompt", + request.system, + "--tools", + "", + "--safe-mode", + "--no-session-persistence", + ...effort, + ]; +} + +// --------------------------------------------------------------------------- +// The result (PLAN.md §21.1, the field table) + +type ResultRecord = Readonly>; + +function isRecord(value: unknown): value is ResultRecord { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +/** The `type: "result"` object stdout carries (alone, or inside the older message array); undefined when stdout is anything else. */ +function readResult(stdout: string): ResultRecord | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(stdout.trim()) as unknown; + } catch { + return undefined; + } + const candidates = Array.isArray(parsed) ? (parsed as unknown[]) : [parsed]; + return candidates.find((item): item is ResultRecord => isRecord(item) && item["type"] === "result"); +} + +/** + * `api_error_status` — the API error that terminated the conversation — can ride on a success arm: a number there is a failure too. + * A result with no `subtype` at all is a failure as well (today's CLI always emits it; a shape we do not know is not a success). + */ +function failedResult(result: ResultRecord): boolean { + return result["is_error"] === true || result["subtype"] !== "success" || typeof result["api_error_status"] === "number"; +} + +function count(value: unknown): number { + return typeof value === "number" ? value : 0; +} + +/** Every input token counts as sent — cached or not — as the chat adapters count `prompt_tokens`. */ +function usageOf(raw: unknown, cost: unknown): LlmUsage | undefined { + if (!isRecord(raw)) return undefined; + return { + promptTokens: count(raw["input_tokens"]) + count(raw["cache_creation_input_tokens"]) + count(raw["cache_read_input_tokens"]), + completionTokens: count(raw["output_tokens"]), + ...(typeof cost === "number" ? { cost } : {}), + }; +} + +/** The model that served — the key of `modelUsage`, its `canonicalModel` when present — not the alias asked for. */ +function servedModel(modelUsage: unknown): string | undefined { + if (!isRecord(modelUsage)) return undefined; + const [key, entry] = Object.entries(modelUsage)[0] ?? []; + if (key === undefined) return undefined; + const canonical = isRecord(entry) ? entry["canonicalModel"] : undefined; + return typeof canonical === "string" ? canonical : key; +} + +function responseOf(result: ResultRecord, requestedModel: string): LlmResponse { + const text = typeof result["result"] === "string" ? result["result"] : ""; + let json: unknown; + if (result["structured_output"] !== undefined) { + json = result["structured_output"]; + } else { + if (text.trim() === "") throw new LlmError("model returned an empty completion", undefined, false); + json = extractJson(text); + } + const usage = usageOf(result["usage"], result["total_cost_usd"]); + return { + json, + text: text === "" ? JSON.stringify(json) : text, + model: servedModel(result["modelUsage"]) ?? requestedModel, + ...(usage === undefined ? {} : { usage }), + }; +} + +/** One result JSON on stdout → our response; a failure result, or stdout that is not one, is thrown as the classified `LlmError`. */ +export function parseClaudeCodeResult(stdout: string, requestedModel: string): LlmResponse { + const result = readResult(stdout); + if (result === undefined || failedResult(result)) throw toClaudeCodeError({ stdout, stderr: "", code: 0, signal: null }, result); + return responseOf(result, requestedModel); +} + +// --------------------------------------------------------------------------- +// The errors (PLAN.md §21.1, the error table) + +/** What the message says when the result carries no status; the first row that matches wins. */ +const MESSAGE_STATUSES: readonly { readonly pattern: RegExp; readonly status: number }[] = [ + { pattern: /not logged in|invalid api key|unauthorized|authentication/iu, status: 401 }, + { pattern: /rate limit|\b429\b|too many requests/iu, status: 429 }, + { pattern: /overloaded|\b529\b/iu, status: 529 }, + { pattern: /budget|credit|billing|\b402\b/iu, status: 402 }, +]; + +function statusOfMessage(text: string): number | undefined { + return MESSAGE_STATUSES.find((rule) => rule.pattern.test(text))?.status; +} + +/** The documented error arms (SDKResultMessage): what each means for the message, and the one that has a status of its own. */ +const SUBTYPE_NOTES: Readonly> = { + error_max_turns: "the CLI reached its turn limit", + error_during_execution: "the CLI failed while running", + error_max_budget_usd: "the CLI's own budget is exhausted", + error_max_structured_output_retries: "the model never produced schema-valid output", +}; +const SUBTYPE_STATUSES: Readonly> = { error_max_budget_usd: 402 }; + +/** Everything the CLI said about a failure: the result's `result`, `errors` and `error` fields, then stderr. */ +function saidOf(result: ResultRecord | undefined, stderr: string): string { + const parts: string[] = []; + const push = (value: unknown): void => { + if (typeof value === "string" && value.trim() !== "") parts.push(value.trim()); + else if (Array.isArray(value)) value.forEach(push); + else if (isRecord(value)) push(value["message"]); + }; + if (result !== undefined) { + push(result["result"]); + push(result["errors"]); + push(result["error"]); + } + push(stderr); + return parts.join("; "); +} + +/** + * One `LlmError` per row of the error table. `run` supplies the command and + * the timeout for the messages of the two process rows; without it they fall + * back to what the outcome itself carries. + */ +export function toClaudeCodeError(outcome: ClaudeCodeOutcome, parsed?: unknown, run?: Pick): LlmError { + if (outcome.error !== undefined) { + const command = run?.command ?? outcome.error.path ?? "claude"; + const code = outcome.error.code ?? outcome.error.message; + return new LlmError(`claude-code: cannot run ${command}: ${code}`, undefined, false, { cause: outcome.error }); + } + if (outcome.timedOut === true) { + const limit = run === undefined ? "the timeout" : `${run.timeoutMs} ms`; + return new LlmError(`claude-code: no result within ${limit}; the process was killed`, undefined, false); + } + const result = isRecord(parsed) ? parsed : undefined; + if (result === undefined && outcome.code === 0) { + const head = outcome.stdout.trim().slice(0, 200); + return new LlmError(`claude-code: stdout is not the result JSON${head === "" ? "" : `: ${head}`}`, undefined, false); + } + const said = saidOf(result, outcome.stderr); + const exit = outcome.code !== null ? `exit ${outcome.code}` : outcome.signal !== null ? `killed by ${outcome.signal}` : "no exit code"; + const subtype = typeof result?.["subtype"] === "string" ? result["subtype"] : ""; + const apiStatus = result?.["api_error_status"]; + // The status: the API's own on any arm, else the arm's (budget → 402), else what the text says. + const status = typeof apiStatus === "number" ? apiStatus : (SUBTYPE_STATUSES[subtype] ?? statusOfMessage(said)); + const notes = [ + ...(typeof apiStatus === "number" ? [`API error ${apiStatus}`] : []), + ...(SUBTYPE_NOTES[subtype] === undefined ? [] : [SUBTYPE_NOTES[subtype]]), + ...(said === "" ? [] : [said.slice(0, 300)]), + ]; + return new LlmError( + `claude-code: ${exit}${subtype === "" || subtype === "success" ? "" : ` (${subtype})`}${notes.length === 0 ? "" : `: ${notes.join("; ")}`}`, + status, + status === undefined ? false : isRetryableStatus(status), + ); +} + +// --------------------------------------------------------------------------- +// The default process: node:child_process behind the seam + +/** The slice of `ChildProcess` the runner touches, so a test hands in a scripted child and spawns nothing. */ +export interface ClaudeCodeChild { + readonly stdin: { write(chunk: string): unknown; end(): unknown; on(event: "error", listener: (error: Error) => void): unknown } | null; + readonly stdout: ClaudeCodeChildPipe | null; + readonly stderr: ClaudeCodeChildPipe | null; + on(event: "error", listener: (error: NodeJS.ErrnoException) => void): unknown; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown; + kill(signal: NodeJS.Signals): boolean; +} + +/** An output pipe of the child: read, and destroyed when a descendant keeps it open after the child's exit. */ +export interface ClaudeCodeChildPipe { + on(event: "data", listener: (chunk: Buffer | string) => void): unknown; + destroy(): unknown; +} + +export interface ClaudeCodeSpawnOptions { + readonly cwd: string; + readonly env: Readonly>; + readonly stdio: ["pipe", "pipe", "pipe"]; + readonly windowsHide: true; +} + +/** `node:child_process`'s `spawn`, narrowed to how the runner calls it: argv as an array, never a shell. */ +export type ClaudeCodeSpawn = (command: string, argv: readonly string[], options: ClaudeCodeSpawnOptions) => ClaudeCodeChild; + +export interface ChildProcessRunnerOptions { + /** Defaults to `node:child_process`; tests inject a fake. */ + readonly spawn?: ClaudeCodeSpawn; + /** Defaults to `CLAUDE_CODE_KILL_GRACE_MS`. */ + readonly killGraceMs?: number; + /** Defaults to `CLAUDE_CODE_DRAIN_GRACE_MS`. */ + readonly drainGraceMs?: number; +} + +function abortError(signal: AbortSignal | undefined): LlmError { + const reason: unknown = signal?.reason; + return new LlmError("claude-code: the call was aborted", undefined, false, reason === undefined ? undefined : { cause: reason }); +} + +function asBuffer(chunk: Buffer | string): Buffer { + return typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk; +} + +/** + * The real `ClaudeCodeProcess`: spawn, feed stdin, collect both streams, and + * resolve on close. At `timeoutMs` (or on abort) the child gets SIGTERM, then + * SIGKILL after the kill grace if it is still there; a timeout is an outcome + * (`timedOut`, only when the timeout killed a child that had not exited), an + * abort a rejection — the caller asked for it. + * + * 'close' needs the pipes closed, and a descendant of the child may hold them + * after the child's exit (`sleep 30 &`): the child's result is complete at + * its exit, so from there the runner waits the drain grace for 'close', then + * destroys the pipes and settles with what it has — a grandchild's output is + * noise. Without this a leaked descendant would hold every call for as long + * as it lives. + */ +export function childProcessRunner(options: ChildProcessRunnerOptions = {}): ClaudeCodeProcess { + const spawn: ClaudeCodeSpawn = options.spawn ?? nodeSpawn; + const killGraceMs = options.killGraceMs ?? CLAUDE_CODE_KILL_GRACE_MS; + const drainGraceMs = options.drainGraceMs ?? CLAUDE_CODE_DRAIN_GRACE_MS; + return { + run(run: ClaudeCodeRun): Promise { + return new Promise((resolve, reject) => { + if (run.signal?.aborted === true) { + reject(abortError(run.signal)); + return; + } + let child: ClaudeCodeChild; + try { + child = spawn(run.command, run.argv, { cwd: run.cwd, env: run.env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }); + } catch (error) { + resolve({ stdout: "", stderr: "", code: null, signal: null, error: error as NodeJS.ErrnoException }); + return; + } + const out: Buffer[] = []; + const err: Buffer[] = []; + child.stdout?.on("data", (chunk) => out.push(asBuffer(chunk))); + child.stderr?.on("data", (chunk) => err.push(asBuffer(chunk))); + + let exited: Pick | undefined; + let timedOut = false; + let aborted = false; + let settled = false; + let killTimer: NodeJS.Timeout | undefined; + let drainTimer: NodeJS.Timeout | undefined; + // Idempotent: a timeout and an abort together signal once and leave one escalation timer. + const kill = (): void => { + if (killTimer !== undefined || exited !== undefined) return; + child.kill("SIGTERM"); + killTimer = setTimeout(() => child.kill("SIGKILL"), killGraceMs); + }; + const timer = setTimeout(() => { + if (exited !== undefined) return; // out already; the drain bounds the rest + timedOut = true; + kill(); + }, run.timeoutMs); + const onAbort = (): void => { + aborted = true; + kill(); + }; + run.signal?.addEventListener("abort", onAbort, { once: true }); + + // The first of 'error' (never ran), 'close' and the drain settles; the others are ignored. + const settle = (ended: Pick): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (killTimer !== undefined) clearTimeout(killTimer); + if (drainTimer !== undefined) clearTimeout(drainTimer); + run.signal?.removeEventListener("abort", onAbort); + if (aborted) { + reject(abortError(run.signal)); + return; + } + resolve({ + stdout: Buffer.concat(out).toString("utf8"), + stderr: Buffer.concat(err).toString("utf8"), + code: ended.code, + signal: ended.signal, + ...(ended.error === undefined ? {} : { error: ended.error }), + ...(timedOut ? { timedOut: true } : {}), + }); + }; + child.on("error", (error) => settle({ code: null, signal: null, error })); + child.on("exit", (code, signal) => { + exited = { code, signal }; + drainTimer = setTimeout(() => { + child.stdout?.destroy(); + child.stderr?.destroy(); + settle({ code, signal }); + }, drainGraceMs); + }); + child.on("close", (code, signal) => settle({ code, signal })); + + // A child that exits before reading its prompt closes the pipe: EPIPE here is noise, not the failure. + // The CLI caps stdin at 10 MB (non-zero exit above); a context pack is far below. + child.stdin?.on("error", () => undefined); + child.stdin?.write(run.stdin); + child.stdin?.end(); + }); + }, + }; +} + +// --------------------------------------------------------------------------- +// The client + +/** The child's environment: the caller's, with every unset variable dropped (spawn takes strings only). */ +function definedEnv(env: Readonly>): Record { + const out: Record = {}; + for (const [name, value] of Object.entries(env)) if (value !== undefined) out[name] = value; + return out; +} + +function failed(outcome: ClaudeCodeOutcome, result: ResultRecord): boolean { + return outcome.error !== undefined || outcome.timedOut === true || outcome.code !== 0 || failedResult(result); +} + +export function claudeCodeClient(options: ClaudeCodeOptions): LlmClient { + const runner = options.process ?? childProcessRunner(); + const env = definedEnv(options.env ?? process.env); + const cwd = options.cwd ?? tmpdir(); + const timeoutMs = options.timeoutMs ?? CLAUDE_CODE_DEFAULT_TIMEOUT_MS; + return { + name: "claude-code", + complete(request: LlmRequest, signal?: AbortSignal): Promise { + const run: ClaudeCodeRun = { + command: options.command, + argv: buildClaudeCodeArgv(request), + stdin: request.user, + env, + cwd, + timeoutMs, + ...(signal === undefined ? {} : { signal }), + }; + return withRetry(async () => { + let outcome: ClaudeCodeOutcome; + try { + outcome = await runner.run(run); + } catch (error) { + if (isLlmError(error)) throw error; + const message = error instanceof Error ? error.message : String(error); + throw new LlmError(`claude-code: ${message}`, undefined, false, { cause: error }); + } + const result = readResult(outcome.stdout); + if (result === undefined || failed(outcome, result)) throw toClaudeCodeError(outcome, result, run); + return responseOf(result, request.model); + }, options.retry); + }, + }; +} diff --git a/packages/llm/src/index.ts b/packages/llm/src/index.ts index dcc4189..5ca5452 100644 --- a/packages/llm/src/index.ts +++ b/packages/llm/src/index.ts @@ -2,22 +2,28 @@ * `@codegraph/llm` — the one package in the workspace that talks to a model * provider. Everything else programs against `LlmClient`: * - * client.ts the contract: one structured completion in, parsed JSON out - * retry.ts exponential back-off on transient provider errors, Retry-After obeyed - * chat.ts the OpenAI chat-completion shape both providers return - * openrouter.ts OpenRouter through its SDK — the ONLY module allowed to - * import a provider SDK (test/boundary.test.ts enforces it) - * cloudflare.ts Cloudflare AI Gateway through its REST API, plain fetch - * providers.ts which provider, decided from the environment in one place - * fake.ts a deterministic, zero-latency client for tests and dry runs + * client.ts the contract: one structured completion in, parsed JSON out + * retry.ts exponential back-off on transient provider errors, Retry-After obeyed + * chat.ts the OpenAI chat-completion shape the two HTTP providers return + * openrouter.ts OpenRouter through its SDK — the ONLY module allowed to + * import a provider SDK (test/boundary.test.ts enforces it) + * cloudflare.ts Cloudflare AI Gateway through its REST API, plain fetch + * claude-code.ts Claude Code headless (`claude -p`), one subprocess per call + * claude-code-discovery.ts where the `claude` binary is: option, variable, PATH, known installs + * providers.ts which provider, decided from the environment (and the + * discovery) in one place + * fake.ts a deterministic, zero-latency client for tests and dry runs * - * No test in the workspace opens a socket: the fake, an injected transport - * and an injected fetch cover every path the real clients have. + * No test in the workspace opens a socket or spawns a process: the fake, an + * injected transport, an injected fetch and an injected process cover every + * path the real clients have. */ export * from "./client.js"; export * from "./retry.js"; export * from "./chat.js"; export * from "./openrouter.js"; export * from "./cloudflare.js"; +export * from "./claude-code.js"; +export * from "./claude-code-discovery.js"; export * from "./providers.js"; export * from "./fake.js"; diff --git a/packages/llm/src/providers.ts b/packages/llm/src/providers.ts index abc52f4..6f543a6 100644 --- a/packages/llm/src/providers.ts +++ b/packages/llm/src/providers.ts @@ -1,40 +1,59 @@ +import { claudeCodeClient } from "./claude-code.js"; +import { CLAUDE_CODE_PATH_VARIABLE, type ClaudeCodeDiscovery, type ClaudeCodeLocation } from "./claude-code-discovery.js"; import type { LlmClient } from "./client.js"; import { cloudflareGatewayClient } from "./cloudflare.js"; import { openRouterClient } from "./openrouter.js"; import type { RetryOptions } from "./retry.js"; /** - * WHICH PROVIDER, decided from the environment in ONE place. A caller passes - * `auto` or a name; it gets back a client or the exact variables it lacks — - * never a half-configured client that fails on the first call. + * WHICH ADAPTER, decided in ONE place. `LlmClient` (client.ts) is the port; + * openrouter.ts, cloudflare.ts and claude-code.ts are the adapters behind it, + * and this module is the only one that knows there are three. A caller passes + * `auto` or a name; it gets back a client or exactly what it lacks — never a + * half-configured client that fails on the first call. * - * `auto` picks the single provider that is configured. When both are, it - * keeps OpenRouter — the historical default, whose model slugs the docs use — - * and says so, so routing through AI Gateway is always an explicit `--provider`. + * Two kinds of configuration: a key provider is configured when its variables + * are set; Claude Code when discovery (claude-code-discovery.ts, run by the + * caller and handed over as the probe) found the binary. `auto` picks the + * single configured provider. With several, a fixed precedence applies — + * OpenRouter, then Cloudflare, then Claude Code (the order of `PROVIDERS`): + * an exported key is a deliberate act, an installed CLI is ambient — and the + * reason names the flag for each alternative. + * + * The fourth adapter, the Anthropic API with an API key, is one more entry + * here when it comes (PLAN.md §21.6); nothing above the port changes. */ -export const PROVIDERS = ["openrouter", "cloudflare"] as const; +export const PROVIDERS = ["openrouter", "cloudflare", "claude-code"] as const; export type Provider = (typeof PROVIDERS)[number]; export type ProviderChoice = Provider | "auto"; export const PROVIDER_VARIABLES: Readonly> = { openrouter: { required: ["OPENROUTER_API_KEY"], optional: [] }, cloudflare: { required: ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"], optional: ["CLOUDFLARE_AI_GATEWAY_ID"] }, + "claude-code": { required: [], optional: [CLAUDE_CODE_PATH_VARIABLE] }, }; export type Env = Readonly>; +/** What resolution knows beyond the environment: the outcome of looking for the Claude Code binary. Absent = not looked for = not configured. */ +export interface ProviderProbe { + readonly claudeCode?: ClaudeCodeDiscovery | undefined; +} + function present(env: Env, name: string): boolean { const value = env[name]; return value !== undefined && value.trim() !== ""; } -export function missingVariables(provider: Provider, env: Env): string[] { +/** The variables the provider still lacks — for Claude Code, the one way to point at a binary that was not found. */ +export function missingVariables(provider: Provider, env: Env, probe: ProviderProbe = {}): string[] { + if (provider === "claude-code") return probe.claudeCode?.location === undefined ? [CLAUDE_CODE_PATH_VARIABLE] : []; return PROVIDER_VARIABLES[provider].required.filter((name) => !present(env, name)); } -export function isConfigured(provider: Provider, env: Env): boolean { - return missingVariables(provider, env).length === 0; +export function isConfigured(provider: Provider, env: Env, probe: ProviderProbe = {}): boolean { + return missingVariables(provider, env, probe).length === 0; } export interface ProviderResolution { @@ -43,23 +62,52 @@ export interface ProviderResolution { readonly missing: readonly string[]; /** A one-line explanation of the choice, for the human stream. */ readonly reason: string; + /** The binary, when the provider is `claude-code` and discovery found one. */ + readonly claudeCode?: ClaudeCodeLocation; +} + +const LABEL: Readonly> = { openrouter: "OpenRouter", cloudflare: "Cloudflare", "claude-code": "Claude Code" }; +const SWITCH_HINT: Readonly> = { + openrouter: "to route through OpenRouter", + cloudflare: "to route through AI Gateway", + "claude-code": "to run the local Claude Code", +}; + +/** How a configured provider got configured, for the reason line. */ +function configuredBy(provider: Provider, probe: ProviderProbe): string { + if (provider === "claude-code") { + const discovery = probe.claudeCode; + return discovery?.location === undefined ? "claude not found" : `${discovery.reason}: ${discovery.location.path}`; + } + return `${PROVIDER_VARIABLES[provider].required.join(" + ")} set`; } -export function resolveProvider(choice: ProviderChoice, env: Env): ProviderResolution { +export function resolveProvider(choice: ProviderChoice, env: Env, probe: ProviderProbe = {}): ProviderResolution { + const located = (resolution: Omit): ProviderResolution => { + const location = resolution.provider === "claude-code" ? probe.claudeCode?.location : undefined; + return location === undefined ? resolution : { ...resolution, claudeCode: location }; + }; if (choice !== "auto") { - return { provider: choice, missing: missingVariables(choice, env), reason: `--provider ${choice}` }; + const missing = missingVariables(choice, env, probe); + const reason = + choice !== "claude-code" + ? `--provider ${choice}` + : missing.length === 0 + ? `--provider claude-code, ${configuredBy(choice, probe)}` + : (probe.claudeCode?.reason ?? "claude not looked for"); + return located({ provider: choice, missing, reason }); } - const configured = PROVIDERS.filter((p) => isConfigured(p, env)); + const configured = PROVIDERS.filter((p) => isConfigured(p, env, probe)); if (configured.length === 1) { const provider = configured[0]!; - return { provider, missing: [], reason: `${PROVIDER_VARIABLES[provider].required.join(" + ")} set` }; + return located({ provider, missing: [], reason: configuredBy(provider, probe) }); } if (configured.length > 1) { - return { - provider: "openrouter", - missing: [], - reason: "both OpenRouter and Cloudflare are configured; using OpenRouter (pass --provider cloudflare to route through AI Gateway)", - }; + const [first, ...others] = configured; + const names = configured.map((p) => LABEL[p]); + const listed = `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`; + const hints = others.map((p) => `--provider ${p} ${SWITCH_HINT[p]}`).join(", or "); + return located({ provider: first!, missing: [], reason: `${listed} are configured; using ${LABEL[first!]} (pass ${hints})` }); } return { provider: "openrouter", @@ -70,10 +118,16 @@ export function resolveProvider(choice: ProviderChoice, env: Env): ProviderResol export interface ClientOptions { readonly retry?: RetryOptions; + /** For `claude-code`: the binary discovery found. */ + readonly claudeCode?: ClaudeCodeLocation | undefined; } -/** Build the client for a RESOLVED provider; throws when a required variable is missing. */ +/** Build the client for a RESOLVED provider; throws when a required variable (or, for Claude Code, the binary) is missing. */ export function clientFromEnv(provider: Provider, env: Env, options: ClientOptions = {}): LlmClient { + if (provider === "claude-code") { + if (options.claudeCode === undefined) throw new Error(`claude-code: no binary (set ${CLAUDE_CODE_PATH_VARIABLE} or pass --claude-path FILE)`); + return claudeCodeClient({ command: options.claudeCode.path, env, ...(options.retry === undefined ? {} : { retry: options.retry }) }); + } const missing = missingVariables(provider, env); if (missing.length > 0) throw new Error(`${provider}: missing ${missing.join(", ")}`); switch (provider) { @@ -90,3 +144,9 @@ export function clientFromEnv(provider: Provider, env: Env, options: ClientOptio } } } + +/** The client for a resolution with nothing missing — the one call a command makes after `resolveProvider`. */ +export function clientFromResolution(resolution: ProviderResolution, env: Env, options: Omit = {}): LlmClient { + if (resolution.missing.length > 0) throw new Error(`${resolution.provider}: missing ${resolution.missing.join(", ")}`); + return clientFromEnv(resolution.provider, env, { ...options, ...(resolution.claudeCode === undefined ? {} : { claudeCode: resolution.claudeCode }) }); +} diff --git a/packages/llm/test/claude-code-discovery.test.ts b/packages/llm/test/claude-code-discovery.test.ts new file mode 100644 index 0000000..5721058 --- /dev/null +++ b/packages/llm/test/claude-code-discovery.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from "vitest"; +import { + CLAUDE_CODE_PATH_VARIABLE, + claudeExecutableNames, + findClaudeCode, + knownClaudeCodePaths, + pathDirectories, +} from "../src/claude-code-discovery.js"; + +/** A fake disk: only the listed paths exist. */ +function disk(...paths: readonly string[]): (path: string) => boolean { + const present = new Set(paths); + return (path) => present.has(path); +} + +const HOME = "/home/me"; +const ON_PATH = "/usr/local/bin/claude"; +const NATIVE = `${HOME}/.local/bin/claude`; +const posixEnv = { HOME, PATH: "/usr/local/bin:/usr/bin" }; + +describe("findClaudeCode — the search order", () => { + it("takes the explicit path first, then the variable, then PATH, then the known locations", () => { + const exists = disk("/opt/mine/claude", "/opt/env/claude", ON_PATH, NATIVE); + const env = { ...posixEnv, [CLAUDE_CODE_PATH_VARIABLE]: "/opt/env/claude" }; + expect(findClaudeCode({ explicit: "/opt/mine/claude", env, exists, platform: "linux" })).toEqual({ + location: { path: "/opt/mine/claude", source: "option" }, + reason: "--claude-path", + }); + expect(findClaudeCode({ env, exists, platform: "linux" })).toEqual({ + location: { path: "/opt/env/claude", source: "env" }, + reason: CLAUDE_CODE_PATH_VARIABLE, + }); + expect(findClaudeCode({ env: posixEnv, exists, platform: "linux" })).toEqual({ + location: { path: ON_PATH, source: "PATH" }, + reason: "found on PATH", + }); + expect(findClaudeCode({ env: { HOME }, exists, platform: "linux" })).toEqual({ + location: { path: NATIVE, source: "known" }, + reason: "found in a known install location", + }); + }); + + it("an explicit path that does not exist is the answer, with that path in the reason — never a fall-through", () => { + const exists = disk(ON_PATH, NATIVE); + const option = findClaudeCode({ explicit: "/nowhere/claude", env: posixEnv, exists, platform: "linux" }); + expect(option.location).toBeUndefined(); + expect(option.reason).toContain("/nowhere/claude"); + expect(option.reason).toContain("--claude-path"); + const variable = findClaudeCode({ env: { ...posixEnv, [CLAUDE_CODE_PATH_VARIABLE]: "/gone/claude" }, exists, platform: "linux" }); + expect(variable.location).toBeUndefined(); + expect(variable.reason).toContain("/gone/claude"); + expect(variable.reason).toContain(CLAUDE_CODE_PATH_VARIABLE); + }); + + it("says what was searched when nothing is found", () => { + const nothing = findClaudeCode({ env: posixEnv, exists: () => false, platform: "linux" }); + expect(nothing.location).toBeUndefined(); + expect(nothing.reason).toMatch(/PATH/u); + expect(nothing.reason).toMatch(/known install location/u); + }); + + it("ignores blank values: a blank option or variable falls through, an empty PATH entry is skipped", () => { + const exists = disk(ON_PATH, "claude"); + expect(findClaudeCode({ explicit: " ", env: { ...posixEnv, [CLAUDE_CODE_PATH_VARIABLE]: "" }, exists, platform: "linux" })).toMatchObject({ + location: { path: ON_PATH, source: "PATH" }, + }); + expect(pathDirectories({ PATH: ":/usr/bin::/opt/bin: " }, "linux")).toEqual(["/usr/bin", "/opt/bin"]); + // An empty PATH entry is not the current directory: a bare `claude` there is never tried. + expect(findClaudeCode({ env: { PATH: "::" }, exists: disk("claude", "/claude"), platform: "linux" }).location).toBeUndefined(); + }); +}); + +describe("findClaudeCode — the platforms' path shapes", () => { + it("walks PATH with ':' on posix and ';' on win32, reading the Path key of a Windows record", () => { + expect(pathDirectories({ PATH: "/a:/b" }, "linux")).toEqual(["/a", "/b"]); + expect(pathDirectories({ PATH: "/a:/b" }, "darwin")).toEqual(["/a", "/b"]); + expect(pathDirectories({ Path: "C:\\tools;D:\\bin" }, "win32")).toEqual(["C:\\tools", "D:\\bin"]); + expect(pathDirectories({ PATH: "C:\\tools;D:\\bin" }, "win32")).toEqual(["C:\\tools", "D:\\bin"]); + expect(pathDirectories({}, "linux")).toEqual([]); + }); + + it("tries claude.exe and claude.cmd on Windows, claude alone elsewhere, in the shell's order", () => { + expect(claudeExecutableNames("win32")).toEqual(["claude.exe", "claude.cmd", "claude"]); + expect(claudeExecutableNames("linux")).toEqual(["claude"]); + expect(claudeExecutableNames("darwin")).toEqual(["claude"]); + const exists = disk("D:\\bin\\claude.cmd"); + expect(findClaudeCode({ env: { Path: "C:\\tools;D:\\bin" }, exists, platform: "win32" })).toEqual({ + location: { path: "D:\\bin\\claude.cmd", source: "PATH" }, + reason: "found on PATH", + }); + expect(findClaudeCode({ env: { PATH: "/usr/bin:/opt/bin" }, exists: disk("/opt/bin/claude"), platform: "darwin" }).location).toEqual({ + path: "/opt/bin/claude", + source: "PATH", + }); + }); + + it("names the install locations per platform, from HOME on posix and USERPROFILE and APPDATA on Windows", () => { + expect(knownClaudeCodePaths({ HOME }, "linux")).toEqual([ + `${HOME}/.local/bin/claude`, + `${HOME}/.claude/local/claude`, + "/opt/homebrew/bin/claude", + "/usr/local/bin/claude", + ]); + expect(knownClaudeCodePaths({ HOME }, "darwin")).toEqual(knownClaudeCodePaths({ HOME }, "linux")); + expect(knownClaudeCodePaths({}, "linux")).toEqual(["/opt/homebrew/bin/claude", "/usr/local/bin/claude"]); + expect(knownClaudeCodePaths({ USERPROFILE: "C:\\Users\\me", APPDATA: "C:\\Users\\me\\AppData\\Roaming" }, "win32")).toEqual([ + "C:\\Users\\me\\.local\\bin\\claude.exe", + "C:\\Users\\me\\AppData\\Roaming\\npm\\claude.cmd", + ]); + expect(knownClaudeCodePaths({ HOME, USERPROFILE: " " }, "win32")).toEqual([]); + const found = findClaudeCode({ env: { APPDATA: "C:\\Users\\me\\AppData\\Roaming" }, exists: disk("C:\\Users\\me\\AppData\\Roaming\\npm\\claude.cmd"), platform: "win32" }); + expect(found).toEqual({ + location: { path: "C:\\Users\\me\\AppData\\Roaming\\npm\\claude.cmd", source: "known" }, + reason: "found in a known install location", + }); + }); +}); diff --git a/packages/llm/test/claude-code-process.test.ts b/packages/llm/test/claude-code-process.test.ts new file mode 100644 index 0000000..e31855a --- /dev/null +++ b/packages/llm/test/claude-code-process.test.ts @@ -0,0 +1,249 @@ +import { EventEmitter } from "node:events"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + CLAUDE_CODE_DRAIN_GRACE_MS, + CLAUDE_CODE_KILL_GRACE_MS, + childProcessRunner, + type ClaudeCodeChild, + type ClaudeCodeRun, + type ClaudeCodeSpawn, + type ClaudeCodeSpawnOptions, +} from "../src/claude-code.js"; + +/** + * The default `ClaudeCodeProcess` drives a child through the slice of + * `ChildProcess` it needs; these tests hand it a scripted child, so the + * runner's own behaviour — argv as an array, stdin, the two streams, the + * timeout's SIGTERM then SIGKILL, the abort signal, the drain after an exit + * whose pipes a descendant still holds — is exercised without a single + * process being spawned. + */ + +/** A stdio pipe: emits 'data', records whether the runner destroyed it. */ +class FakeStream extends EventEmitter { + destroyed = false; + destroy(): void { + this.destroyed = true; + } +} + +class FakeChild extends EventEmitter implements ClaudeCodeChild { + readonly written: string[] = []; + ended = false; + readonly kills: NodeJS.Signals[] = []; + readonly stdinErrors: ((error: Error) => void)[] = []; + readonly stdin = { + write: (chunk: string): boolean => { + this.written.push(chunk); + return true; + }, + end: (): void => { + this.ended = true; + }, + on: (_event: "error", listener: (error: Error) => void): void => { + this.stdinErrors.push(listener); + }, + }; + readonly stdout = new FakeStream(); + readonly stderr = new FakeStream(); + + kill(signal: NodeJS.Signals): boolean { + this.kills.push(signal); + return true; + } +} + +type Spawned = { command: string; argv: readonly string[]; options: ClaudeCodeSpawnOptions }; + +function fakeSpawn(behaviour: { throws?: Error } = {}): { spawn: ClaudeCodeSpawn; calls: Spawned[]; children: FakeChild[] } { + const calls: Spawned[] = []; + const children: FakeChild[] = []; + const spawn: ClaudeCodeSpawn = (command, argv, options) => { + calls.push({ command, argv, options }); + if (behaviour.throws !== undefined) throw behaviour.throws; + const child = new FakeChild(); + children.push(child); + return child; + }; + return { spawn, calls, children }; +} + +const RUN: ClaudeCodeRun = { + command: "/home/me/.local/bin/claude", + argv: ["-p", "--output-format", "json", "--system-prompt", "a system prompt with spaces and \"quotes\""], + stdin: "# Unit\nexplain it", + env: { PATH: "/usr/bin", HOME: "/home/me" }, + cwd: "/tmp/scratch", + timeoutMs: 600_000, +}; + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("childProcessRunner", () => { + it("spawns the command with the argv as an array (no shell), the run's cwd and env, and pipes every stream", () => { + const { spawn, calls, children } = fakeSpawn(); + void childProcessRunner({ spawn }).run(RUN); + expect(calls).toHaveLength(1); + expect(calls[0]).toEqual({ + command: RUN.command, + argv: RUN.argv, + options: { cwd: RUN.cwd, env: RUN.env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }, + }); + expect(children[0]!.written).toEqual([RUN.stdin]); + expect(children[0]!.ended).toBe(true); + expect(children[0]!.stdinErrors).toHaveLength(1); + }); + + it("collects stdout and stderr as UTF-8 across chunks and resolves with the exit code", async () => { + const { spawn, children } = fakeSpawn(); + const pending = childProcessRunner({ spawn }).run(RUN); + const child = children[0]!; + const accented = Buffer.from("é", "utf8"); + child.stdout.emit("data", Buffer.from('{"type":"result","result":"caf')); + child.stdout.emit("data", accented.subarray(0, 1)); + child.stdout.emit("data", accented.subarray(1)); + child.stdout.emit("data", '"}'); + child.stderr.emit("data", Buffer.from("a warning")); + child.emit("close", 0, null); + await expect(pending).resolves.toEqual({ stdout: '{"type":"result","result":"café"}', stderr: "a warning", code: 0, signal: null }); + }); + + it("reports a spawn failure as the outcome's error, and ignores the close that may follow", async () => { + const { spawn, children } = fakeSpawn(); + const pending = childProcessRunner({ spawn }).run(RUN); + const failure = Object.assign(new Error(`spawn ${RUN.command} ENOENT`), { code: "ENOENT", path: RUN.command, syscall: "spawn" }); + children[0]!.emit("error", failure); + children[0]!.emit("close", -2, null); + await expect(pending).resolves.toEqual({ stdout: "", stderr: "", code: null, signal: null, error: failure }); + }); + + it("reports a spawn that throws synchronously the same way", async () => { + const thrown = Object.assign(new Error("spawn EINVAL"), { code: "EINVAL" }); + const { spawn } = fakeSpawn({ throws: thrown }); + await expect(childProcessRunner({ spawn }).run(RUN)).resolves.toMatchObject({ code: null, error: thrown }); + }); + + it("kills the child at the timeout with SIGTERM, then SIGKILL after the grace period, and says it timed out", async () => { + vi.useFakeTimers(); + const { spawn, children } = fakeSpawn(); + const pending = childProcessRunner({ spawn }).run({ ...RUN, timeoutMs: 1000 }); + const child = children[0]!; + await vi.advanceTimersByTimeAsync(999); + expect(child.kills).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + expect(child.kills).toEqual(["SIGTERM"]); + await vi.advanceTimersByTimeAsync(CLAUDE_CODE_KILL_GRACE_MS - 1); + expect(child.kills).toEqual(["SIGTERM"]); + await vi.advanceTimersByTimeAsync(1); + expect(child.kills).toEqual(["SIGTERM", "SIGKILL"]); + child.emit("close", null, "SIGKILL"); + await expect(pending).resolves.toEqual({ stdout: "", stderr: "", code: null, signal: "SIGKILL", timedOut: true }); + }); + + it("does not escalate to SIGKILL when the child leaves on SIGTERM, and a child that finishes in time is never killed", async () => { + vi.useFakeTimers(); + const { spawn, children } = fakeSpawn(); + const runner = childProcessRunner({ spawn, killGraceMs: 50 }); + const slow = runner.run({ ...RUN, timeoutMs: 100 }); + await vi.advanceTimersByTimeAsync(100); + children[0]!.emit("close", null, "SIGTERM"); + await vi.advanceTimersByTimeAsync(1000); + expect(children[0]!.kills).toEqual(["SIGTERM"]); + await expect(slow).resolves.toMatchObject({ signal: "SIGTERM", timedOut: true }); + + const quick = runner.run({ ...RUN, timeoutMs: 100 }); + children[1]!.emit("close", 0, null); + await vi.advanceTimersByTimeAsync(1000); + expect(children[1]!.kills).toEqual([]); + await expect(quick).resolves.toMatchObject({ code: 0, signal: null }); + expect("timedOut" in (await quick)).toBe(false); + }); + + it("settles within the drain grace once the child has exited while a descendant still holds the pipes — not timed out, nothing killed", async () => { + vi.useFakeTimers(); + const { spawn, children } = fakeSpawn(); + let resolved = false; + const pending = childProcessRunner({ spawn }).run({ ...RUN, timeoutMs: 500 }); + void pending.then(() => { + resolved = true; + }); + const child = children[0]!; + child.stdout.emit("data", Buffer.from('{"type":"result"}')); + child.emit("exit", 0, null); // the child is gone; `sleep 30 &` keeps stdout open, so 'close' never comes on its own + await vi.advanceTimersByTimeAsync(CLAUDE_CODE_DRAIN_GRACE_MS - 1); // the 500 ms timeout has fired by now + expect(resolved).toBe(false); + expect(child.kills).toEqual([]); + expect(child.stdout.destroyed).toBe(false); + await vi.advanceTimersByTimeAsync(1); + expect(child.stdout.destroyed).toBe(true); + expect(child.stderr.destroyed).toBe(true); + await expect(pending).resolves.toEqual({ stdout: '{"type":"result"}', stderr: "", code: 0, signal: null }); + expect(vi.getTimerCount()).toBe(0); + child.emit("close", 0, null); // the late close is ignored + expect(CLAUDE_CODE_DRAIN_GRACE_MS).toBe(1000); + }); + + it("a timed-out child whose orphan keeps the pipes settles within the drain grace after its exit, timed out, without SIGKILL", async () => { + vi.useFakeTimers(); + const { spawn, children } = fakeSpawn(); + const pending = childProcessRunner({ spawn, drainGraceMs: 200 }).run({ ...RUN, timeoutMs: 1000 }); + const child = children[0]!; + await vi.advanceTimersByTimeAsync(1000); + expect(child.kills).toEqual(["SIGTERM"]); + child.emit("exit", null, "SIGTERM"); // sh is gone, its `sleep 20` holds the pipes + await vi.advanceTimersByTimeAsync(200); + await expect(pending).resolves.toEqual({ stdout: "", stderr: "", code: null, signal: "SIGTERM", timedOut: true }); + expect(child.kills).toEqual(["SIGTERM"]); + expect(vi.getTimerCount()).toBe(0); + }); + + it("the 'close' fast path still wins when the streams end on their own: no drain, no destroy", async () => { + vi.useFakeTimers(); + const { spawn, children } = fakeSpawn(); + const pending = childProcessRunner({ spawn }).run(RUN); + const child = children[0]!; + child.emit("exit", 0, null); + child.emit("close", 0, null); + await expect(pending).resolves.toMatchObject({ code: 0, signal: null }); + expect(child.stdout.destroyed).toBe(false); + expect(vi.getTimerCount()).toBe(0); + }); + + it("kills once: a timeout followed by an abort sends one SIGTERM, one SIGKILL, and leaves no timer behind", async () => { + vi.useFakeTimers(); + const { spawn, children } = fakeSpawn(); + const controller = new AbortController(); + const pending = childProcessRunner({ spawn, killGraceMs: 300 }).run({ ...RUN, timeoutMs: 100, signal: controller.signal }); + const child = children[0]!; + await vi.advanceTimersByTimeAsync(100); + controller.abort(new Error("stop")); + expect(child.kills).toEqual(["SIGTERM"]); + await vi.advanceTimersByTimeAsync(300); + expect(child.kills).toEqual(["SIGTERM", "SIGKILL"]); + child.emit("exit", null, "SIGKILL"); + child.emit("close", null, "SIGKILL"); + await expect(pending).rejects.toMatchObject({ name: "LlmError", retryable: false }); + expect(vi.getTimerCount()).toBe(0); + }); + + it("honours the abort signal: kills the child and rejects with a final LlmError carrying the reason", async () => { + const { spawn, children } = fakeSpawn(); + const controller = new AbortController(); + const pending = childProcessRunner({ spawn }).run({ ...RUN, signal: controller.signal }); + const reason = new Error("the user stopped the run"); + controller.abort(reason); + expect(children[0]!.kills).toEqual(["SIGTERM"]); + children[0]!.emit("close", null, "SIGTERM"); + await expect(pending).rejects.toMatchObject({ name: "LlmError", status: undefined, retryable: false, cause: reason }); + }); + + it("rejects without spawning when the signal is already aborted", async () => { + const { spawn, calls } = fakeSpawn(); + const controller = new AbortController(); + controller.abort(); + await expect(childProcessRunner({ spawn }).run({ ...RUN, signal: controller.signal })).rejects.toMatchObject({ name: "LlmError", retryable: false }); + expect(calls).toHaveLength(0); + }); +}); diff --git a/packages/llm/test/claude-code.test.ts b/packages/llm/test/claude-code.test.ts new file mode 100644 index 0000000..c15dc7e --- /dev/null +++ b/packages/llm/test/claude-code.test.ts @@ -0,0 +1,368 @@ +import { readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { describe, expect, it } from "vitest"; +import { + CLAUDE_CODE_DEFAULT_TIMEOUT_MS, + buildClaudeCodeArgv, + claudeCodeClient, + parseClaudeCodeResult, + toClaudeCodeError, + type ClaudeCodeOutcome, + type ClaudeCodeProcess, + type ClaudeCodeRun, +} from "../src/claude-code.js"; +import { LlmError, type LlmRequest } from "../src/client.js"; + +/** A real `claude -p --output-format json --json-schema …` result (2.1.318, Sonnet 5.5). */ +const SAMPLE = readFileSync(new URL("./fixtures/claude-result-sample.json", import.meta.url), "utf8"); + +const COMMAND = "/home/me/.local/bin/claude"; + +const REQUEST: LlmRequest = { + model: "sonnet", + system: "You are a DDD architect.", + user: "# Unit java:p/A.f()\nexplain", + schema: { + name: "operation", + jsonSchema: { type: "object", properties: { name: { type: "string" } }, required: ["name"], additionalProperties: false }, + }, +}; + +/** An outcome of a process that ran to the end; override what the case is about. */ +function outcome(partial: Partial = {}): ClaudeCodeOutcome { + return { stdout: "", stderr: "", code: 0, signal: null, ...partial }; +} + +/** A result JSON as the CLI prints it, with fields overridden. */ +function result(fields: Record = {}): string { + return JSON.stringify({ type: "result", subtype: "success", is_error: false, result: '{"name":"bill"}', ...fields }); +} + +function scripted(outcomes: readonly (ClaudeCodeOutcome | Error)[]): ClaudeCodeProcess & { runs: ClaudeCodeRun[] } { + const runs: ClaudeCodeRun[] = []; + let call = 0; + return { + runs, + run(run) { + runs.push(run); + const next = outcomes[call]; + call += 1; + return next instanceof Error ? Promise.reject(next) : Promise.resolve(next ?? outcome({ code: 1, stderr: "script exhausted" })); + }, + }; +} + +const noSleep = { sleep: () => Promise.resolve(), baseMs: 1 }; + +describe("buildClaudeCodeArgv", () => { + it("builds the headless invocation exactly: one JSON result, the strict schema, no tools, safe mode, nothing persisted", () => { + expect(buildClaudeCodeArgv(REQUEST)).toEqual([ + "-p", + "--output-format", + "json", + "--model", + "sonnet", + "--json-schema", + JSON.stringify(REQUEST.schema.jsonSchema), + "--system-prompt", + REQUEST.system, + "--tools", + "", + "--safe-mode", + "--no-session-persistence", + ]); + }); + + it("never puts the user prompt in the argv (it goes through stdin)", () => { + expect(buildClaudeCodeArgv(REQUEST)).not.toContain(REQUEST.user); + expect(buildClaudeCodeArgv(REQUEST).join("\n")).not.toContain("explain"); + }); + + it("maps reasoningEffort to --effort, with none lowered to low, and omits it when unset", () => { + expect(buildClaudeCodeArgv({ ...REQUEST, reasoningEffort: "high" }).slice(-2)).toEqual(["--effort", "high"]); + expect(buildClaudeCodeArgv({ ...REQUEST, reasoningEffort: "medium" }).slice(-2)).toEqual(["--effort", "medium"]); + expect(buildClaudeCodeArgv({ ...REQUEST, reasoningEffort: "none" }).slice(-2)).toEqual(["--effort", "low"]); + expect(buildClaudeCodeArgv(REQUEST)).not.toContain("--effort"); + }); + + it("ignores temperature and maxTokens, which the CLI cannot take", () => { + expect(buildClaudeCodeArgv({ ...REQUEST, temperature: 0.7, maxTokens: 800 })).toEqual(buildClaudeCodeArgv(REQUEST)); + }); +}); + +describe("the run the client hands to the process", () => { + it("carries the command, the argv, the prompt on stdin, and the defaults: the OS temp dir and a 10 min timeout", async () => { + const process = scripted([outcome({ stdout: result() })]); + const client = claudeCodeClient({ command: COMMAND, process, env: { PATH: "/usr/bin" }, retry: noSleep }); + await client.complete(REQUEST); + expect(process.runs).toHaveLength(1); + const run = process.runs[0]!; + expect(run.command).toBe(COMMAND); + expect(run.argv).toEqual(buildClaudeCodeArgv(REQUEST)); + expect(run.stdin).toBe(REQUEST.user); + expect(run.cwd).toBe(tmpdir()); + expect(run.timeoutMs).toBe(CLAUDE_CODE_DEFAULT_TIMEOUT_MS); + expect(CLAUDE_CODE_DEFAULT_TIMEOUT_MS).toBe(600_000); + expect(run.signal).toBeUndefined(); + }); + + it("takes cwd, timeout and the abort signal from the options and the call", async () => { + const process = scripted([outcome({ stdout: result() })]); + const client = claudeCodeClient({ command: COMMAND, process, env: {}, cwd: "/work", timeoutMs: 1234, retry: noSleep }); + const controller = new AbortController(); + await client.complete(REQUEST, controller.signal); + expect(process.runs[0]).toMatchObject({ cwd: "/work", timeoutMs: 1234, signal: controller.signal }); + }); + + it("passes the caller's environment with every undefined value dropped", async () => { + const process = scripted([outcome({ stdout: result() })]); + const client = claudeCodeClient({ command: COMMAND, process, env: { HOME: "/home/me", UNSET: undefined, PATH: "/bin" }, retry: noSleep }); + await client.complete(REQUEST); + expect(process.runs[0]!.env).toEqual({ HOME: "/home/me", PATH: "/bin" }); + expect(Object.values(process.runs[0]!.env).every((value) => typeof value === "string")).toBe(true); + }); + + it("is named claude-code", () => { + expect(claudeCodeClient({ command: COMMAND, process: scripted([]) }).name).toBe("claude-code"); + }); +}); + +describe("parseClaudeCodeResult", () => { + it("reads the real sample: the structured output, the text, every input token counted, the cost and the served model", () => { + const response = parseClaudeCodeResult(SAMPLE, "sonnet"); + expect(response.json).toEqual({ answer: "ok", n: 2 }); + expect(response.text).toBe('{"answer":"ok","n":2}'); + expect(response.usage).toEqual({ promptTokens: 1142, completionTokens: 74, cost: 0.005304 }); + expect(response.model).toBe("claude-sonnet-5-5"); + }); + + it("falls back to the result text, fenced or plain, when there is no structured output", () => { + expect(parseClaudeCodeResult(result({ result: '```json\n{"name":"x"}\n```' }), "sonnet").json).toEqual({ name: "x" }); + expect(parseClaudeCodeResult(result({ result: '{"name":"y"}' }), "sonnet").json).toEqual({ name: "y" }); + }); + + it("treats an empty or non-JSON result without structured output as a final error", () => { + expect(() => parseClaudeCodeResult(result({ result: "" }), "sonnet")).toThrow(/empty completion/u); + expect(() => parseClaudeCodeResult(result({ result: "Sure! Here it is." }), "sonnet")).toThrow(/non-JSON completion/u); + try { + parseClaudeCodeResult(result({ result: " " }), "sonnet"); + } catch (error) { + expect(error).toBeInstanceOf(LlmError); + expect((error as LlmError).retryable).toBe(false); + } + }); + + it("reports the requested model when modelUsage is absent, and the key when canonicalModel is", () => { + expect(parseClaudeCodeResult(result(), "sonnet").model).toBe("sonnet"); + expect(parseClaudeCodeResult(result({ modelUsage: { "claude-opus-5-5": { costUSD: 1 } } }), "sonnet").model).toBe("claude-opus-5-5"); + expect(parseClaudeCodeResult(result({ modelUsage: { alias: { canonicalModel: "claude-sonnet-5-5" } } }), "sonnet").model).toBe("claude-sonnet-5-5"); + }); + + it("reports no usage when the result has none, counts missing numbers as 0, and takes the cost only when it is a number", () => { + expect(parseClaudeCodeResult(result(), "sonnet").usage).toBeUndefined(); + expect(parseClaudeCodeResult(result({ usage: { input_tokens: 5, output_tokens: 7 } }), "sonnet").usage).toEqual({ promptTokens: 5, completionTokens: 7 }); + expect(parseClaudeCodeResult(result({ usage: { cache_read_input_tokens: 9 }, total_cost_usd: "0.1" }), "sonnet").usage).toEqual({ promptTokens: 9, completionTokens: 0 }); + expect(parseClaudeCodeResult(result({ usage: {}, total_cost_usd: 0.25 }), "sonnet").usage).toEqual({ promptTokens: 0, completionTokens: 0, cost: 0.25 }); + }); + + it("is a failure, not a response, when the result says is_error or a subtype other than success", () => { + expect(() => parseClaudeCodeResult(result({ is_error: true, result: "something broke" }), "sonnet")).toThrow(LlmError); + expect(() => parseClaudeCodeResult(result({ subtype: "error_max_turns" }), "sonnet")).toThrow(LlmError); + expect(() => parseClaudeCodeResult("not json at all", "sonnet")).toThrow(/not the result JSON/u); + expect(() => parseClaudeCodeResult('{"type":"assistant"}', "sonnet")).toThrow(/not the result JSON/u); + }); +}); + +describe("toClaudeCodeError — the error table", () => { + const spawnFailure = (code: string): NodeJS.ErrnoException => Object.assign(new Error(`spawn ${COMMAND} ${code}`), { code, path: COMMAND, syscall: "spawn" }); + const run = { command: COMMAND, timeoutMs: 600_000 }; + + it("a binary that cannot be spawned (ENOENT) is final and names the command and the code", () => { + const error = toClaudeCodeError(outcome({ code: null, error: spawnFailure("ENOENT") }), undefined, run); + expect(error).toBeInstanceOf(LlmError); + expect(error).toMatchObject({ status: undefined, retryable: false }); + expect(error.message).toContain(COMMAND); + expect(error.message).toContain("ENOENT"); + expect(error.cause).toBeInstanceOf(Error); + }); + + it("a binary that cannot be executed (EACCES) is final too", () => { + const error = toClaudeCodeError(outcome({ code: null, error: spawnFailure("EACCES") }), undefined, run); + expect(error).toMatchObject({ status: undefined, retryable: false }); + expect(error.message).toContain("EACCES"); + }); + + it("a call killed at the timeout is final and says how long it had", () => { + const error = toClaudeCodeError(outcome({ code: null, signal: "SIGKILL", timedOut: true }), undefined, { command: COMMAND, timeoutMs: 1500 }); + expect(error).toMatchObject({ status: undefined, retryable: false }); + expect(error.message).toContain("1500"); + }); + + it("a result with a numeric api_error_status takes that status and the HTTP retry rule", () => { + const overloaded = JSON.parse(result({ is_error: true, subtype: "error", api_error_status: 503, result: "upstream" })) as unknown; + expect(toClaudeCodeError(outcome({ code: 1 }), overloaded, run)).toMatchObject({ status: 503, retryable: true }); + const rejected = JSON.parse(result({ is_error: true, subtype: "error", api_error_status: 400, result: "bad request" })) as unknown; + expect(toClaudeCodeError(outcome({ code: 1 }), rejected, run)).toMatchObject({ status: 400, retryable: false, message: expect.stringContaining("bad request") }); + }); + + it("without a status, 'not logged in', 'invalid api key', 'unauthorized' and 'authentication' are a final 401", () => { + for (const text of ["Not logged in · Please run /login", "Invalid API key", "unauthorized", "Authentication failed"]) { + const parsed = JSON.parse(result({ is_error: true, subtype: "error", result: text })) as unknown; + expect(toClaudeCodeError(outcome({ code: 1 }), parsed, run), text).toMatchObject({ status: 401, retryable: false }); + } + }); + + it("'rate limit', '429' and 'too many requests' are a retryable 429, read from stderr when stdout has nothing", () => { + for (const text of ["Rate limit reached", "API Error: 429", "too many requests"]) { + expect(toClaudeCodeError(outcome({ code: 1, stderr: text }), undefined, run), text).toMatchObject({ status: 429, retryable: true }); + } + }); + + it("'overloaded' and '529' are a retryable 529", () => { + const parsed = JSON.parse(result({ is_error: true, subtype: "error", errors: [{ message: "Overloaded" }] })) as unknown; + expect(toClaudeCodeError(outcome({ code: 1 }), parsed, run)).toMatchObject({ status: 529, retryable: true }); + expect(toClaudeCodeError(outcome({ code: 1, stderr: "API Error: 529" }), undefined, run)).toMatchObject({ status: 529, retryable: true }); + }); + + it("'budget', 'credit', 'billing' and '402' are a final 402", () => { + for (const text of ["Budget exceeded", "Your credit balance is too low", "billing problem", "API Error: 402"]) { + const parsed = JSON.parse(result({ is_error: true, subtype: "error", error: text })) as unknown; + expect(toClaudeCodeError(outcome({ code: 1 }), parsed, run), text).toMatchObject({ status: 402, retryable: false }); + } + }); + + it("anything else is final with no status, and the message carries the exit code and what was said", () => { + const error = toClaudeCodeError(outcome({ code: 1, stderr: "segfault somewhere" }), undefined, run); + expect(error).toMatchObject({ status: undefined, retryable: false }); + expect(error.message).toContain("exit 1"); + expect(error.message).toContain("segfault somewhere"); + const killed = toClaudeCodeError(outcome({ code: null, signal: "SIGSEGV" }), undefined, run); + expect(killed.message).toContain("SIGSEGV"); + }); + + it("exit 0 with stdout that is not the result JSON is final with no status", () => { + const error = toClaudeCodeError(outcome({ code: 0, stdout: "Welcome to Claude Code!" }), undefined, run); + expect(error).toMatchObject({ status: undefined, retryable: false }); + expect(error.message).toContain("not the result JSON"); + expect(error.message).toContain("Welcome to Claude Code!"); + }); + + /** An error arm as the SDK documents it: `is_error`, the subtype, `errors: string[]`, no `result`. */ + const arm = (subtype: string, errors: readonly string[], extra: Record = {}): unknown => + JSON.parse(result({ is_error: true, subtype, result: undefined, errors, ...extra })) as unknown; + + it("error_max_turns is final with no status; the errors array is the message", () => { + const error = toClaudeCodeError(outcome({ code: 1 }), arm("error_max_turns", ["Reached max turns (1)"]), run); + expect(error).toMatchObject({ status: undefined, retryable: false }); + expect(error.message).toContain("error_max_turns"); + expect(error.message).toContain("Reached max turns (1)"); + }); + + it("error_during_execution is final with no status, unless the errors say what the API answered", () => { + const plain = toClaudeCodeError(outcome({ code: 1 }), arm("error_during_execution", ["Something went wrong while running"]), run); + expect(plain).toMatchObject({ status: undefined, retryable: false }); + expect(plain.message).toContain("Something went wrong while running"); + const overloaded = toClaudeCodeError(outcome({ code: 1 }), arm("error_during_execution", ["API Error: 529 Overloaded"]), run); + expect(overloaded).toMatchObject({ status: 529, retryable: true }); + }); + + it("error_max_budget_usd is a final 402 even when the errors never spell 'budget'", () => { + const error = toClaudeCodeError(outcome({ code: 1 }), arm("error_max_budget_usd", ["Spent $0.0531 of the $0.05 limit"]), run); + expect(error).toMatchObject({ status: 402, retryable: false }); + expect(error.message).toContain("error_max_budget_usd"); + expect(error.message).toContain("$0.05 limit"); + }); + + it("error_max_structured_output_retries is final and says the model never produced schema-valid output", () => { + const error = toClaudeCodeError(outcome({ code: 1 }), arm("error_max_structured_output_retries", ["Structured output validation failed 3 times"]), run); + expect(error).toMatchObject({ status: undefined, retryable: false }); + expect(error.message).toMatch(/schema-valid/u); + expect(error.message).toContain("validation failed 3 times"); + }); + + it("a numeric api_error_status wins on any arm — a success arm included — and makes the result a failure", () => { + const success = JSON.parse(result({ api_error_status: 529 })) as unknown; + const error = toClaudeCodeError(outcome({ code: 0 }), success, run); + expect(error).toMatchObject({ status: 529, retryable: true }); + expect(error.message).toContain("529"); + expect(toClaudeCodeError(outcome({ code: 1 }), arm("error_max_budget_usd", ["limit"], { api_error_status: 500 }), run)).toMatchObject({ status: 500, retryable: true }); + expect(toClaudeCodeError(outcome({ code: 1 }), arm("error_during_execution", ["Not logged in"], { api_error_status: 400 }), run)).toMatchObject({ status: 400, retryable: false }); + try { + parseClaudeCodeResult(result({ api_error_status: 500 }), "sonnet"); + expect.unreachable("a success arm terminated by an API error is not a response"); + } catch (error) { + expect(error).toBeInstanceOf(LlmError); + expect((error as LlmError).status).toBe(500); + } + }); +}); + +describe("claudeCodeClient", () => { + it("runs the process once and returns the parsed response", async () => { + const process = scripted([outcome({ stdout: SAMPLE })]); + const client = claudeCodeClient({ command: COMMAND, process, env: {}, retry: noSleep }); + const response = await client.complete(REQUEST); + expect(response.json).toEqual({ answer: "ok", n: 2 }); + expect(response.model).toBe("claude-sonnet-5-5"); + expect(response.usage).toEqual({ promptTokens: 1142, completionTokens: 74, cost: 0.005304 }); + expect(process.runs).toHaveLength(1); + }); + + it("retries a 429 outcome and then succeeds: two runs, one response", async () => { + const delays: number[] = []; + const limited = outcome({ code: 1, stdout: result({ is_error: true, subtype: "error", api_error_status: 429, result: "rate limited" }) }); + const process = scripted([limited, outcome({ stdout: result({ result: '{"name":"ok"}' }) })]); + const client = claudeCodeClient({ + command: COMMAND, + process, + env: {}, + retry: { + sleep: (ms) => { + delays.push(ms); + return Promise.resolve(); + }, + baseMs: 1, + }, + }); + await expect(client.complete(REQUEST)).resolves.toMatchObject({ json: { name: "ok" } }); + expect(process.runs).toHaveLength(2); + expect(delays).toEqual([1]); + }); + + it("retries a success arm that carries a transient api_error_status, as the failure it reports", async () => { + const terminated = outcome({ code: 0, stdout: result({ api_error_status: 529 }) }); + const process = scripted([terminated, outcome({ stdout: result({ result: '{"name":"ok"}' }) })]); + const client = claudeCodeClient({ command: COMMAND, process, env: {}, retry: noSleep }); + await expect(client.complete(REQUEST)).resolves.toMatchObject({ json: { name: "ok" } }); + expect(process.runs).toHaveLength(2); + }); + + it("does not retry a final error: one run, the LlmError surfaced", async () => { + const denied = outcome({ code: 1, stdout: result({ is_error: true, subtype: "error", result: "Not logged in" }) }); + const process = scripted([denied, outcome({ stdout: result() })]); + const client = claudeCodeClient({ command: COMMAND, process, env: {}, retry: noSleep }); + await expect(client.complete(REQUEST)).rejects.toMatchObject({ name: "LlmError", status: 401, retryable: false }); + expect(process.runs).toHaveLength(1); + }); + + it("does not retry a spawn failure, a timeout or a malformed stdout", async () => { + const enoent = outcome({ code: null, error: Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" }) }); + for (const first of [enoent, outcome({ code: null, timedOut: true }), outcome({ stdout: "" })]) { + const process = scripted([first, outcome({ stdout: result() })]); + const client = claudeCodeClient({ command: COMMAND, process, env: {}, retry: noSleep }); + await expect(client.complete(REQUEST)).rejects.toMatchObject({ name: "LlmError", retryable: false }); + expect(process.runs).toHaveLength(1); + } + }); + + it("wraps a foreign rejection of the process in a final LlmError and passes an LlmError through", async () => { + const foreign = scripted([new TypeError("bug in the runner")]); + await expect(claudeCodeClient({ command: COMMAND, process: foreign, env: {}, retry: noSleep }).complete(REQUEST)).rejects.toMatchObject({ + name: "LlmError", + retryable: false, + cause: expect.any(TypeError), + }); + const own = new LlmError("aborted", undefined, false); + await expect(claudeCodeClient({ command: COMMAND, process: scripted([own]), env: {}, retry: noSleep }).complete(REQUEST)).rejects.toBe(own); + }); +}); diff --git a/packages/llm/test/fixtures/claude-result-sample.json b/packages/llm/test/fixtures/claude-result-sample.json new file mode 100644 index 0000000..1a75178 --- /dev/null +++ b/packages/llm/test/fixtures/claude-result-sample.json @@ -0,0 +1 @@ +{"duration_api_ms":2836,"stop_reason":"tool_use","session_id":"386402c5-2b58-4e77-abd0-19069fae8bd7","total_cost_usd":0.005304,"usage":{"input_tokens":2,"cache_creation_input_tokens":1140,"cache_read_input_tokens":0,"output_tokens":74,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":1140,"ephemeral_5m_input_tokens":0},"inference_geo":"global","iterations":[{"input_tokens":2,"output_tokens":74,"cache_read_input_tokens":0,"cache_creation_input_tokens":1140,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1140},"type":"message"}],"speed":"standard","fallback_credit":null},"modelUsage":{"claude-sonnet-5-5":{"inputTokens":2,"outputTokens":74,"cacheReadInputTokens":0,"cacheCreationInputTokens":1140,"webSearchRequests":0,"costUSD":0.005304,"contextWindow":1000000,"maxOutputTokens":128000,"thinkingTokens":0,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationEphemeral1hInputTokens":1140,"canonicalModel":"claude-sonnet-5-5","provider":"firstParty","costBasis":"list"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subagent_stats":{"spawned":0},"safety_stops":0,"is_error":false,"num_turns":2,"subtype":"success","api_error_status":null,"result":"{\"answer\":\"ok\",\"n\":2}","structured_output":{"answer":"ok","n":2},"ttft_ms":2864,"type":"result","duration_ms":2896,"uuid":"a4cd898d-d6a6-4032-b615-d61e7303e50a","result_index":0} diff --git a/packages/llm/test/providers.test.ts b/packages/llm/test/providers.test.ts index f6fa496..07f10db 100644 --- a/packages/llm/test/providers.test.ts +++ b/packages/llm/test/providers.test.ts @@ -1,8 +1,12 @@ import { describe, expect, it } from "vitest"; -import { clientFromEnv, isConfigured, missingVariables, resolveProvider } from "../src/providers.js"; +import type { ClaudeCodeDiscovery } from "../src/claude-code-discovery.js"; +import { clientFromEnv, clientFromResolution, isConfigured, missingVariables, resolveProvider } from "../src/providers.js"; const OR = { OPENROUTER_API_KEY: "sk-or" }; const CF = { CLOUDFLARE_API_TOKEN: "cf", CLOUDFLARE_ACCOUNT_ID: "acc" }; +const CLAUDE = "/home/me/.local/bin/claude"; +const FOUND: ClaudeCodeDiscovery = { location: { path: CLAUDE, source: "PATH" }, reason: "found on PATH" }; +const NOT_FOUND: ClaudeCodeDiscovery = { location: undefined, reason: "no claude on PATH or in a known install location" }; describe("resolveProvider", () => { it("auto picks the one provider that is configured", () => { @@ -40,3 +44,60 @@ describe("clientFromEnv", () => { expect(() => clientFromEnv("cloudflare", OR)).toThrow(/CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID/); }); }); + +describe("claude-code in resolution", () => { + it("is configured only when the probe found a binary; what it lacks is the one variable that points at one", () => { + expect(isConfigured("claude-code", {}, { claudeCode: FOUND })).toBe(true); + expect(isConfigured("claude-code", {}, { claudeCode: NOT_FOUND })).toBe(false); + expect(isConfigured("claude-code", { CLAUDE_CODE_PATH: CLAUDE })).toBe(false); + expect(missingVariables("claude-code", {}, { claudeCode: NOT_FOUND })).toEqual(["CLAUDE_CODE_PATH"]); + expect(missingVariables("claude-code", {}, { claudeCode: FOUND })).toEqual([]); + }); + + it("auto picks it when it is the only one, with how it was found and where in the reason", () => { + const resolution = resolveProvider("auto", {}, { claudeCode: FOUND }); + expect(resolution).toMatchObject({ provider: "claude-code", missing: [], claudeCode: FOUND.location }); + expect(resolution.reason).toContain("found on PATH"); + expect(resolution.reason).toContain(CLAUDE); + expect(resolveProvider("auto", {}, { claudeCode: NOT_FOUND })).toEqual({ provider: "openrouter", missing: ["OPENROUTER_API_KEY"], reason: "no provider configured" }); + }); + + it("auto prefers an exported key over the installed CLI — OpenRouter, then Cloudflare — and names --provider claude-code", () => { + const withOpenRouter = resolveProvider("auto", OR, { claudeCode: FOUND }); + expect(withOpenRouter.provider).toBe("openrouter"); + expect(withOpenRouter.reason).toContain("--provider claude-code"); + expect(withOpenRouter.claudeCode).toBeUndefined(); + const withCloudflare = resolveProvider("auto", CF, { claudeCode: FOUND }); + expect(withCloudflare.provider).toBe("cloudflare"); + expect(withCloudflare.reason).toContain("--provider claude-code"); + const all = resolveProvider("auto", { ...OR, ...CF }, { claudeCode: FOUND }); + expect(all.provider).toBe("openrouter"); + expect(all.reason).toContain("--provider cloudflare"); + expect(all.reason).toContain("--provider claude-code"); + }); + + it("--provider claude-code with a binary found mentions the path; without one, lists CLAUDE_CODE_PATH and the discovery's reason", () => { + const found = resolveProvider("claude-code", OR, { claudeCode: FOUND }); + expect(found).toMatchObject({ provider: "claude-code", missing: [], claudeCode: FOUND.location }); + expect(found.reason).toContain("--provider claude-code"); + expect(found.reason).toContain(CLAUDE); + const missing = resolveProvider("claude-code", OR, { claudeCode: NOT_FOUND }); + expect(missing).toMatchObject({ provider: "claude-code", missing: ["CLAUDE_CODE_PATH"], reason: NOT_FOUND.reason }); + expect(missing.claudeCode).toBeUndefined(); + const explicit = resolveProvider("claude-code", {}, { claudeCode: { location: undefined, reason: "--claude-path /nowhere/claude does not exist" } }); + expect(explicit.reason).toBe("--claude-path /nowhere/claude does not exist"); + expect(resolveProvider("claude-code", {}).missing).toEqual(["CLAUDE_CODE_PATH"]); + }); + + it("clientFromEnv builds a client named claude-code from the location, and refuses without one", () => { + expect(clientFromEnv("claude-code", {}, { claudeCode: FOUND.location }).name).toBe("claude-code"); + expect(() => clientFromEnv("claude-code", { CLAUDE_CODE_PATH: CLAUDE })).toThrow(/CLAUDE_CODE_PATH|--claude-path/u); + }); + + it("clientFromResolution round-trips the resolved location into the client", () => { + const resolution = resolveProvider("claude-code", {}, { claudeCode: FOUND }); + expect(clientFromResolution(resolution, {}).name).toBe("claude-code"); + expect(clientFromResolution(resolveProvider("auto", OR, { claudeCode: FOUND }), OR).name).toBe("openrouter"); + expect(() => clientFromResolution(resolveProvider("claude-code", {}, { claudeCode: NOT_FOUND }), {})).toThrow(/CLAUDE_CODE_PATH/u); + }); +}); From d0eb1ac8ba133cf573b1acb7ec50339d06f5257d Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Tue, 10 Nov 2026 10:36:16 +0000 Subject: [PATCH 2/3] feat(cli): explain --provider claude-code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit M20b. `codegraph explain --provider claude-code [--claude-path FILE]`; --model defaults per provider and is resolved before the plan, so --dry-run and --estimate show `sonnet`; --max-tokens is ignored on Claude Code with a note. PLAN §21 (Phase 18) records the port, the three adapters and the Anthropic API as a named empty slot; docs, README, CLAUDE.md and the website's explain pages follow. Live run on the Java fixture (Claude Code 2.1.322): 68 calls, 0 failed, 79 records stamped claude-sonnet-5-5, decode-clean, $1.03. Prompt tokens come out ~2.7x the estimate: Claude Code adds ~2 500 tokens of scaffolding per call that the estimate does not count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PKCVh1q6FUhWzQi6KYtoTz --- CLAUDE.md | 16 +- PLAN.md | 202 +++++++++++++++++- README.md | 15 +- WEBSITE.md | 2 +- docs/cli.md | 35 ++- docs/insights.md | 81 +++++-- docs/model-metamodel.md | 2 +- packages/cli/src/args.ts | 63 ++++-- packages/cli/src/commands/explain.ts | 96 ++++++--- packages/cli/test/explain.test.ts | 153 ++++++++++++- .../docs/explanation/explaining-bottom-up.md | 21 +- website/content/docs/how-to/explain-cost.md | 29 ++- .../reference/artifacts/insights-jsonl.md | 4 +- website/content/docs/reference/cli/explain.md | 11 +- website/content/docs/reference/environment.md | 19 +- website/content/docs/tutorials/explain.md | 18 +- 16 files changed, 643 insertions(+), 124 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a48d1f0..db1c29f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,9 +80,11 @@ packages/insights/ @codegraph/insights — the bottom-up EXPLANATION walk: uni database) and its export, the `.insights.jsonl` side-car (Specy domain vocabulary). Pure computation: source, model calls and the database are injected. -packages/llm/ @codegraph/llm — LlmClient + OpenRouter (SDK) + Cloudflare - AI Gateway (REST) implementations + a deterministic fake. - The ONLY package that may import @openrouter/sdk. +packages/llm/ @codegraph/llm — LlmClient (the PORT) + its adapters: OpenRouter + (SDK), Cloudflare AI Gateway (REST), Claude Code headless + (subprocess: `claude -p`, found by discovery, no key) + a + deterministic fake. The Anthropic API (key) is a named empty + slot (PLAN §21.6). The ONLY package that may import @openrouter/sdk. packages/cli/ @codegraph/cli — `codegraph` command. packages/viz/ @codegraph/viz — Three.js code city: renders a laid-out city.json artifact (its ONLY input; guard-enforced). The @@ -246,9 +248,15 @@ node scripts/homebrew/render.mjs --version X.Y.Z --sums SHA256SUMS [--npm-sha256 ./bin/codegraph explain model.jsonl --src DIR --dry-run # the walk plan, no call ./bin/codegraph explain model.jsonl --src DIR --estimate --price-in 0.10 --price-out 0.60 # tokens in/out + cost, no call OPENROUTER_API_KEY=… ./bin/codegraph explain model.jsonl --src DIR [--max-calls N] [--yes] -# [--model SLUG] (default openai/gpt-5.6-luna) [--rollup-model SLUG] (types+modules; defaults to --model) +# [--model SLUG] (default per provider: openai/gpt-5.6-luna on openrouter/cloudflare, sonnet on claude-code) +# [--rollup-model SLUG] (types+modules; defaults to --model) # prints the estimate on stderr and asks [y/N] first; --yes (required without a TTY) skips it # or CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… [--provider cloudflare] +# or ./bin/codegraph explain model.jsonl --src DIR --provider claude-code [--claude-path FILE] +# the installed, logged-in Claude Code in headless mode (`claude -p`, one process per call, Sonnet, no key); +# the binary: --claude-path, else CLAUDE_CODE_PATH, else `claude` on PATH, else the known install locations. +# --provider auto (default) takes the one configured; with several: OpenRouter, Cloudflare, then Claude Code. +# --max-tokens does not apply to claude-code (noted, ignored); --concurrency N is N processes # → model.insights.db (the working copy: one commit per finished unit) and its export # model.insights.jsonl, both beside the model; re-runs redo only what changed ./bin/codegraph explain model.jsonl --export # the side-car from the store (after a killed run); no model read diff --git a/PLAN.md b/PLAN.md index 4d92611..5a1b6be 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2729,7 +2729,7 @@ under one command-line contract (§13.5, schemas/README.md §8) exactly so this could be true: the app needs to know nothing about them but that contract and the file extensions they claim. -Locked decisions, each with its reason (the delta table in §22 repeats them): +Locked decisions, each with its reason (the delta table in §23 repeats them): - **Tauri is the shell, not a runtime.** Window, native menu, folder dialog, drag-and-drop, sidecar lifecycle, bundling, signing and notarization. No @@ -3634,7 +3634,7 @@ file without one of them lying, so they do not share one: | will not open | degrade to the `.jsonl`, silently | a usage error naming the file; never overwritten | | committed / shared | never | never — the JSONL export is what is committed, diffed and handed to Specy | -Locked decisions, each with its reason (the delta table in §22 repeats them): +Locked decisions, each with its reason (the delta table in §23 repeats them): - **The db is the working copy; the JSONL becomes its deterministic export.** `.insights.jsonl` keeps its format, its byte-determinism and its @@ -5872,7 +5872,196 @@ green; the coverage table and the cost filled in this section. --- -## 21. Milestones +## 21. Phase 18 — Model providers as adapters: Claude Code headless (M20) + +Motivation: `explain` buys its explanations call by call from a provider, and +until now a provider meant an API key — `OPENROUTER_API_KEY`, or a Cloudflare +token in front of one. A developer who already pays for Claude Code has a +model on the machine: the CLI's headless mode (`claude -p`) answers one +prompt per process, takes a system prompt and a JSON Schema, and prints one +JSON object with the document, the tokens and the cost. The request: let +`explain` use that installation — Sonnet by default — instead of OpenRouter, +detect the binary or take its path as a parameter, and name the architecture +so a direct Anthropic API client can follow without touching the walk. + +**Decision: the port is what `@codegraph/llm` already has — `LlmClient` +(`client.ts`: one structured completion in, parsed JSON out, one error type +with `retryable` decided once). The adapters are the provider modules behind +it: OpenRouter (SDK), Cloudflare AI Gateway (REST) and now Claude Code (a +subprocess). The fourth — the Anthropic API with an API key — is a named, +empty slot, not a stub.** Nothing above the port changes shape: the run's +`Completer`, the CLI's `completerFor`, the store and the side-car are +untouched; `provider` in the side-car header was already a free string. +Rejected, each with its reason: + +- **The Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) as the adapter.** + It bundles its own copy of Claude Code: the user's install, login and + version would be bypassed, a second provider SDK would enter the workspace + (the boundary test guards ONE), and `query()` is an agent loop where one + completion is wanted. The CLI on the machine IS the installation the + request names. +- **The Anthropic SDK now.** "Maybe in the future" is not a milestone; a + stub is an unwired subsystem (CLAUDE.md). §21.6 says exactly where it goes. +- **`--bare` for a clean process.** `--bare` restricts authentication to + `ANTHROPIC_API_KEY`: a subscription login stops working, which is the + case this phase exists for. `--safe-mode` keeps authentication and model + selection and disables every customization (CLAUDE.md, hooks, plugins, + MCP servers, output styles) — the Claude Code persona is replaced by + `--system-prompt` anyway. +- **A hand-rolled JSON mode** (`--output-format text` + fence stripping). + `--json-schema` is the CLI's own structured output; the answer arrives + parsed in `structured_output`. The fenced-text fallback stays for a + version that lacks it. +- **Probing `claude --version` during resolution.** Discovery is a pure + function of (option, environment, `exists`), like the key providers are of + the environment; a process per resolution would make `--dry-run` spawn. + +### 21.1 The adapter (`packages/llm/src/claude-code.ts`) + +One call = one process. Measured on 2.1.318 (2026-11-05, Sonnet 5.5): a +2-token prompt costs 1 140 cache-creation tokens of scaffolding plus the +prompt, $0.0053, 2.8 s wall; `--concurrency N` is N processes. + +| argument | why | +|---|---| +| `-p --output-format json` | one JSON object on stdout, the prompt from stdin | +| `--model ` | `sonnet` by default (Claude Code's alias for the latest Sonnet); a full id (`claude-sonnet-5-5`) pins the fingerprint | +| `--json-schema ` | the strict response schema, as the other adapters send it | +| `--system-prompt ` | REPLACES the default system prompt: no persona, no tool talk | +| `--tools ""` | no tool may run: the model can only answer | +| `--safe-mode` | no CLAUDE.md, hooks, plugins, MCP, output styles; auth untouched | +| `--no-session-persistence` | nothing written under `~/.claude/projects` | +| `--effort ` | from `reasoningEffort` when set (`none` → `low`) | + +The **user prompt goes through stdin**: a context pack with source can +exceed Linux's 128 KB per-argument limit (`MAX_ARG_STRLEN`); the system +prompt (~6 KB) and the schema ride as arguments. The working directory is +the OS temp directory — no CLAUDE.md of the caller's tree, `--safe-mode` or +not. The environment is the parent's: the `CLAUDECODE` nesting markers of a +`codegraph` run started from inside Claude Code do not stop a `-p` child +(tested on 2.1.318). + +Reading the result (`type: "result"`): + +| field | → | +|---|---| +| `structured_output` | `json`; absent → `result` through the shared `extractJson` (fenced text tolerated) | +| `result` | `text` | +| `usage.input_tokens + cache_creation_input_tokens + cache_read_input_tokens` | `promptTokens` — what was sent, cached or not, as the chat adapters count it | +| `usage.output_tokens` | `completionTokens` | +| `total_cost_usd` | `cost` | +| the key of `modelUsage` (its `canonicalModel`) | `model` — what served, not the alias asked for | + +Errors, every one an `LlmError` (the port's one type): + +| what happened | status | retryable | +|---|---|---| +| the binary cannot be spawned (`ENOENT`, `EACCES`) | — | no: the message names the path | +| the call exceeded `timeoutMs` (default 10 min): the child is killed | — | no (`--retry-failed` redoes the unit) | +| non-zero exit, or `is_error`/`subtype ≠ success`: `api_error_status` is a number | that status | the HTTP rule (`isRetryableStatus`) | +| … no status: the message says not logged in / invalid key / unauthorized | 401 | no — and `FATAL_STATUSES` aborts the run | +| … rate limit / 429 | 429 | yes | +| … overloaded / 529 | 529 | yes | +| … budget / credit / billing / 402 | 402 | no, aborts the run | +| … anything else | — | no | +| exit 0 but stdout is not the result JSON | — | no | + +The CLI retries its own API errors before answering, so the adapter's +`withRetry` only covers what leaks. What the port carries and the CLI cannot +take — `temperature`, `maxTokens` — is ignored; `explain` says so once when +`--max-tokens` is combined with this provider. + +The subprocess is held behind a one-function seam (`ClaudeCodeProcess.run`), +like OpenRouter's transport and Cloudflare's `fetch`: every test drives the +adapter with a fake process and recorded stdout/stderr/exit, and no test in +the workspace spawns anything. + +### 21.2 Discovery (`packages/llm/src/claude-code-discovery.ts`) + +`findClaudeCode({ explicit, env, exists, platform })` — pure — looks, in +order: `--claude-path` (explicit); `CLAUDE_CODE_PATH`; `claude` in each +directory of `PATH` (`claude.exe`/`claude.cmd` also on Windows); then the +install locations the docs name: + +| method | path | +|---|---| +| native installer (macOS, Linux, WSL) | `~/.local/bin/claude` | +| native installer (Windows) | `%USERPROFILE%\.local\bin\claude.exe` | +| legacy local install | `~/.claude/local/claude` | +| Homebrew | `/opt/homebrew/bin/claude`, `/usr/local/bin/claude` | +| npm global (Windows) | `%APPDATA%\npm\claude.cmd` | + +An explicit path (option or variable) that does not exist is an error with +that path in it — never a fall-through to a different binary. On Windows an +npm-global `claude.cmd` is found but cannot be spawned: the adapter passes +argv without a shell and Node refuses `.cmd`/`.bat` there (`EINVAL`, the +CVE-2024-27980 mitigation) — the native installer's `claude.exe` is the +supported binary, `--claude-path` points at it. The result +carries `source` (`option`, `env`, `PATH`, `known`), which the provider line +prints. + +### 21.3 Resolution (`providers.ts`) + +`PROVIDERS` gains `claude-code`; it is *configured* when discovery found a +binary (`PROVIDER_VARIABLES["claude-code"]` requires nothing, lists +`CLAUDE_CODE_PATH` as optional). `resolveProvider(choice, env, { claudeCode })` +keeps its rule — the single configured provider wins — and, with several, a +fixed precedence: OpenRouter, then Cloudflare, then Claude Code; the reason +names the flag for each alternative. An exported key is a deliberate act; an +installed CLI is ambient, so it never overrides one. For `claude-code` the +`missing` list is `["CLAUDE_CODE_PATH"]` — the way to fix it — and the +reason says what was searched. `clientFromEnv` takes the found location and +builds `claudeCodeClient`; the seam's `clientFor` takes the whole resolution. + +### 21.4 The CLI + +- `--provider claude-code`; `--claude-path FILE`. Under `--provider auto`, + `--claude-path` alone IMPLIES `claude-code` — a user who named a binary + meant to run it, key or no key; otherwise a path that does not exist would + vanish behind "no provider configured". +- `--model` defaults **per provider**: `openai/gpt-5.6-luna` on the key + providers (unchanged), `sonnet` on `claude-code`; `--rollup-model` still + defaults to `--model`. The provider is therefore resolved BEFORE the plan, + so `--dry-run` and `--estimate` print the model that would run — and still + need no binary, no key. +- A run that needs calls with nothing found is a usage error that leads with + what discovery said — `no claude on PATH or in a known install location, + and this run needs N model calls`, or `--claude-path FILE does not exist, + …`, or `CLAUDE_CODE_PATH=FILE does not exist, …` — never "a variable is + not set" for a path the user named on the command line; the hint: install + Claude Code and log in, `--claude-path FILE`, or the variable. + `--claude-path` with `--provider openrouter|cloudflare` is a usage error: + the flag names a binary that provider would never run. +- The provider line: `provider: claude-code (found on PATH: + /home/me/.local/bin/claude)` — or `--claude-path: …`, `CLAUDE_CODE_PATH: + …`, `found in a known install location: …`; the header's `provider` is + `claude-code`; the trailer's cost is the CLI's `total_cost_usd` (list + price — a subscription is billed by its plan), summed as before. +- The fingerprint carries the slug as REQUESTED (`sonnet`), each record's + `model` the id that served (`claude-sonnet-5-5`): a new Sonnet behind the + alias does not re-explain what was explained; a full id in `--model` does. + +### 21.5 Milestone split + +| | scope | definition of done | +|---|---|---| +| **M20a** | the adapter, discovery and resolution in `@codegraph/llm` | `claudeCodeClient` passes the same request/response/error paths the other two adapters are tested on, against a fake process; discovery and resolution tested as pure functions on both platforms' path shapes; the boundary test unchanged (no SDK); `pnpm --filter @codegraph/llm test` and typecheck green | +| **M20b** | the CLI, docs, a live run | `codegraph explain --provider claude-code` on the Java fixture against the real CLI yields a validate-clean side-car with `provider: "claude-code"` and a Sonnet cost in the trailer; `auto` picks it only when no key is set; `--dry-run`/`--estimate` show `sonnet`; docs (`docs/cli.md`, `docs/insights.md`, README, CLAUDE.md, the website's explain pages) name three adapters and the empty slot; the workspace gate green | + +### 21.6 Deferred, explicitly + +- **The Anthropic API adapter** — `packages/llm/src/anthropic.ts`, + `ANTHROPIC_API_KEY`, `--provider anthropic`: the Messages API with + `output_config.format` for the schema, through the official SDK (a second + line in the boundary test) or raw `fetch` (none). Model slugs would be + Anthropic's own ids, so a run that moves from `claude-code` to `anthropic` + keeps its fingerprints only when `--model` names the same full id. +- The desktop app's job using `claude-code` (the daemon knows extractors, + not providers). +- `--output-format stream-json` for per-call progress; `claude --version` + in the header. + +## 22. Milestones | # | Milestone | Definition of done | |---|---|---| @@ -5919,8 +6108,10 @@ green; the coverage table and the cost filled in this section. | M19a | Vocabulary — lexicon, split, artifact | ✅ (2026-10-26, five stacked PRs from #26, not yet merged; Broadleaf 76 310 entities → 3 381 terms in 0.29 s, 2.9 MB, its top ten a commerce vocabulary after 13 words joined the shared list) `Profile.lexicon` on the eleven profiles (keywords, conventional names, affixes, separators — the profile half of #19), METAMODEL §5 row, printed by `profiles --lang`; `@codegraph/vocabulary`: one idiom-parametrized splitter with the acronym rule on Unicode categories, four term classes as tags (never filters), role weights recorded in the artifact, scopes = the fold's containers; `codegraph vocabulary` report, `--level`/`--scope`/`--class`/`--drift FILE`; five `vocabulary.json` snapshots byte-identical, closure and determinism properties; the coverage table of §20.1 filled on fixtures, Broadleaf, codegraph, Mastodon, Plausible | | M19b | Vocabulary — cloud, tab, city channel | ✅ (2026-10-26, three stacked PRs from #31, not yet merged; Broadleaf's cloud and its city raised by `order` are the demo images) deterministic spiral layout with an injected measurer and the no-overlap property; `--svg` with the fixture snapshot; `serve` builds `/vocabulary.json` and answers `/carriers.json?scope=&term=`; the sixth navigator tab (scope follows the selection, chips, table, carriers → reveal), literals pinned, types-only import; `vocabulary:` metric source through the CLI hook, city unchanged; the two demo images under `docs/` and the README section — the issue's fourth criterion | | M19c | Vocabulary — glossary in the explanation | `words` on every insight block — the words of the unit's name, its parameters' and (for a type) its fields', each with `in`, `concern` (domain / technical / ambiguous), `sense`, `meaning`, in that entity's context, asked in the SAME call that explains it; `glossary` on the module block reconciling its types' entries with `polysemous`; `PROMPT_VERSION` 2, the words `.optional()` in the record schema so every existing side-car round-trips byte-identical — no new record type, no format change; the store at version 2 with the `insight_word` projection (rebuilt on `--import`); readers `insights --word/--glossary/--polysemy/--concerns`, `vocabulary --drift-insights`, `/glossary.json`, the entries shown as inferences in both panels; the Broadleaf re-explanation priced by `--estimate` and measured; `docs/vocabulary.md` | +| M20a | Model providers — the Claude Code adapter | ✅ (2026-11-10, 94 `@codegraph/llm` tests) `claudeCodeClient` in `@codegraph/llm` (§21.1): `claude -p --output-format json --json-schema --system-prompt --tools "" --safe-mode --no-session-persistence`, the user prompt on stdin, `structured_output` / `usage` / `total_cost_usd` / `modelUsage` read into the port's response, every failure classified into the port's one error type; `findClaudeCode` (option → `CLAUDE_CODE_PATH` → PATH → known install locations, pure) and `resolveProvider` with the fixed precedence; fake-process tests, the boundary test unchanged | +| M20b | Model providers — wired and documented | ✅ (2026-11-10, live on Claude Code 2.1.322, Java fixture: 68 calls, 0 failed, 79 records — 70 explained, stamped `claude-sonnet-5-5`, 9 templated — decode-clean, eof `$1.03` for 307 896 + 54 688 tokens; the prompt side is ≈ 2.7× the estimate, the ≈ 2 500 tokens of Claude Code scaffolding per call the estimate does not count) `--provider claude-code`, `--claude-path`, `--model` default per provider resolved before the plan (`sonnet`), the usage error naming the fix and the `--max-tokens` note; a live run on the Java fixture; `docs/cli.md`, `docs/insights.md`, README, CLAUDE.md and the website's explain pages name the port, the three adapters and the Anthropic API slot (§21.6) | -## 22. Decisions made in this plan (deltas vs. the design doc) +## 23. Decisions made in this plan (deltas vs. the design doc) | Topic | Decision | Rationale | |---|---|---| @@ -6039,3 +6230,6 @@ green; the coverage table and the cost filled in this section. | Glossary tied to the entity (M19c) | each explained unit's block carries `words`: the words its name (and its parameters' or fields' names) is made of, with sense and concern in that entity's context, asked in the explanation call itself; the module block reconciles its types' words into `glossary`; scopes and the corpus roll up from the records | a meaning belongs to the entity that uses the word, and the context pack of that entity is the one place the pipeline has its source, facts and dependencies' explanations together; a scope has a vocabulary, not a meaning — the two earlier drafts (a standalone command over a term table; a second request per scope) asked at the wrong altitude | | Glossary storage (M19c) | the insights store, version 2: an `insight_word (id, word, in, concern, sense, confidence)` projection written with the record and rebuilt on `--import`, indexed on `word`; the side-car stays the one source of truth | bought, so it shares the insights' lifecycle (migrated, never regenerated); a projection makes `--word` an index lookup without a second authoritative copy — the M16b rule (what is queried is a column over the JSON, what is fetched is the block) | | Glossary wire format (M19c) | no new record type: `words`/`glossary` live inside `block`, `.optional()` in the record schema and required on the wire by `strictify`; `PROMPT_VERSION` 2 | M11 put the prompt version in every fingerprint so a better prompt re-explains what it improves — the designed case; a version-1 record decodes and re-encodes to its own bytes, so every existing side-car round-trips, and nothing is deleted by the bump | +| Port and adapters (M20) | `LlmClient` is the port; OpenRouter, Cloudflare AI Gateway and Claude Code are adapters behind it, each holding its transport behind one function; the Anthropic API is a named empty slot (§21.6), not a stub | the walk, the store and the CLI never learn a provider; a fourth adapter is one file and one entry in `providers.ts` | +| Claude Code as a subprocess (M20) | the user's own `claude` binary in headless mode — `--safe-mode` (not `--bare`, which drops OAuth), tools off, no session, the system prompt replaced, the user prompt on stdin | the installation, login and version are the user's; no second SDK enters the workspace; argv has a 128 KB per-argument limit | +| Provider precedence (M20) | `auto` takes the single configured provider; with several, OpenRouter, then Cloudflare, then Claude Code, the reason naming the flag for the others; `--model` defaults per provider (`sonnet` on Claude Code) | an exported key is a deliberate act, an installed CLI is ambient; `openai/gpt-5.6-luna` means nothing to Claude Code | diff --git a/README.md b/README.md index 92b411b..ccb1e86 100644 --- a/README.md +++ b/README.md @@ -288,6 +288,7 @@ codegraph replay --store gson.db --history gson-history.jsonl --serve codegraph explain gson.jsonl --src ~/src/gson/gson/src/main/java --dry-run # the plan, no call codegraph explain gson.jsonl --src ... --estimate --price-in 0.10 --price-out 0.60 # tokens and cost, no call OPENROUTER_API_KEY=… codegraph explain gson.jsonl --src ... --max-calls 50 # shows the estimate, asks [y/N] +codegraph explain gson.jsonl --src ... --provider claude-code # the installed, logged-in Claude Code instead (Sonnet, no key) codegraph explain gson.jsonl --src ... --model openai/gpt-5.6-luna --rollup-model anthropic/claude-sonnet-5 # pick the models codegraph insights gson.jsonl # what was bought: records, concepts, what is owed, the spend codegraph insights gson.jsonl --concept aggregate # the types the model read as aggregates @@ -301,9 +302,14 @@ its export, `gson.insights.jsonl`; never into the model. `codegraph serve` shows them on the selected type or module, marked as a model's inference. Re-running redoes only the units whose inputs changed. On the reference fixture a full run was 68 calls and about six cents. `--model` sets the model -for every unit (default `openai/gpt-5.6-luna`); `--rollup-model` overrides it -for types and modules only. Switching models re-explains the affected units. Cloudflare AI Gateway is -the other supported provider. +for every unit (default `openai/gpt-5.6-luna` on a key provider, `sonnet` on +Claude Code); `--rollup-model` overrides it for types and modules only. +Switching models re-explains the affected units. The calls go through one +port (`LlmClient`) and three adapters: OpenRouter (an API key), Cloudflare AI +Gateway (a token pair) and Claude Code headless (the `claude` CLI already +installed and logged in — found on `PATH` or named with `--claude-path`; no +key). `auto` prefers a key over the installed CLI; a direct Anthropic API +adapter is a named slot for later. ### Feed it to something else @@ -367,7 +373,8 @@ Read these before you commit an afternoon. repeatable, but the same package declared under several roots at once (main and test sources, or one package split across modules) confuses noClasspath resolution; pass such roots in separate runs. -- **`explain` costs money and needs a network.** It is the only command that +- **`explain` costs money and needs a network** (or an installed Claude Code, + which spends the subscription). It is the only command that does. `--dry-run` and `--estimate` tell you what it would do first, a real run asks for confirmation after showing the estimate (`--yes` in scripts), and `--max-calls` caps it. diff --git a/WEBSITE.md b/WEBSITE.md index 89dfe8d..344a3c1 100644 --- a/WEBSITE.md +++ b/WEBSITE.md @@ -237,7 +237,7 @@ Each page links to the tutorial or how-to that applies it. | `time-as-structure.md` | Hotspots, ownership, co-change, hidden coupling and deadweight; why history is a dependency source cannot show; the replay design. | PLAN §11, Tornhill | write | | `explaining-bottom-up.md` | Units, cycles as one unit, context packs, fingerprints, the side-car rule. | docs/insights.md | exists | | `architecture.md` | The packages, the hard boundaries and why each exists. | CLAUDE.md, PLAN §1–2 | partial | -| `decisions.md` | The decision log. | PLAN §21 | exists | +| `decisions.md` | The decision log. | PLAN §23 | exists | | `prior-art.md` | Moose/FamixNG, CodeCity, Structure101, Gource and Tornhill, Sourcetrail, jQAssistant, ArchUnit: what each does and where codegraph differs. | README credits | write | ### 4.5 Documentation debt found while writing (repository docs, not the site) diff --git a/docs/cli.md b/docs/cli.md index 9cc6825..4841efb 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -78,7 +78,8 @@ codegraph domain-facts [model.jsonl] [--framework spring] [--out FILE] codegraph explain [model.jsonl] [--src DIR] [--out FILE] [--dry-run] [--estimate [--price-in USD --price-out USD]] - [--provider auto|openrouter|cloudflare] + [--provider auto|openrouter|cloudflare|claude-code] + [--claude-path FILE] [--model SLUG] [--rollup-model SLUG] [--depth N] [--max-calls N] [--max-tokens N] [--scope IDS] [--concurrency N] @@ -320,10 +321,34 @@ writes the side-car from the store and stops — after an interrupted run, or a deleted file. Neither flag reads the model or needs a key. Mutually dependent units (a cycle) are explained as one unit. Re-runs redo only what changed (Merkle fingerprints over inputs, never over explanation -text). Needs `OPENROUTER_API_KEY`, or `CLOUDFLARE_API_TOKEN` + -`CLOUDFLARE_ACCOUNT_ID` [+ `CLOUDFLARE_AI_GATEWAY_ID`], unless `--dry-run` or -`--estimate`. `--model SLUG` overrides the model (default -`openai/gpt-5.6-luna`, `author/model` form on either provider) for every unit; +text). The model calls go through one of three adapters of one port +(`LlmClient`, in `@codegraph/llm`): `--provider openrouter` needs +`OPENROUTER_API_KEY`; `--provider cloudflare` (AI Gateway) needs +`CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID` [+ `CLOUDFLARE_AI_GATEWAY_ID`]; +`--provider claude-code` needs an installed and logged-in Claude Code and no +key — it runs the CLI in headless mode (`claude -p`), one process per call, so +`--concurrency N` is N processes and `--max-tokens` does not apply (the CLI has +no output cap; the flag is noted and ignored). The binary is `--claude-path +FILE` (which implies `claude-code` under `auto`, and is refused with a key +provider), else `CLAUDE_CODE_PATH`, else `claude` on `PATH`, else the known +install locations; naming one that does not exist is an error, never a +fall-through. +On Windows, an npm-global `claude.cmd` is found but cannot run (the adapter +spawns without a shell, and Node refuses `.cmd`/`.bat` there: `EINVAL`); use +the native installer's `claude.exe` (`%USERPROFILE%\.local\bin\claude.exe`), +with `--claude-path` if needed. +`auto` (the default) takes the one that is configured, and with several +OpenRouter, then Cloudflare, then Claude Code: a key is deliberate, an +installed CLI is ambient. `--dry-run` and `--estimate` need none of it. A +fourth adapter, the Anthropic API with an API key, is a named slot for later +(PLAN.md §21.6). `--model SLUG` overrides the model for every unit; it defaults +per provider: `openai/gpt-5.6-luna` (`author/model` form) on OpenRouter and +Cloudflare, `sonnet` on Claude Code — an alias the CLI resolves to the latest +Sonnet. The fingerprint carries the slug as requested (`sonnet`), each +record's `model` the id that served (`claude-sonnet-5-5`): a new Sonnet +behind the alias does not re-explain what was explained; a full id in +`--model` does. The trailer's cost on Claude Code is the CLI's +`total_cost_usd` at list price — a subscription is billed by its plan. `--rollup-model SLUG` overrides it again for types and modules. The slug is part of each record's fingerprint, so a new model re-explains what it covers. A run that makes model calls first prints its token estimate on diff --git a/docs/insights.md b/docs/insights.md index 8621214..f777db3 100644 --- a/docs/insights.md +++ b/docs/insights.md @@ -21,33 +21,82 @@ is why they live beside it. @codegraph/insights pure: units, walk order, context packs, prompts, fingerprints, plan, run, side-car format - @codegraph/llm the model clients: LlmClient + OpenRouter (SDK) + - Cloudflare AI Gateway (REST, plain fetch) + a fake + @codegraph/llm the port, LlmClient, and its adapters: OpenRouter + (SDK), Cloudflare AI Gateway (REST, plain fetch), + Claude Code headless (a subprocess) + a fake `insights` depends on `core` and `analyzer` only and does no I/O: source text arrives through an injected reader, the model call through an injected `Completer`, finished records leave through a hook. `llm` is the **only package allowed to import the provider SDK** — `packages/llm/test/boundary.test.ts` scans the workspace for the import, and `eslint.config.js` restricts it. The -CLI wires the two: it owns the filesystem, the environment variable -(`OPENROUTER_API_KEY`) and the progress narration. +CLI wires the two: it owns the filesystem, the environment (the keys, +`CLAUDE_CODE_PATH`, `PATH`) and the progress narration. The provider SDK is itself held behind a one-function `OpenRouterTransport`, so every request/response/error path is driven by a fake transport in tests, and an SDK change is repaired in one file. -**Two providers, one contract.** Both speak OpenAI's chat-completion shape, -parsed once in `chat.ts`. What differs: OpenRouter goes through its SDK -(camel-cased request and reply, its own API key per request); Cloudflare AI -Gateway goes through the AI REST API on `api.cloudflare.com` with plain -`fetch` (snake_case wire, one Cloudflare API token that both authenticates -and bills through Unified Billing or a stored provider key, an optional -`cf-aig-gateway-id`). Model names are the same `author/model` form on both, -so switching the route leaves every fingerprint — and every reusable record -— intact. `providers.ts` resolves `--provider auto|openrouter|cloudflare` -from the environment in one place: the single configured provider wins; -with both configured OpenRouter stays the default and the choice is printed. -The side-car header records the provider that served the run. +**One port, three adapters.** `LlmClient` (`client.ts`) is the port: one +structured completion in, parsed JSON out, one error type with `retryable` +decided once. Nothing above it — the run's `Completer`, the CLI's +`completerFor`, the store, the side-car — knows which adapter answered. +The two key adapters speak OpenAI's chat-completion shape, parsed once in +`chat.ts`: OpenRouter goes through its SDK (camel-cased request and reply, +its own API key per request); Cloudflare AI Gateway goes through the AI REST +API on `api.cloudflare.com` with plain `fetch` (snake_case wire, one +Cloudflare API token that both authenticates and bills through Unified +Billing or a stored provider key, an optional `cf-aig-gateway-id`). Model +names are the same `author/model` form on both, so switching the route +leaves every fingerprint — and every reusable record — intact. + +The third adapter, **Claude Code headless** (`claude-code.ts`, PLAN.md §21), +is a subprocess: one `claude -p --output-format json` process per call, so +`--concurrency N` is N processes. It runs with `--safe-mode`, not `--bare`: +`--bare` restricts authentication to an API key and drops the subscription +login this adapter exists for, while `--safe-mode` keeps the login and +disables every customization (CLAUDE.md, hooks, plugins, MCP servers, output +styles); the default persona is replaced by `--system-prompt` and tools are +off (`--tools ""`), so the model can only answer. The user prompt goes +through stdin — a context pack with source can exceed Linux's 128 KB +per-argument limit — while the system prompt and the `--json-schema` ride as +arguments. The result JSON is read into the port's response: +`structured_output` is the parsed answer (fenced text through the shared +`extractJson` when a version lacks it), `usage` gives the tokens (input, +cache creation and cache read summed as what was sent), `total_cost_usd` +the cost (list price; a subscription is billed by its plan). The fingerprint +carries the slug as requested (`sonnet`), the record's `model` the id that +served (`modelUsage`'s key, `claude-sonnet-5-5`): a new Sonnet behind the +alias does not re-explain what was explained, a full id in `--model` does. +`--max-tokens` has no counterpart on the CLI and is noted, then +ignored. Like the SDK behind `OpenRouterTransport`, the process is held +behind a one-function seam (`ClaudeCodeProcess.run`): every test drives the +adapter with recorded stdout, stderr and exit codes, and nothing is spawned. + +**Discovery and precedence.** `claude-code-discovery.ts` finds the binary as +a pure function of the flag, the environment and an `exists` probe — never a +process, so `--dry-run` resolves a provider without spawning — in this +order: `--claude-path`, `CLAUDE_CODE_PATH`, `claude` in each directory of +`PATH`, then the install locations the docs name (`~/.local/bin/claude`, +`~/.claude/local/claude`, Homebrew's, and on Windows +`%USERPROFILE%\.local\bin\claude.exe` and `%APPDATA%\npm\claude.cmd`). An +explicit path that does not exist is an answer naming it, never a +fall-through to another binary. One Windows limit: a found `claude.cmd` +cannot be run — the adapter spawns without a shell, and Node refuses +`.cmd`/`.bat` there (`EINVAL`, the CVE-2024-27980 mitigation) — so the run +fails with `claude-code: cannot run …\claude.cmd: EINVAL`; the native +installer's `claude.exe` works, and `--claude-path` can point at it. +`providers.ts` resolves `--provider +auto|openrouter|cloudflare|claude-code` in one place: a key provider is +configured when its variables are set, Claude Code when discovery found a +binary; `auto` takes the single configured one, and with several a fixed +precedence — OpenRouter, then Cloudflare, then Claude Code — because an +exported key is a deliberate act while an installed CLI is ambient, so the +CLI never overrides a key (the reason line names the flag for each +alternative). The side-car header records the provider that served the run. +The fourth adapter — the Anthropic API with `ANTHROPIC_API_KEY`, +`--provider anthropic` — is a named, empty slot (PLAN.md §21.6): one more +entry in `providers.ts`, nothing above the port. ## IN-2 · Units and the walk order diff --git a/docs/model-metamodel.md b/docs/model-metamodel.md index 4d0f46d..09a43a9 100644 --- a/docs/model-metamodel.md +++ b/docs/model-metamodel.md @@ -109,7 +109,7 @@ decides how order manifests physically. makes v1's rendered-id uniqueness a *consequence* of it. - [x] Property suite: natural-key uniqueness, injectivity, and canonical order as a total order, generatively (`packages/core/test/properties.test.ts`). -- [x] PLAN.md §9.1/§21/§22 (milestones/decisions): decisions recorded. +- [x] PLAN.md §9.1/§22/§23 (milestones/decisions): decisions recorded. Done in M6 (PLAN.md §9.2), as planned: the `children` key is gone from `Entity`, the `TRAITS` table and the wire — the trait declaration stays — and closure, diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts index 531afc1..b3b4558 100644 --- a/packages/cli/src/args.ts +++ b/packages/cli/src/args.ts @@ -574,9 +574,16 @@ export const DOMAIN_FACTS_SPEC: CommandSpec = { ], }; +/** `--model` on the key providers (OpenRouter, Cloudflare), in their `author/model` form. */ export const DEFAULT_EXPLAIN_MODEL = "openai/gpt-5.6-luna"; -/** `--provider` values: the two clients of @codegraph/llm, or pick from the environment. */ -export const EXPLAIN_PROVIDERS = ["auto", "openrouter", "cloudflare"] as const; +/** + * `--model` on claude-code: Claude Code's alias for the latest Sonnet. Restated from + * @codegraph/llm's CLAUDE_CODE_DEFAULT_MODEL and pinned equal by a test: parsing must + * not load the provider package (and with it the SDK) for every command. + */ +export const DEFAULT_CLAUDE_CODE_MODEL = "sonnet"; +/** `--provider` values: the three adapters of @codegraph/llm, or pick from the environment. */ +export const EXPLAIN_PROVIDERS = ["auto", "openrouter", "cloudflare", "claude-code"] as const; export type ExplainProvider = (typeof EXPLAIN_PROVIDERS)[number]; export const EXPLAIN_SPEC: CommandSpec = { @@ -602,19 +609,33 @@ export const EXPLAIN_SPEC: CommandSpec = { name: "provider", type: "string", describe: - "Where the model calls go: openrouter (OPENROUTER_API_KEY) or cloudflare — Cloudflare AI " + + "Where the model calls go: openrouter (OPENROUTER_API_KEY), cloudflare — Cloudflare AI " + "Gateway's REST API (CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, optional " + - "CLOUDFLARE_AI_GATEWAY_ID). auto picks whichever is configured, OpenRouter when both are.", + "CLOUDFLARE_AI_GATEWAY_ID) — or claude-code, the local Claude Code CLI in headless mode " + + "(`claude -p`, Sonnet by default, no key). auto picks whichever is configured; with " + + "several, OpenRouter, then Cloudflare, then Claude Code.", choices: [...EXPLAIN_PROVIDERS], placeholder: "NAME", defaultValue: "auto", }, + { + name: "claude-path", + type: "string", + describe: + "The Claude Code binary. Under --provider auto it implies claude-code; with openrouter or " + + "cloudflare it is an error. Otherwise CLAUDE_CODE_PATH, then `claude` on PATH, then the known " + + "install locations; a path that does not exist is an error, never a fall-through.", + placeholder: "FILE", + }, { name: "model", type: "string", - describe: "Model slug for operations (the leaves), in author/model form on either provider.", + describe: + `Model slug for operations (the leaves). Defaults per provider: ${DEFAULT_EXPLAIN_MODEL} ` + + `(author/model form) on openrouter and cloudflare, ${DEFAULT_CLAUDE_CODE_MODEL} on claude-code ` + + "— an alias Claude Code resolves to the latest Sonnet; a full id such as claude-sonnet-5-5 " + + "pins the fingerprint.", placeholder: "SLUG", - defaultValue: DEFAULT_EXPLAIN_MODEL, }, { name: "rollup-model", @@ -643,7 +664,8 @@ export const EXPLAIN_SPEC: CommandSpec = { describe: "Cap on the tokens one answer may use (reasoning included). Omitted, the provider assumes " + "the model's full output window and a prepaid account must afford THAT for every call; a " + - "block is ~1k tokens, a full cycle call ~12k. An answer cut at the cap fails its unit.", + "block is ~1k tokens, a full cycle call ~12k. An answer cut at the cap fails its unit. " + + "Does not apply to claude-code (the CLI has no output cap): noted on stderr, ignored.", placeholder: "N", integer: true, }, @@ -1325,10 +1347,14 @@ export interface ExplainOptions extends ModelInputOptions, ViewOptions, CacheOpt readonly src: string | undefined; /** `--out FILE`; undefined = `.insights.jsonl` beside the first model. */ readonly out: string | undefined; - /** `--provider`; `auto` resolves from the environment at run time. */ + /** `--provider`; `auto` resolves from the environment (and the Claude Code discovery) at run time. */ readonly provider: ExplainProvider; - readonly model: string; - readonly rollupModel: string; + /** `--claude-path FILE`; undefined = CLAUDE_CODE_PATH, then PATH, then the known install locations. */ + readonly claudePath: string | undefined; + /** `--model`; undefined = the resolved provider's default (DEFAULT_EXPLAIN_MODEL or DEFAULT_CLAUDE_CODE_MODEL). */ + readonly model: string | undefined; + /** `--rollup-model`; undefined = the resolved `--model`. */ + readonly rollupModel: string | undefined; readonly depth: number; readonly maxCalls: number | undefined; /** `--max-tokens`; undefined = the provider's default (the model's whole output window). */ @@ -2014,7 +2040,6 @@ export function parseInvocation(argv: readonly string[]): Invocation { "Run explain once per model, or drop --src to read each model's own root.", ); } - const model = stringOf(values, "model") ?? DEFAULT_EXPLAIN_MODEL; if (flagOf(values, "retry-failed") && stringOf(values, "scope") !== undefined) { throw new UsageError( "--retry-failed and --scope both choose what to explain", @@ -2027,6 +2052,15 @@ export function parseInvocation(argv: readonly string[]): Invocation { "Run them one after the other: --import FILE replaces the store, --export writes the side-car from it.", ); } + const provider = (stringOf(values, "provider") ?? "auto") as ExplainProvider; + const claudePath = stringOf(values, "claude-path"); + // A named binary is meant to run (auto implies claude-code); a key provider could only ignore it. + if (claudePath !== undefined && provider !== "auto" && provider !== "claude-code") { + throw new UsageError( + `--claude-path names a binary that --provider ${provider} would never run`, + "Drop --claude-path, or pass --provider claude-code (or auto, which it implies).", + ); + } return { kind: "run", command: "explain", @@ -2034,9 +2068,10 @@ export function parseInvocation(argv: readonly string[]): Invocation { models, src, out: stringOf(values, "out"), - provider: (stringOf(values, "provider") ?? "auto") as ExplainProvider, - model, - rollupModel: stringOf(values, "rollup-model") ?? model, + provider, + claudePath, + model: stringOf(values, "model"), + rollupModel: stringOf(values, "rollup-model"), depth: integerOf(values, "depth") ?? 1, maxCalls: integerOf(values, "max-calls"), maxTokens: integerOf(values, "max-tokens"), diff --git a/packages/cli/src/commands/explain.ts b/packages/cli/src/commands/explain.ts index 5511760..7abec6f 100644 --- a/packages/cli/src/commands/explain.ts +++ b/packages/cli/src/commands/explain.ts @@ -41,9 +41,9 @@ import { type RunUsage, type Unit, } from "@codegraph/insights"; -import { clientFromEnv, resolveProvider, type LlmClient, type Provider } from "@codegraph/llm"; +import { clientFromResolution, findClaudeCode, resolveProvider, type LlmClient, type Provider, type ProviderResolution } from "@codegraph/llm"; import { buildVocabulary, definitionSpeller, rankedWords, type VocabularyArtifact } from "@codegraph/vocabulary"; -import type { ExplainOptions } from "../args.js"; +import { DEFAULT_CLAUDE_CODE_MODEL, DEFAULT_EXPLAIN_MODEL, type ExplainOptions } from "../args.js"; import { EXIT, UsageError, type ExitCode } from "../exit.js"; import { errLine, errLines, outLine, type IoSink } from "../io.js"; import { sidecarPathFor } from "../insights-paths.js"; @@ -77,6 +77,12 @@ import { resolveView } from "../view.js"; * estimate on stderr and asks before the first call; `--yes` skips the * question, and with no terminal to ask on the run refuses rather than spends. * + * THE PROVIDER IS RESOLVED BEFORE THE PLAN (PLAN.md §21.4): `--provider`, or + * on `auto` whichever adapter the environment configures (a key) or discovery + * found (the Claude Code binary) — a pure function of flags, environment and + * an `exists` probe, so `--dry-run` prints the model that would run and spawns + * nothing. `--model` defaults per provider, which is why it waits for this. + * * THE SEAM: environment, filesystem, clock, the client factory and the * question come in one object, so the whole command runs in-process against a * fake model with no network and no disk (test/explain.test.ts). @@ -107,8 +113,8 @@ export interface ExplainSeam { /** This process, recorded on the run so a later one can tell a live writer from a dead one. */ readonly pid: number; isAlive(pid: number): boolean; - /** The client for a RESOLVED provider whose variables are all present in `env`. */ - clientFor(provider: Provider, env: Readonly>): LlmClient; + /** The client for a resolution with nothing missing: a key provider's variables are in `env`, Claude Code's binary rides on the resolution. */ + clientFor(resolution: ProviderResolution, env: Readonly>): LlmClient; now(): Date; /** Asks a yes/no question; undefined when there is no interactive terminal to ask on. */ readonly confirm: ((question: string) => Promise) | undefined; @@ -182,7 +188,7 @@ export function realSeam(): ExplainSeam { return (error as NodeJS.ErrnoException).code === "EPERM"; } }, - clientFor: (provider, env) => clientFromEnv(provider, env), + clientFor: (resolution, env) => clientFromResolution(resolution, env), now: () => new Date(), confirm: process.stdin.isTTY && process.stderr.isTTY ? confirmOnTerminal : undefined, }; @@ -199,17 +205,30 @@ async function confirmOnTerminal(question: string): Promise { } +/** `ExplainOptions` once the provider is known: `--model` defaulted per provider, `--rollup-model` to it. */ +type ResolvedOptions = Omit & { readonly model: string; readonly rollupModel: string }; + +/** The provider and, from it, the models. `--claude-path` names a binary on purpose: on `auto` it implies `--provider claude-code`. */ +function resolveRun(flags: ExplainOptions, seam: ExplainSeam): { resolution: ProviderResolution; options: ResolvedOptions } { + const discovery = findClaudeCode({ explicit: flags.claudePath, env: seam.env, exists: seam.fs.exists }); + const choice = flags.provider === "auto" && flags.claudePath !== undefined ? "claude-code" : flags.provider; + const resolution = resolveProvider(choice, seam.env, { claudeCode: discovery }); + const model = flags.model ?? (resolution.provider === "claude-code" ? DEFAULT_CLAUDE_CODE_MODEL : DEFAULT_EXPLAIN_MODEL); + return { resolution, options: { ...flags, model, rollupModel: flags.rollupModel ?? model } }; +} + export async function explainCommand( - options: ExplainOptions, + flags: ExplainOptions, io: IoSink, seam: ExplainSeam = realSeam(), ): Promise { - const out = options.out ?? sidecarPathFor(options.models[0] ?? "model.jsonl"); + const out = flags.out ?? sidecarPathFor(flags.models[0] ?? "model.jsonl"); const storePath = insightsStorePathFor(out); // Neither reads a model: they move records between the store and its side-car. - if (options.exportOnly) return exportOnly(out, storePath, seam, io); - if (options.importFrom !== undefined) return importOnly(options.importFrom, out, storePath, options, seam, io); + if (flags.exportOnly) return exportOnly(out, storePath, seam, io); + if (flags.importFrom !== undefined) return importOnly(flags.importFrom, out, storePath, flags, seam, io); + const { resolution, options } = resolveRun(flags, seam); const source = openAnalysis(options.models, options, io); let store: InsightsStore | undefined; try { @@ -280,7 +299,7 @@ export async function explainCommand( { cause: error }, ); } - const { complete, provider } = completerFor(plan, options, seam, io); + const { complete, provider } = completerFor(plan, options, resolution, seam, io); if (!(await confirmed(plan, options, seam, io))) { errLine(io, "aborted: no call was made, nothing was written."); return EXIT.OK; @@ -338,7 +357,7 @@ export async function explainCommand( if (misses.length > 0) { errLine(io, `warning: ${misses.length} source file${misses.length === 1 ? "" : "s"} not found under ${srcRoot} (first: ${misses[0]}); those units were explained from facts alone.`); } - errLines(io, summaryLines(out, result, options)); + errLines(io, summaryLines(out, result, options, provider)); if (options.json) { outLine(io, JSON.stringify({ kind: "codegraph.explainSummary/1", out, counts: result.counts, usage: result.usage, failures: result.failures, ...(result.aborted === undefined ? {} : { aborted: result.aborted }) })); } @@ -540,7 +559,7 @@ function loadExisting(out: string, storePath: string, journal: string, seam: Exp * run that failed: model and depth are part of every fingerprint, so a retried * unit explained under others is redone again by the next plain run. */ -function retryLines(failures: readonly FailureRecord[], previous: InsightsHeader, options: ExplainOptions): string[] { +function retryLines(failures: readonly FailureRecord[], previous: InsightsHeader, options: ResolvedOptions): string[] { const lines = [`retrying ${failures.length} failed unit${failures.length === 1 ? " and its" : "s and their"} direct dependents:`]; const byReason = new Map(); for (const failure of failures) { @@ -577,32 +596,46 @@ function scopePredicate( unit.members.some((m) => wanted.has(m) || wanted.has(folder.containingType(m) ?? "") || wanted.has(folder.containingModule(m) ?? "")); } +/** How to make each adapter buildable, for the usage error of a run that needs calls and cannot make them. */ +const SETUP_HINT: Readonly> = { + openrouter: + "Create one at https://openrouter.ai/keys, or export CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID to route through Cloudflare AI Gateway, " + + "or install Claude Code and pass --provider claude-code to run it locally (no key).", + cloudflare: "CLOUDFLARE_API_TOKEN needs the AI Gateway Run permission (wrangler auth token); CLOUDFLARE_AI_GATEWAY_ID is optional (the account's default gateway otherwise).", + "claude-code": "Install Claude Code (https://code.claude.com/docs/en/setup) and log in, or point at the binary with --claude-path FILE or CLAUDE_CODE_PATH.", +}; + /** - * The provider: `--provider` or, on `auto`, whichever of OpenRouter / Cloudflare - * AI Gateway the environment configures. Resolved BEFORE any call, so a - * missing variable is a usage error naming it — never a failed first request. + * The completer over the resolved provider. What it lacks — a variable, the + * Claude Code binary — is checked BEFORE any call, so it is a usage error + * naming it (and what was searched), never a failed first request. */ function completerFor( plan: RunPlan, - options: ExplainOptions, + options: ResolvedOptions, + resolution: ProviderResolution, seam: ExplainSeam, io: IoSink, ): { complete: Completer; provider: Provider | undefined } { if (plan.estimates.calls === 0) return { complete: () => Promise.reject(new Error("no call was planned")), provider: undefined }; - const resolution = resolveProvider(options.provider, seam.env); if (resolution.missing.length > 0) { const calls = `${plan.estimates.calls} model call${plan.estimates.calls === 1 ? "" : "s"}`; - const setup = - resolution.provider === "cloudflare" - ? "CLOUDFLARE_API_TOKEN needs the AI Gateway Run permission (wrangler auth token); CLOUDFLARE_AI_GATEWAY_ID is optional (the account's default gateway otherwise)." - : "Create one at https://openrouter.ai/keys, or export CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID to route through Cloudflare AI Gateway."; + // Claude Code leads with what discovery said: a path the user named is the message, not "a variable is not set". + const lacking = + resolution.provider === "claude-code" + ? resolution.reason + : `${resolution.missing.join(" and ")} ${resolution.missing.length === 1 ? "is" : "are"} not set (${resolution.reason})`; throw new UsageError( - `${resolution.missing.join(" and ")} ${resolution.missing.length === 1 ? "is" : "are"} not set (${resolution.reason}), and this run needs ${calls}`, - `${setup} Add --dry-run to see the plan without calling. Models: ${options.model}${options.rollupModel === options.model ? "" : `, ${options.rollupModel}`}.`, + `${lacking}, and this run needs ${calls}`, + `${SETUP_HINT[resolution.provider]} Add --dry-run to see the plan without calling. Models: ${options.model}${options.rollupModel === options.model ? "" : `, ${options.rollupModel}`}.`, ); } - const client = seam.clientFor(resolution.provider, seam.env); + const client = seam.clientFor(resolution, seam.env); errLine(io, `provider: ${client.name} (${resolution.reason})`); + // The port carries maxTokens; the CLI has no output cap, so that adapter drops it — said here, once. + if (resolution.provider === "claude-code" && options.maxTokens !== undefined) { + errLine(io, "note: --max-tokens does not apply to claude-code (the CLI has no output cap); ignored."); + } const complete: Completer = async (request) => { const response = await client.complete({ model: request.model, @@ -646,7 +679,7 @@ function naturalKeys(paths: readonly string[], io: IoSink): ((id: string) => Rec } function headerFor( - options: ExplainOptions, + options: ResolvedOptions, provider: string | undefined, langs: readonly string[], viewName: string, @@ -687,7 +720,7 @@ function eofFor( }; } -function printPlan(plan: RunPlan, options: ExplainOptions, io: IoSink): void { +function printPlan(plan: RunPlan, options: ResolvedOptions, io: IoSink): void { const { estimates } = plan; if (options.json) { outLine( @@ -746,7 +779,7 @@ export function estimatedCost(promptTokens: number, completionTokens: number, pr * rate-limit retries are not included, and a run that reuses records sends * less than a cold one. */ -function printEstimate(plan: RunPlan, options: ExplainOptions, io: IoSink): void { +function printEstimate(plan: RunPlan, options: ResolvedOptions, io: IoSink): void { const { estimates } = plan; const cost = estimatedCost(estimates.promptTokens, estimates.completionTokens, options.priceIn, options.priceOut); const layers = (plan.steps[plan.steps.length - 1]?.unit.layer ?? -1) + 1; @@ -779,7 +812,7 @@ function printEstimate(plan: RunPlan, options: ExplainOptions, io: IoSink): void outLine(io, estimateLines(plan, options).join("\n")); } -function estimateLines(plan: RunPlan, options: ExplainOptions): string[] { +function estimateLines(plan: RunPlan, options: ResolvedOptions): string[] { const { estimates } = plan; const cost = estimatedCost(estimates.promptTokens, estimates.completionTokens, options.priceIn, options.priceOut); const layers = (plan.steps[plan.steps.length - 1]?.unit.layer ?? -1) + 1; @@ -818,7 +851,7 @@ function outputAssumption(): string { * that plans no call, or `--yes`, passes silently; no terminal and no `--yes` * is a usage error, so a script never spends by accident. */ -async function confirmed(plan: RunPlan, options: ExplainOptions, seam: ExplainSeam, io: IoSink): Promise { +async function confirmed(plan: RunPlan, options: ResolvedOptions, seam: ExplainSeam, io: IoSink): Promise { if (plan.estimates.calls === 0 || options.yes) return true; const { calls, promptTokens, completionTokens } = plan.estimates; if (seam.confirm === undefined) { @@ -834,7 +867,7 @@ async function confirmed(plan: RunPlan, options: ExplainOptions, seam: ExplainSe ); } -function summaryLines(out: string, result: Awaited>, options: ExplainOptions): string[] { +function summaryLines(out: string, result: Awaited>, options: ExplainOptions, provider: Provider | undefined): string[] { const { counts, usage } = result; const lines = [ `wrote ${counts.records} record${counts.records === 1 ? "" : "s"} to ${out} (${counts.llm} explained, ${counts.template} templated, ${counts.reused} reused, ${counts.failed} failed, ${counts.skipped} skipped).`, @@ -846,7 +879,8 @@ function summaryLines(out: string, result: Awaited // Units never reached have no failure record, so --retry-failed would miss them: a plain re-run resumes both. lines.push(`aborted: the provider answered ${aborted.reason.status ?? "?"} for ${aborted.unit} — every later call would get the same answer, so none was made.`); lines.push(`${aborted.notAttempted} unit${aborted.notAttempted === 1 ? " was" : "s were"} not attempted. Once the account is sorted out, run the same command again: it redoes the failures and resumes where this run stopped.`); - if (aborted.reason.status === 402 && options.maxTokens === undefined) { + // A cap lowers what a prepaid call must afford on a key provider; the Claude Code CLI has none. + if (aborted.reason.status === 402 && options.maxTokens === undefined && provider !== "claude-code") { lines.push("hint: without --max-tokens the provider prices every call at the model's full output window; a cap (e.g. --max-tokens 16384) lowers the balance a call needs."); } } else if (result.failures.length > 0) { diff --git a/packages/cli/test/explain.test.ts b/packages/cli/test/explain.test.ts index cfcdbce..5fe8ae6 100644 --- a/packages/cli/test/explain.test.ts +++ b/packages/cli/test/explain.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -15,12 +15,12 @@ import { type InsightRecord, type InsightsStore, } from "@codegraph/insights"; -import { LlmError, fakeLlmClient, type LlmClient, type LlmRequest, type Provider } from "@codegraph/llm"; -import { EXIT } from "../src/exit.js"; +import { CLAUDE_CODE_DEFAULT_MODEL, LlmError, PROVIDERS, fakeLlmClient, type LlmClient, type LlmRequest, type Provider } from "@codegraph/llm"; +import { EXIT, UsageError } from "../src/exit.js"; import { captureIo } from "../src/io.js"; import { run } from "../src/main.js"; import { explainCommand, realSeam, sidecarPathFor, type ExplainSeam } from "../src/commands/explain.js"; -import { parseInvocation } from "../src/args.js"; +import { DEFAULT_CLAUDE_CODE_MODEL, DEFAULT_EXPLAIN_MODEL, EXPLAIN_PROVIDERS, parseInvocation } from "../src/args.js"; const FIXTURE = fileURLToPath(new URL("../../../fixtures/java/expected/model.jsonl", import.meta.url)); const SRC = fileURLToPath(new URL("../../../fixtures/java/src", import.meta.url)); @@ -134,8 +134,8 @@ function seamWith( }, pid: 1000, isAlive: (pid) => alive.has(pid), - clientFor: (provider) => { - providers.push(provider); + clientFor: (resolution) => { + providers.push(resolution.provider); return client; }, now: () => new Date("2026-09-02T10:00:00.000Z"), @@ -388,7 +388,7 @@ describe("explain records what failed, and --retry-failed redoes exactly that", key: { lang: "java", module: "com.acme.order", symbol: "" }, level: "module", members: [MODULE], - model: options([]).rollupModel, + model: DEFAULT_EXPLAIN_MODEL, reason: { kind: "provider", message: TOO_LONG, status: 400, retryable: false }, attempts: 1, calls: 0, @@ -807,17 +807,150 @@ describe("explain picks its provider from the flag or the environment", () => { }); }); +describe("explain runs the installed Claude Code as a provider (PLAN.md §21, M20b)", () => { + const HOME = "/home/test"; + const KNOWN = `${HOME}/.local/bin/claude`; + const ON_PATH = "/usr/bin/claude"; + const NOTE = "note: --max-tokens does not apply to claude-code (the CLI has no output cap); ignored."; + /** A binary planted on the fake disk: discovery only asks whether it exists. */ + const binary = (...paths: string[]) => new Map(paths.map((path) => [resolve(path), ""])); + + it("auto with no key and a binary in a known install location runs through claude-code, on sonnet, and records it", async () => { + const machine = seamWith({ HOME }, binary(KNOWN)); + const io = captureIo(); + expect(await explainCommand(options(["--out", OUT]), io, machine.seam)).toBe(EXIT.OK); + expect(new Set(machine.providers)).toEqual(new Set(["claude-code"])); + expect(io.stderr()).toContain(`provider: fake (found in a known install location: ${KNOWN})`); + expect(machine.client.calls.length).toBeGreaterThan(0); + expect(machine.client.calls.every((c) => c.model === "sonnet")).toBe(true); + const file = decodeInsights(machine.disk.get(OUT)!); + expect(file.header.provider).toBe("claude-code"); + expect(file.header.models).toEqual({ leaf: "sonnet", rollup: "sonnet" }); + }); + + it("--dry-run and --estimate print the model the resolved provider would run, and need neither key nor binary", async () => { + for (const flag of ["--dry-run", "--estimate"]) { + const found = captureIo(); + expect(await explainCommand(options([flag]), found, seamWith({ HOME }, binary(KNOWN)).seam)).toBe(EXIT.OK); + expect(found.stdout()).toContain("models: sonnet (operations), sonnet (types, modules)"); + // Asked for and not installed: still the plan, still its default — the error waits for a run that calls. + const asked = captureIo(); + expect(await explainCommand(options([flag, "--provider", "claude-code"]), asked, seamWith({}).seam)).toBe(EXIT.OK); + expect(asked.stdout()).toContain("models: sonnet (operations), sonnet (types, modules)"); + const keyed = captureIo(); + expect(await explainCommand(options([flag]), keyed, seamWith({ OPENROUTER_API_KEY: KEY, HOME }, binary(KNOWN)).seam)).toBe(EXIT.OK); + expect(keyed.stdout()).toContain(`models: ${DEFAULT_EXPLAIN_MODEL} (operations), ${DEFAULT_EXPLAIN_MODEL} (types, modules)`); + const pinned = captureIo(); + expect(await explainCommand(options([flag, "--provider", "claude-code", "--model", "claude-sonnet-5-5", "--rollup-model", "opus"]), pinned, seamWith({}).seam)).toBe(EXIT.OK); + expect(pinned.stdout()).toContain("models: claude-sonnet-5-5 (operations), opus (types, modules)"); + } + const json = captureIo(); + await explainCommand(options(["--dry-run", "--json"]), json, seamWith({ HOME }, binary(KNOWN)).seam); + expect(JSON.parse(json.stdout())).toMatchObject({ models: { leaf: "sonnet", rollup: "sonnet" } }); + }); + + it("auto with a key AND a binary keeps OpenRouter — a key is deliberate, an installed CLI is ambient — and says how to switch", async () => { + const machine = seamWith({ OPENROUTER_API_KEY: KEY, HOME }, binary(KNOWN)); + const io = captureIo(); + expect(await explainCommand(options(["--out", OUT]), io, machine.seam)).toBe(EXIT.OK); + expect(new Set(machine.providers)).toEqual(new Set(["openrouter"])); + expect(io.stderr()).toContain("provider: fake (OpenRouter and Claude Code are configured; using OpenRouter (pass --provider claude-code to run the local Claude Code))"); + expect(decodeInsights(machine.disk.get(OUT)!).header.provider).toBe("openrouter"); + }); + + it("--provider claude-code with nothing found is a usage error that leads with what was searched, then how to point at the binary", async () => { + const machine = seamWith({}); + const io = captureIo(); + const failure = await explainCommand(options(["--out", OUT, "--provider", "claude-code"]), io, machine.seam).then(() => undefined, (error: unknown) => error); + expect(failure).toBeInstanceOf(UsageError); + expect((failure as UsageError).message).toBe("no claude on PATH or in a known install location, and this run needs 68 model calls"); + expect((failure as UsageError).hint).toContain("Install Claude Code (https://code.claude.com/docs/en/setup) and log in, or point at the binary with --claude-path FILE or CLAUDE_CODE_PATH."); + expect((failure as UsageError).hint).toContain("Models: sonnet."); + expect(io.stdout()).toBe(""); + expect(machine.providers).toEqual([]); + }); + + it("a named binary that does not exist is a usage error leading with that path — never 'not set', never a fall-through to the binary on PATH", async () => { + const flagged = seamWith({ PATH: "/usr/bin" }, binary(ON_PATH)); + const byFlag = await explainCommand(options(["--out", OUT, "--claude-path", "/nowhere/claude"]), captureIo(), flagged.seam).then(() => undefined, (error: unknown) => error); + expect(byFlag).toBeInstanceOf(UsageError); + expect((byFlag as UsageError).message).toBe("--claude-path /nowhere/claude does not exist, and this run needs 68 model calls"); + expect(flagged.providers).toEqual([]); + expect(flagged.client.calls).toHaveLength(0); + const exported = seamWith({ PATH: "/usr/bin", CLAUDE_CODE_PATH: "/x/claude" }, binary(ON_PATH)); + const byEnv = await explainCommand(options(["--out", OUT, "--provider", "claude-code"]), captureIo(), exported.seam).then(() => undefined, (error: unknown) => error); + expect((byEnv as UsageError).message).toBe("CLAUDE_CODE_PATH=/x/claude does not exist, and this run needs 68 model calls"); + expect(exported.providers).toEqual([]); + }); + + it("--claude-path with a key provider is refused at parse time: that provider would never run the binary", () => { + for (const provider of ["openrouter", "cloudflare"]) { + expect(() => options(["--provider", provider, "--claude-path", "/opt/tools/claude"])).toThrow(`--claude-path names a binary that --provider ${provider} would never run`); + } + expect(options(["--provider", "claude-code", "--claude-path", "/opt/tools/claude"]).claudePath).toBe("/opt/tools/claude"); + expect(options(["--provider", "auto", "--claude-path", "/opt/tools/claude"]).claudePath).toBe("/opt/tools/claude"); + }); + + it("--claude-path FILE on the disk wins — over the binary on PATH and over a key — and the reason says so", async () => { + const machine = seamWith({ OPENROUTER_API_KEY: KEY, PATH: "/usr/bin" }, binary(ON_PATH, "/opt/tools/claude")); + const io = captureIo(); + expect(await explainCommand(options(["--out", OUT, "--claude-path", "/opt/tools/claude"]), io, machine.seam)).toBe(EXIT.OK); + expect(new Set(machine.providers)).toEqual(new Set(["claude-code"])); + expect(io.stderr()).toContain("provider: fake (--provider claude-code, --claude-path: /opt/tools/claude)"); + expect(decodeInsights(machine.disk.get(OUT)!).header.provider).toBe("claude-code"); + }); + + it("--max-tokens does not apply to claude-code: said once on stderr, and nothing said on a key provider", async () => { + const machine = seamWith({ HOME }, binary(KNOWN)); + const io = captureIo(); + expect(await explainCommand(options(["--out", OUT, "--max-tokens", "100", "--provider", "claude-code"]), io, machine.seam)).toBe(EXIT.OK); + expect(io.stderr().split(NOTE)).toHaveLength(2); + const keyed = seamWith({ OPENROUTER_API_KEY: KEY }); + const quiet = captureIo(); + expect(await explainCommand(options(["--out", OUT, "--max-tokens", "100"]), quiet, keyed.seam)).toBe(EXIT.OK); + expect(quiet.stderr()).not.toContain("--max-tokens does not apply"); + }); + + it("a 402 from claude-code aborts the run without the --max-tokens hint, which is a key provider's", async () => { + const machine = seamWith({ HOME }, binary(KNOWN)); + const broke: LlmClient = { name: "fake", complete: () => Promise.reject(new LlmError("billing: out of credit", 402, false)) }; + const io = captureIo(); + expect(await explainCommand(options(["--out", OUT, "--concurrency", "1"]), io, { ...machine.seam, clientFor: () => broke })).toBe(EXIT.FINDINGS); + expect(io.stderr()).toMatch(/aborted: .* answered 402/u); + expect(io.stderr()).not.toContain("--max-tokens"); + }); + + it("the flags: --provider claude-code and --claude-path parse, azure is still refused, --model has no static default", () => { + expect(EXPLAIN_PROVIDERS).toEqual(["auto", ...PROVIDERS]); + // Restated in args.ts (which must not load @codegraph/llm, and with it the SDK, for every command) and pinned here. + expect(DEFAULT_CLAUDE_CODE_MODEL).toBe(CLAUDE_CODE_DEFAULT_MODEL); + const parsed = options(["--provider", "claude-code", "--claude-path", "/opt/tools/claude"]); + expect(parsed.provider).toBe("claude-code"); + expect(parsed.claudePath).toBe("/opt/tools/claude"); + expect(options([]).model).toBeUndefined(); + expect(options([]).rollupModel).toBeUndefined(); + expect(options([]).claudePath).toBeUndefined(); + expect(() => parseInvocation(["explain", FIXTURE, "--provider", "azure"])).toThrow(/invalid value 'azure' for --provider/u); + }); +}); + describe("explain usage errors exit 2 with nothing on stdout", () => { it("without an API key when calls are planned", async () => { - // The real seam reads the process environment: a key in the developer's shell must not make it found. - for (const name of ["OPENROUTER_API_KEY", "CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_AI_GATEWAY_ID"]) vi.stubEnv(name, undefined); + // The real seam reads the process environment: a key in the developer's shell must not make it found, + // and neither must the Claude Code installed on this machine — PATH, HOME and the variables point nowhere. + for (const name of ["OPENROUTER_API_KEY", "CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_AI_GATEWAY_ID", "CLAUDE_CODE_PATH", "USERPROFILE", "APPDATA"]) vi.stubEnv(name, undefined); + vi.stubEnv("PATH", ""); + vi.stubEnv("HOME", "/nonexistent/home"); + // The Homebrew locations are probed by absolute path: on a machine that has one, ask for OpenRouter by name. + const homebrew = ["/opt/homebrew/bin/claude", "/usr/local/bin/claude"].some((path) => existsSync(path)); try { const io = captureIo(); - const code = await run(["explain", FIXTURE, "--src", SRC, "--out", OUT], io); + const code = await run(["explain", FIXTURE, "--src", SRC, "--out", OUT, ...(homebrew ? ["--provider", "openrouter"] : [])], io); expect(code).toBe(EXIT.USAGE); expect(io.stdout()).toBe(""); expect(io.stderr()).toContain("OPENROUTER_API_KEY"); expect(io.stderr()).toContain("CLOUDFLARE_API_TOKEN"); + expect(io.stderr()).toContain("--provider claude-code"); } finally { vi.unstubAllEnvs(); } diff --git a/website/content/docs/explanation/explaining-bottom-up.md b/website/content/docs/explanation/explaining-bottom-up.md index 1bd2de4..7a5d443 100644 --- a/website/content/docs/explanation/explaining-bottom-up.md +++ b/website/content/docs/explanation/explaining-bottom-up.md @@ -46,13 +46,20 @@ logic in it — is tested without a network at all. The provider SDK is itself h behind a one-function transport, so every request, response and error path is driven by a fake in tests and an SDK change is repaired in one file. -**Two providers, one contract.** Both speak the same chat-completion shape, -parsed once. What differs is the route: one goes through its own SDK with its own -key; the other goes through a gateway's REST API with a single token that both -authenticates and bills. Model names are the same `author/model` form on both, so -switching providers leaves every fingerprint — and therefore every reusable -record — intact. The resolution of which provider to use lives in one place, and -the side-car header records which one served the run. +**One port, three adapters.** The port is `LlmClient`: one structured completion +in, parsed JSON out, one error type. Behind it, three adapters. OpenRouter goes +through its own SDK with its own key; Cloudflare AI Gateway goes through a +gateway's REST API with a single token that both authenticates and bills — the +two speak the same chat-completion shape, parsed once, and name models in the +same `author/model` form, so switching between them leaves every fingerprint — +and therefore every reusable record — intact. The third, Claude Code headless, +is a subprocess: the `claude` CLI already installed and logged in on the +machine, one `claude -p` process per call, no key, Sonnet by default. It is found +on `PATH` or in the known install locations, or named with `--claude-path`; +`auto` prefers a key over it, because an exported key is a deliberate act and an +installed CLI is ambient. A fourth adapter — the Anthropic API with an API key — +is a named slot for later. The resolution of which adapter to use lives in one +place, and the side-car header records which one served the run. ## IN-2 · Units, and the walk order diff --git a/website/content/docs/how-to/explain-cost.md b/website/content/docs/how-to/explain-cost.md index 9bd3827..332364e 100644 --- a/website/content/docs/how-to/explain-cost.md +++ b/website/content/docs/how-to/explain-cost.md @@ -84,15 +84,26 @@ way to see whether the output is worth paying for on the rest of the corpus. ## Choose a provider -| Provider | Environment | +| Provider | What it needs | |---|---| | OpenRouter | `OPENROUTER_API_KEY` | | Cloudflare AI Gateway | `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID`, optional `CLOUDFLARE_AI_GATEWAY_ID` | - -`--provider auto` (the default) picks whichever is configured, and OpenRouter -when both are; `--provider openrouter` or `--provider cloudflare` forces one. The -Cloudflare token needs the AI Gateway Run permission, and without -`CLOUDFLARE_AI_GATEWAY_ID` the account's default gateway is used. +| Claude Code | an installed and logged-in Claude Code; no key; `--claude-path FILE` or `CLAUDE_CODE_PATH` when it is not on `PATH`. On Windows an npm-global `claude.cmd` is found but cannot be run (Node refuses `.cmd` without a shell: `EINVAL`); point `--claude-path` at the native installer's `%USERPROFILE%\.local\bin\claude.exe` | + +`--provider auto` (the default) picks the one that is configured; with several +it takes OpenRouter, then Cloudflare, then Claude Code — an exported key is a +deliberate act, an installed CLI is ambient, so the CLI never overrides a key. +`--provider openrouter`, `--provider cloudflare` or `--provider claude-code` +forces one. The Cloudflare token needs the AI Gateway Run permission, and +without `CLOUDFLARE_AI_GATEWAY_ID` the account's default gateway is used. Claude +Code runs in headless mode (`claude -p`), one process per call, Sonnet by +default (`--model sonnet`); it spends the subscription — the cost the run +reports is the CLI's `total_cost_usd` at list price — and `--max-tokens` does +not apply. The fingerprint carries the slug as requested (`sonnet`) and each +record's `model` the id that served (`claude-sonnet-5-5`), so a new Sonnet +behind the alias does not re-explain what was explained; a full id in `--model` +does. `--claude-path` implies `--provider claude-code` under `auto` and is +refused with a key provider. With nothing configured, the command refuses before it does any work: @@ -100,8 +111,10 @@ With nothing configured, the command refuses before it does any work: codegraph: OPENROUTER_API_KEY is not set (no provider configured), and this run needs 1 model call ``` -Model slugs are the same `author/model` form on both providers, so switching the -route leaves every fingerprint — and every reusable record — intact. +Model slugs are the same `author/model` form on both key providers, so switching +between them leaves every fingerprint — and every reusable record — intact. +Claude Code names models its own way (`sonnet`, `claude-sonnet-5-5`), so moving +to or from it re-explains what the new slug covers. ## Pick models per level diff --git a/website/content/docs/reference/artifacts/insights-jsonl.md b/website/content/docs/reference/artifacts/insights-jsonl.md index a034a49..4047a3e 100644 --- a/website/content/docs/reference/artifacts/insights-jsonl.md +++ b/website/content/docs/reference/artifacts/insights-jsonl.md @@ -6,7 +6,7 @@ weight: 6 The side-car [`explain`](/docs/reference/cli/explain/) writes: one explanation record per operation, type and module, in the vocabulary of the Specy domain metamodel. It lives **beside** the model — `.insights.jsonl` by default — and never inside it, so it can be regenerated, pointed at another model, or deleted without touching `model.jsonl` or `model.db`. {{< callout type="info" >}} -This page is derived from the Zod schemas in `packages/insights/src/schema.ts` and the vocabularies in `packages/insights/src/ddd.ts`. Unlike the other artifact pages it carries no excerpt from a real run: producing one requires a model provider and an API key. +This page is derived from the Zod schemas in `packages/insights/src/schema.ts` and the vocabularies in `packages/insights/src/ddd.ts`. Unlike the other artifact pages it carries no excerpt from a real run: producing one requires a model provider — an API key, or an installed Claude Code. {{< /callout >}} ## File layout @@ -31,7 +31,7 @@ During a run, finished records are appended one per line to `.journal` and | `promptVersion` | string | bumped whenever the prompt or a block shape changes; every fingerprint includes it | | `metamodel` | string | the vocabulary the blocks speak — `specy.domain/3` | | `models` | `{leaf, rollup}` | the model slug used for operations, and for types and modules | -| `provider` | string | which client served the calls (`openrouter`, `cloudflare`); absent on files written before it was recorded | +| `provider` | string | which adapter served the calls (`openrouter`, `cloudflare`, `claude-code`); absent on files written before it was recorded | | `depth` | integer ≥ 0 | how many levels of dependency explanations each prompt carried | | `source` | `{paths, langs, view}` | the models explained, their languages, and the view | diff --git a/website/content/docs/reference/cli/explain.md b/website/content/docs/reference/cli/explain.md index 666102a..ae8ba5e 100644 --- a/website/content/docs/reference/cli/explain.md +++ b/website/content/docs/reference/cli/explain.md @@ -8,7 +8,7 @@ Explain every operation, type and module with an LLM, bottom-up, into a side-car ## Synopsis ``` -codegraph explain [model.jsonl...] [--src DIR] [--out FILE] [--provider ] [--model SLUG] [--rollup-model SLUG] [--depth N] [--max-calls N] [--max-tokens N] [--concurrency N] [--max-lines N] [--max-scc N] [--terms N] [--scope IDS] [--framework ] [--internal-only] [--declared-only] [--no-cache] [--dry-run] [--estimate] [--price-in USD] [--price-out USD] [--force] [--retry-failed] [--json] +codegraph explain [model.jsonl...] [--src DIR] [--out FILE] [--provider ] [--claude-path FILE] [--model SLUG] [--rollup-model SLUG] [--depth N] [--max-calls N] [--max-tokens N] [--concurrency N] [--max-lines N] [--max-scc N] [--terms N] [--scope IDS] [--framework ] [--internal-only] [--declared-only] [--no-cache] [--dry-run] [--estimate] [--price-in USD] [--price-out USD] [--force] [--retry-failed] [--json] ``` ## Arguments @@ -23,8 +23,9 @@ codegraph explain [model.jsonl...] [--src DIR] [--out FILE] [--provider .insights.jsonl. | — | -| `--provider ` | Where the model calls go: openrouter (OPENROUTER_API_KEY) or cloudflare — Cloudflare AI Gateway's REST API (CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, optional CLOUDFLARE_AI_GATEWAY_ID). auto picks whichever is configured, OpenRouter when both are. | `auto` | -| `--model SLUG` | Model slug for operations (the leaves), in author/model form on either provider. | `openai/gpt-5.6-luna` | +| `--provider ` | Where the model calls go: openrouter (OPENROUTER_API_KEY), cloudflare — Cloudflare AI Gateway's REST API (CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID, optional CLOUDFLARE_AI_GATEWAY_ID) — or claude-code, the local Claude Code CLI in headless mode (`claude -p`, Sonnet by default, no key). auto picks whichever is configured; with several, OpenRouter, then Cloudflare, then Claude Code. | `auto` | +| `--claude-path FILE` | The Claude Code binary. Under `--provider auto` it implies claude-code; with openrouter or cloudflare it is an error. Otherwise CLAUDE_CODE_PATH, then `claude` on PATH, then the known install locations; a path that does not exist is an error, never a fall-through. | — | +| `--model SLUG` | Model slug for operations (the leaves). Defaults per provider: `openai/gpt-5.6-luna` (author/model form) on openrouter and cloudflare, `sonnet` on claude-code — an alias Claude Code resolves to the latest Sonnet, so a full id such as `claude-sonnet-5-5` pins the fingerprint. | per provider | | `--rollup-model SLUG` | Model slug for types and modules; defaults to --model. | — | | `--depth N` | How many levels of dependency explanations a prompt carries. | `1` | | `--max-calls N` | Stop planning model calls after this many; what runs is a dependency-consistent prefix. | — | @@ -41,7 +42,7 @@ codegraph explain [model.jsonl...] [--src DIR] [--out FILE] [--provider set` | -| both configured | `openrouter` | `both OpenRouter and Cloudflare are configured; using OpenRouter (pass --provider cloudflare to route through AI Gateway)` | -| neither configured | `openrouter`, reported as missing its variables | `no provider configured` | +| exactly one configured | that one | ` set`, or where the binary was found — always the absolute path, e.g. `provider: claude-code (found on PATH: /home/me/.local/bin/claude)`, or `found in a known install location: /home/me/.local/bin/claude`, `CLAUDE_CODE_PATH: /opt/tools/claude` | +| several configured | the first of OpenRouter, Cloudflare, Claude Code | `OpenRouter and Claude Code are configured; using OpenRouter (pass --provider claude-code to run the local Claude Code)` — a key is deliberate, an installed CLI is ambient | +| none configured | `openrouter`, reported as missing its variables | `no provider configured` | -An explicit `--provider openrouter` or `--provider cloudflare` skips the decision and reports exactly which variables that provider still lacks. `--dry-run` and `--estimate` make no call and need no variable at all. +An explicit `--provider openrouter`, `--provider cloudflare` or `--provider claude-code` skips the decision; its reason line is prefixed with the flag, e.g. `provider: claude-code (--provider claude-code, --claude-path: /opt/tools/claude)`. A run that needs calls then reports exactly what that provider lacks: the variables (`OPENROUTER_API_KEY is not set (--provider openrouter), and this run needs 68 model calls`), or for Claude Code what the discovery said (`no claude on PATH or in a known install location, and this run needs 68 model calls`; `--claude-path /nowhere/claude does not exist, …`; `CLAUDE_CODE_PATH=/x/claude does not exist, …`). `--claude-path FILE` implies `--provider claude-code` under `auto` and is refused with `--provider openrouter` or `cloudflare`. `--dry-run` and `--estimate` make no call and need no variable and no binary at all. ## Dev servers @@ -56,4 +57,4 @@ Without the variable the app falls back to `?src=URL`, drag and drop, or a file ## Not environment variables -`JAVA_HOME` and `PATH` matter only to the [Java extractor](/docs/reference/java-extractor/), which is an ordinary JVM program: non-interactive shells do not source sdkman, so a JDK has to be on `PATH` explicitly. +`JAVA_HOME` matters only to the [Java extractor](/docs/reference/java-extractor/), which is an ordinary JVM program: non-interactive shells do not source sdkman, so a JDK has to be on `PATH` explicitly. `PATH` is also where `explain` looks for `claude` (above), and `HOME`, `USERPROFILE` and `APPDATA` only name the install locations it searches next. diff --git a/website/content/docs/tutorials/explain.md b/website/content/docs/tutorials/explain.md index cf9f77b..b5b519b 100644 --- a/website/content/docs/tutorials/explain.md +++ b/website/content/docs/tutorials/explain.md @@ -177,15 +177,27 @@ When you do have a key, the run is: OPENROUTER_API_KEY=… codegraph explain order.jsonl --src "$SRC" --max-calls 50 ``` -or, for the other supported provider: +or, for the other key provider: ```bash CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… \ codegraph explain order.jsonl --src "$SRC" --provider cloudflare ``` -Model names are the same `author/model` form on both, so switching provider -leaves every fingerprint — and therefore every reusable record — intact. +Model names are the same `author/model` form on both, so switching between +them leaves every fingerprint — and therefore every reusable record — intact. + +With no key at all but Claude Code installed and logged in, the run goes +through it in headless mode: + +```bash +codegraph explain order.jsonl --src "$SRC" --provider claude-code +``` + +What it costs: the subscription, on Sonnet (`--model sonnet` by default) — each +call is one `claude -p` process carrying roughly 1 100 cached scaffolding tokens +on top of the prompt; the cost the run reports is the CLI's `total_cost_usd` at +list price. `auto` picks it by itself when no key is exported. {{< callout type="warning" >}} `--concurrency` defaults to 4. A new OpenRouter account is limited to 20 From 7b514bc312bba4de01395d2c80e89f3ca99585f0 Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Tue, 10 Nov 2026 10:55:59 +0000 Subject: [PATCH 3/3] fix(explain): count claude code prompt overhead MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The M20b live run billed 307 896 prompt tokens for an estimate of 114 136: every `claude -p` prompt carries Claude Code's scaffolding and the response schema, which it sends as prompt. 48 operation calls came in +2 292…+2 617 over the bare estimate. promptOverhead(provider) in @codegraph/llm says what a transport adds: nothing on the key providers (PetClinic on OpenRouter: +115 median per operation call), CLAUDE_CODE_SCAFFOLD_TOKENS (1 850) plus the schema on Claude Code. planRun takes it as a plain number, so the walk still never learns a provider; the CLI hands it over and both estimate renderings say what was added. Java fixture, re-estimated: 280 481 (was 114 136); operations within 1 % of what was billed. Types (x1.28) and modules (x1.38) stay under, as on OpenRouter: the dependency explanations a prompt inlines do not exist at plan time — a gap every provider shares, not fixed here. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PKCVh1q6FUhWzQi6KYtoTz --- PLAN.md | 12 ++++++- docs/insights.md | 6 +++- packages/cli/src/commands/explain.ts | 34 ++++++++++++++++--- packages/cli/test/explain.test.ts | 27 ++++++++++++++- packages/insights/src/plan.ts | 25 ++++++++++++-- packages/insights/test/run.test.ts | 23 +++++++++++-- packages/llm/src/claude-code.ts | 8 +++++ packages/llm/src/providers.ts | 13 ++++++- packages/llm/test/providers.test.ts | 18 +++++++++- .../docs/explanation/explaining-bottom-up.md | 4 ++- website/content/docs/how-to/explain-cost.md | 6 +++- 11 files changed, 160 insertions(+), 16 deletions(-) diff --git a/PLAN.md b/PLAN.md index 5a1b6be..94a599e 100644 --- a/PLAN.md +++ b/PLAN.md @@ -6040,6 +6040,16 @@ builds `claudeCodeClient`; the seam's `clientFor` takes the whole resolution. - The fingerprint carries the slug as REQUESTED (`sonnet`), each record's `model` the id that served (`claude-sonnet-5-5`): a new Sonnet behind the alias does not re-explain what was explained; a full id in `--model` does. +- The estimate counts what the transport adds to every prompt + (`promptOverhead(provider)` in `providers.ts`, handed to `planRun` as a + number — the walk never learns a provider): nothing on the key providers; + on Claude Code `CLAUDE_CODE_SCAFFOLD_TOKENS` (1 850) a call plus the + response schema, which `claude -p` sends as prompt. The live run measured + why: 48 operation calls billed +2 292…+2 617 over the bare estimate. With + it, operations land within 1 % (190 850 estimated, 191 862 billed); types + (×1.28) and modules (×1.38) stay under, as on OpenRouter (PetClinic types + ×1.20…1.38) — the dependency explanations a prompt inlines do not exist + at plan time, a gap every provider shares. ### 21.5 Milestone split @@ -6109,7 +6119,7 @@ builds `claudeCodeClient`; the seam's `clientFor` takes the whole resolution. | M19b | Vocabulary — cloud, tab, city channel | ✅ (2026-10-26, three stacked PRs from #31, not yet merged; Broadleaf's cloud and its city raised by `order` are the demo images) deterministic spiral layout with an injected measurer and the no-overlap property; `--svg` with the fixture snapshot; `serve` builds `/vocabulary.json` and answers `/carriers.json?scope=&term=`; the sixth navigator tab (scope follows the selection, chips, table, carriers → reveal), literals pinned, types-only import; `vocabulary:` metric source through the CLI hook, city unchanged; the two demo images under `docs/` and the README section — the issue's fourth criterion | | M19c | Vocabulary — glossary in the explanation | `words` on every insight block — the words of the unit's name, its parameters' and (for a type) its fields', each with `in`, `concern` (domain / technical / ambiguous), `sense`, `meaning`, in that entity's context, asked in the SAME call that explains it; `glossary` on the module block reconciling its types' entries with `polysemous`; `PROMPT_VERSION` 2, the words `.optional()` in the record schema so every existing side-car round-trips byte-identical — no new record type, no format change; the store at version 2 with the `insight_word` projection (rebuilt on `--import`); readers `insights --word/--glossary/--polysemy/--concerns`, `vocabulary --drift-insights`, `/glossary.json`, the entries shown as inferences in both panels; the Broadleaf re-explanation priced by `--estimate` and measured; `docs/vocabulary.md` | | M20a | Model providers — the Claude Code adapter | ✅ (2026-11-10, 94 `@codegraph/llm` tests) `claudeCodeClient` in `@codegraph/llm` (§21.1): `claude -p --output-format json --json-schema --system-prompt --tools "" --safe-mode --no-session-persistence`, the user prompt on stdin, `structured_output` / `usage` / `total_cost_usd` / `modelUsage` read into the port's response, every failure classified into the port's one error type; `findClaudeCode` (option → `CLAUDE_CODE_PATH` → PATH → known install locations, pure) and `resolveProvider` with the fixed precedence; fake-process tests, the boundary test unchanged | -| M20b | Model providers — wired and documented | ✅ (2026-11-10, live on Claude Code 2.1.322, Java fixture: 68 calls, 0 failed, 79 records — 70 explained, stamped `claude-sonnet-5-5`, 9 templated — decode-clean, eof `$1.03` for 307 896 + 54 688 tokens; the prompt side is ≈ 2.7× the estimate, the ≈ 2 500 tokens of Claude Code scaffolding per call the estimate does not count) `--provider claude-code`, `--claude-path`, `--model` default per provider resolved before the plan (`sonnet`), the usage error naming the fix and the `--max-tokens` note; a live run on the Java fixture; `docs/cli.md`, `docs/insights.md`, README, CLAUDE.md and the website's explain pages name the port, the three adapters and the Anthropic API slot (§21.6) | +| M20b | Model providers — wired and documented | ✅ (2026-11-10, live on Claude Code 2.1.322, Java fixture: 68 calls, 0 failed, 79 records — 70 explained, stamped `claude-sonnet-5-5`, 9 templated — decode-clean, eof `$1.03` for 307 896 + 54 688 tokens; the prompt side came in ≈ 2.7× the bare estimate — Claude Code's per-call scaffolding and schema, which the estimate now counts (§21.4): 280 481 estimated for the 307 896 billed) `--provider claude-code`, `--claude-path`, `--model` default per provider resolved before the plan (`sonnet`), the usage error naming the fix and the `--max-tokens` note; a live run on the Java fixture; `docs/cli.md`, `docs/insights.md`, README, CLAUDE.md and the website's explain pages name the port, the three adapters and the Anthropic API slot (§21.6) | ## 23. Decisions made in this plan (deltas vs. the design doc) diff --git a/docs/insights.md b/docs/insights.md index f777db3..b7de0a8 100644 --- a/docs/insights.md +++ b/docs/insights.md @@ -404,7 +404,11 @@ once the callee exists. calls it will make, the estimated prompt tokens per level — and makes no call; it needs no key. `--estimate` prints only the volume: calls, input and output tokens per level, and a cost when `--price-in`/`--price-out` (USD per million -tokens) are given. Input is the rendered prompts at four characters per token; +tokens) are given. Input is the rendered prompts at four characters per token, +plus what the transport adds to every prompt — nothing on the key providers; +on Claude Code its scaffolding (1 850 tokens a call) and the response schema, +which it sends as prompt (fitted on the Java fixture, where operations then +land within 1 % of what was billed); output is a measured figure per block asked for (operation 470, type 530, module 530 tokens), plus 120 per word and 125 per glossary entry asked to define — fitted on a live prompt-2 run of gpt-5.6-luna over Spring PetClinic, diff --git a/packages/cli/src/commands/explain.ts b/packages/cli/src/commands/explain.ts index 7abec6f..1423f8c 100644 --- a/packages/cli/src/commands/explain.ts +++ b/packages/cli/src/commands/explain.ts @@ -41,7 +41,16 @@ import { type RunUsage, type Unit, } from "@codegraph/insights"; -import { clientFromResolution, findClaudeCode, resolveProvider, type LlmClient, type Provider, type ProviderResolution } from "@codegraph/llm"; +import { + clientFromResolution, + findClaudeCode, + promptOverhead, + resolveProvider, + type LlmClient, + type PromptOverhead, + type Provider, + type ProviderResolution, +} from "@codegraph/llm"; import { buildVocabulary, definitionSpeller, rankedWords, type VocabularyArtifact } from "@codegraph/vocabulary"; import { DEFAULT_CLAUDE_CODE_MODEL, DEFAULT_EXPLAIN_MODEL, type ExplainOptions } from "../args.js"; import { EXIT, UsageError, type ExitCode } from "../exit.js"; @@ -206,7 +215,12 @@ async function confirmOnTerminal(question: string): Promise { /** `ExplainOptions` once the provider is known: `--model` defaulted per provider, `--rollup-model` to it. */ -type ResolvedOptions = Omit & { readonly model: string; readonly rollupModel: string }; +type ResolvedOptions = Omit & { + readonly model: string; + readonly rollupModel: string; + /** What the resolved provider's transport adds to every prompt, and who adds it — for the estimate. */ + readonly promptOverhead: PromptOverhead & { readonly by: Provider }; +}; /** The provider and, from it, the models. `--claude-path` names a binary on purpose: on `auto` it implies `--provider claude-code`. */ function resolveRun(flags: ExplainOptions, seam: ExplainSeam): { resolution: ProviderResolution; options: ResolvedOptions } { @@ -214,7 +228,8 @@ function resolveRun(flags: ExplainOptions, seam: ExplainSeam): { resolution: Pro const choice = flags.provider === "auto" && flags.claudePath !== undefined ? "claude-code" : flags.provider; const resolution = resolveProvider(choice, seam.env, { claudeCode: discovery }); const model = flags.model ?? (resolution.provider === "claude-code" ? DEFAULT_CLAUDE_CODE_MODEL : DEFAULT_EXPLAIN_MODEL); - return { resolution, options: { ...flags, model, rollupModel: flags.rollupModel ?? model } }; + const overhead = { ...promptOverhead(resolution.provider), by: resolution.provider }; + return { resolution, options: { ...flags, model, rollupModel: flags.rollupModel ?? model, promptOverhead: overhead } }; } export async function explainCommand( @@ -273,6 +288,7 @@ export async function explainCommand( maxCalls: options.maxCalls, inScope: options.retryFailed ? retryScope(previousFailures, walk) : scopePredicate(options.scope, graph, units), terms: options.terms, + promptOverhead: options.promptOverhead, }); if (!source.clean) { @@ -801,7 +817,7 @@ function printEstimate(plan: RunPlan, options: ResolvedOptions, io: IoSink): voi ...(options.priceOut === undefined ? {} : { priceOut: options.priceOut }), ...(cost === undefined ? {} : { cost }), assumptions: { - promptTokens: "characters of the rendered prompts / 4", + promptTokens: `characters of the rendered prompts / 4${overheadAssumption(options.promptOverhead)}`, completionTokens: `measured on a live run: ${outputAssumption()}`, excluded: "repair re-asks, rate-limit retries", }, @@ -835,11 +851,19 @@ function estimateLines(plan: RunPlan, options: ResolvedOptions): string[] { } else { lines.push(" cost: pass --price-in USD --price-out USD (per million tokens) for a figure"); } - lines.push(` input ≈ rendered prompts at 4 characters per token; output ≈ measured on a live run: ${outputAssumption()}.`); + const { perCall, schema, by } = options.promptOverhead; + const added = perCall === 0 && !schema ? "" : `, plus ${grouped(perCall)} per call${schema ? " and the response schema" : ""} that ${by} adds to every prompt`; + lines.push(` input ≈ rendered prompts at 4 characters per token${added}; output ≈ measured on a live run: ${outputAssumption()}.`); lines.push(" not included: repair re-asks, rate-limit retries. Records already in the side-car are reused, not re-sent."); return lines; } +/** The `--json` estimate's word for what the transport adds to every prompt; nothing when it adds nothing. */ +function overheadAssumption({ perCall, schema, by }: ResolvedOptions["promptOverhead"]): string { + if (perCall === 0 && !schema) return ""; + return `, + ${perCall} per call${schema ? " + the response schema" : ""} (${by})`; +} + /** What the output figure assumes, from the constants it is computed with. */ function outputAssumption(): string { const { operation, type, module } = COMPLETION_TOKENS_PER_BLOCK; diff --git a/packages/cli/test/explain.test.ts b/packages/cli/test/explain.test.ts index 5fe8ae6..f6e4182 100644 --- a/packages/cli/test/explain.test.ts +++ b/packages/cli/test/explain.test.ts @@ -10,12 +10,14 @@ import { COMPLETION_TOKENS_PER_WORD, decodeInsights, encodeInsightsToString, + estimateTokens, insightsStorePathFor, + responseJsonSchema, sqliteInsightsStore, type InsightRecord, type InsightsStore, } from "@codegraph/insights"; -import { CLAUDE_CODE_DEFAULT_MODEL, LlmError, PROVIDERS, fakeLlmClient, type LlmClient, type LlmRequest, type Provider } from "@codegraph/llm"; +import { CLAUDE_CODE_DEFAULT_MODEL, CLAUDE_CODE_SCAFFOLD_TOKENS, LlmError, PROVIDERS, fakeLlmClient, type LlmClient, type LlmRequest, type Provider } from "@codegraph/llm"; import { EXIT, UsageError } from "../src/exit.js"; import { captureIo } from "../src/io.js"; import { run } from "../src/main.js"; @@ -911,6 +913,29 @@ describe("explain runs the installed Claude Code as a provider (PLAN.md §21, M2 expect(quiet.stderr()).not.toContain("--max-tokens does not apply"); }); + it("--estimate on claude-code counts the scaffolding and schema Claude Code adds to every prompt, and says so; a key provider adds nothing", async () => { + const estimate = async (args: string[], machine: ReturnType) => { + const io = captureIo(); + expect(await explainCommand(options(["--out", OUT, "--estimate", ...args]), io, machine.seam)).toBe(EXIT.OK); + return io.stdout(); + }; + const keyed = JSON.parse(await estimate(["--json"], seamWith({ OPENROUTER_API_KEY: KEY }))); + const local = JSON.parse(await estimate(["--json", "--provider", "claude-code"], seamWith({ HOME }, binary(KNOWN)))); + expect(local.calls).toBe(keyed.calls); + expect(local.completionTokens).toBe(keyed.completionTokens); + const levels = ["operation", "type", "module"] as const; + const schemas = levels.flatMap((level) => (["block", "scc"] as const).map((shape) => estimateTokens(JSON.stringify(responseJsonSchema(level, shape))))); + const added = local.promptTokens - keyed.promptTokens; + expect(added).toBeGreaterThan(keyed.calls * CLAUDE_CODE_SCAFFOLD_TOKENS); + expect(added).toBeLessThanOrEqual(keyed.calls * (CLAUDE_CODE_SCAFFOLD_TOKENS + Math.max(...schemas))); + expect(local.assumptions.promptTokens).toContain(`${CLAUDE_CODE_SCAFFOLD_TOKENS} per call + the response schema (claude-code)`); + expect(keyed.assumptions.promptTokens).toBe("characters of the rendered prompts / 4"); + + const said = `plus ${String(CLAUDE_CODE_SCAFFOLD_TOKENS).replace(/\B(?=(\d{3})+(?!\d))/gu, " ")} per call and the response schema that claude-code adds to every prompt`; + expect(await estimate(["--provider", "claude-code"], seamWith({ HOME }, binary(KNOWN)))).toContain(said); + expect(await estimate([], seamWith({ OPENROUTER_API_KEY: KEY }))).not.toContain("per call"); + }); + it("a 402 from claude-code aborts the run without the --max-tokens hint, which is a key provider's", async () => { const machine = seamWith({ HOME }, binary(KNOWN)); const broke: LlmClient = { name: "fake", complete: () => Promise.reject(new LlmError("billing: out of credit", 402, false)) }; diff --git a/packages/insights/src/plan.ts b/packages/insights/src/plan.ts index fced14a..c41de83 100644 --- a/packages/insights/src/plan.ts +++ b/packages/insights/src/plan.ts @@ -3,7 +3,7 @@ import { fingerprintOf } from "./fingerprint.js"; import type { Unit, WalkPlan } from "./order.js"; import { estimateCompletionTokens, estimateTokens, renderPrompts, type Prompt } from "./prompt.js"; import { sourceOf, type RecordSource } from "./records.js"; -import type { FailureRecord, InsightRecord, Level } from "./schema.js"; +import { responseJsonSchema, type FailureRecord, type InsightRecord, type Level } from "./schema.js"; import type { TemplateKind } from "./units.js"; /** @@ -75,6 +75,18 @@ export interface PlanOptions { readonly inScope: ((unit: Unit) => boolean) | undefined; /** A module's glossary keeps its heaviest `terms` words (`--terms`). */ readonly terms: number; + /** What the transport adds to every prompt, for the estimate; the caller's to know (absent = nothing). */ + readonly promptOverhead?: PromptOverhead; +} + +/** + * Prompt tokens a call is billed beyond its system and user text: a fixed + * count, plus the response schema when the transport puts it in the prompt. + * A number, never a provider: the walk does not learn who it talks to. + */ +export interface PromptOverhead { + readonly perCall: number; + readonly schema: boolean; } export type PlanEnv = Omit; @@ -149,6 +161,15 @@ export function planRun( module: { calls: 0, promptTokens: 0, completionTokens: 0, units: 0 }, }; const byStatus: Record = { llm: 0, template: 0, reuse: 0, "skip-scope": 0, "skip-budget": 0 }; + const overhead = options.promptOverhead ?? { perCall: 0, schema: false }; + const schemaTokens = new Map(); + const overheadOf = (level: Level, shape: Prompt["shape"]): number => { + if (!overhead.schema) return overhead.perCall; + const key = `${level}/${shape}`; + let tokens = schemaTokens.get(key); + if (tokens === undefined) schemaTokens.set(key, (tokens = estimateTokens(JSON.stringify(responseJsonSchema(level, shape))))); + return overhead.perCall + tokens; + }; let budget = options.maxCalls ?? Number.POSITIVE_INFINITY; let exhausted = false; const statusOf = new Map(); @@ -187,7 +208,7 @@ export function planRun( budget -= prompts.length; } } - const promptTokens = prompts.reduce((sum, p) => sum + estimateTokens(p.system) + estimateTokens(p.user), 0); + const promptTokens = prompts.reduce((sum, p) => sum + estimateTokens(p.system) + estimateTokens(p.user) + overheadOf(unit.level, p.shape), 0); const completionTokens = prompts.reduce((sum, p) => sum + estimateCompletionTokens(unit.level, p.memberIds.length, p.asked), 0); statusOf.set(unit.id, status); byStatus[status] += 1; diff --git a/packages/insights/test/run.test.ts b/packages/insights/test/run.test.ts index 397b763..eb92ef1 100644 --- a/packages/insights/test/run.test.ts +++ b/packages/insights/test/run.test.ts @@ -2,10 +2,10 @@ import { describe, expect, it } from "vitest"; import type { Edge, Entity } from "@codegraph/core"; import { buildWalk } from "../src/order.js"; import { planRun, retryScope, type PlanEnv, type PlanOptions } from "../src/plan.js"; -import { COMPLETION_TOKENS_PER_BLOCK, COMPLETION_TOKENS_PER_GLOSSARY_ENTRY, COMPLETION_TOKENS_PER_WORD } from "../src/prompt.js"; +import { COMPLETION_TOKENS_PER_BLOCK, COMPLETION_TOKENS_PER_GLOSSARY_ENTRY, COMPLETION_TOKENS_PER_WORD, estimateTokens } from "../src/prompt.js"; import { memoryBook, type RecordBook } from "../src/records.js"; import { executeRun, type Completer, type CompletionRequest } from "../src/run.js"; -import type { Block, FailureRecord, InsightRecord, ModuleBlock, OperationBlock, TypeBlock } from "../src/schema.js"; +import { responseJsonSchema, type Block, type FailureRecord, type InsightRecord, type ModuleBlock, type OperationBlock, type TypeBlock } from "../src/schema.js"; import { createSourceReader, mapReader } from "../src/source.js"; import { edge, field, graphOf, method, pkg, prepared, toySpeller, type } from "./fixture.js"; @@ -249,6 +249,25 @@ describe("planRun", () => { for (const step of plan.steps) expect(step.fingerprint).toMatch(/^[0-9a-f]{64}$/); }); + it("a prompt overhead adds its tokens to every call, the response schema's when it rides in the prompt, and nothing where no call is made", () => { + const { walk, env } = corpus(); + const bare = planRun(walk, new Map(), env, OPTIONS); + const fixed = planRun(walk, new Map(), env, { ...OPTIONS, promptOverhead: { perCall: 1000, schema: false } }); + const schemed = planRun(walk, new Map(), env, { ...OPTIONS, promptOverhead: { perCall: 1000, schema: true } }); + const before = new Map(bare.steps.map((s) => [s.unit.id, s])); + for (const [plan, schema] of [[fixed, false], [schemed, true]] as const) { + for (const step of plan.steps) { + const was = before.get(step.unit.id)!; + const perCall = 1000 + (schema ? estimateTokens(JSON.stringify(responseJsonSchema(step.unit.level))) : 0); + expect(step.promptTokens - was.promptTokens).toBe(step.calls * perCall); + expect(step.completionTokens).toBe(was.completionTokens); + } + } + expect(fixed.estimates.promptTokens - bare.estimates.promptTokens).toBe(1000 * bare.estimates.calls); + expect(fixed.steps.find((s) => s.unit.id === m("getTotal"))?.promptTokens).toBe(0); + expect(planRun(walk, new Map(), env, { ...OPTIONS, promptOverhead: { perCall: 0, schema: false } }).estimates).toEqual(bare.estimates); + }); + it("--max-calls keeps a dependency-consistent prefix of the walk", () => { const { walk, env } = corpus(); const plan = planRun(walk, new Map(), env, { ...OPTIONS, maxCalls: 2 }); diff --git a/packages/llm/src/claude-code.ts b/packages/llm/src/claude-code.ts index 64c5f82..6936ac1 100644 --- a/packages/llm/src/claude-code.ts +++ b/packages/llm/src/claude-code.ts @@ -40,6 +40,14 @@ import { withRetry, type RetryOptions } from "./retry.js"; /** Claude Code's alias for the latest Sonnet; a full id (`claude-sonnet-5-5`) pins the fingerprint. */ export const CLAUDE_CODE_DEFAULT_MODEL = "sonnet"; export const CLAUDE_CODE_DEFAULT_TIMEOUT_MS = 600_000; + +/** + * Prompt tokens `claude -p` bills per call beyond the system and user text, the + * response schema aside (it rides in the prompt as a tool, counted per prompt). + * Fitted on the Java fixture (2.1.322, 2026-11-10): 48 operation calls billed + * +2 292…+2 617 over the estimate, median +2 342, with a ~498-token schema. + */ +export const CLAUDE_CODE_SCAFFOLD_TOKENS = 1850; /** After SIGTERM at the timeout or on abort, how long the runner waits before SIGKILL. */ export const CLAUDE_CODE_KILL_GRACE_MS = 5_000; /** After the child's exit, how long the runner waits for its pipes to close before destroying them (a descendant may hold them). */ diff --git a/packages/llm/src/providers.ts b/packages/llm/src/providers.ts index 6f543a6..edea646 100644 --- a/packages/llm/src/providers.ts +++ b/packages/llm/src/providers.ts @@ -1,4 +1,4 @@ -import { claudeCodeClient } from "./claude-code.js"; +import { CLAUDE_CODE_SCAFFOLD_TOKENS, claudeCodeClient } from "./claude-code.js"; import { CLAUDE_CODE_PATH_VARIABLE, type ClaudeCodeDiscovery, type ClaudeCodeLocation } from "./claude-code-discovery.js"; import type { LlmClient } from "./client.js"; import { cloudflareGatewayClient } from "./cloudflare.js"; @@ -36,6 +36,17 @@ export const PROVIDER_VARIABLES: Readonly>; +/** Prompt tokens an adapter's transport adds to every call, for an estimate: a fixed count, and whether the response schema is sent as prompt. */ +export interface PromptOverhead { + readonly perCall: number; + readonly schema: boolean; +} + +/** The key adapters send the schema as a response format, billed as nothing measurable (PetClinic, +115 median per operation call). */ +export function promptOverhead(provider: Provider): PromptOverhead { + return provider === "claude-code" ? { perCall: CLAUDE_CODE_SCAFFOLD_TOKENS, schema: true } : { perCall: 0, schema: false }; +} + /** What resolution knows beyond the environment: the outcome of looking for the Claude Code binary. Absent = not looked for = not configured. */ export interface ProviderProbe { readonly claudeCode?: ClaudeCodeDiscovery | undefined; diff --git a/packages/llm/test/providers.test.ts b/packages/llm/test/providers.test.ts index 07f10db..f7b350f 100644 --- a/packages/llm/test/providers.test.ts +++ b/packages/llm/test/providers.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import type { ClaudeCodeDiscovery } from "../src/claude-code-discovery.js"; -import { clientFromEnv, clientFromResolution, isConfigured, missingVariables, resolveProvider } from "../src/providers.js"; +import { CLAUDE_CODE_SCAFFOLD_TOKENS } from "../src/claude-code.js"; +import { clientFromEnv, clientFromResolution, isConfigured, missingVariables, promptOverhead, resolveProvider } from "../src/providers.js"; const OR = { OPENROUTER_API_KEY: "sk-or" }; const CF = { CLOUDFLARE_API_TOKEN: "cf", CLOUDFLARE_ACCOUNT_ID: "acc" }; @@ -8,6 +9,21 @@ const CLAUDE = "/home/me/.local/bin/claude"; const FOUND: ClaudeCodeDiscovery = { location: { path: CLAUDE, source: "PATH" }, reason: "found on PATH" }; const NOT_FOUND: ClaudeCodeDiscovery = { location: undefined, reason: "no claude on PATH or in a known install location" }; +describe("promptOverhead", () => { + it("is nothing on the key adapters; on Claude Code, its scaffolding per call with the response schema in the prompt", () => { + expect(promptOverhead("openrouter")).toEqual({ perCall: 0, schema: false }); + expect(promptOverhead("cloudflare")).toEqual({ perCall: 0, schema: false }); + expect(promptOverhead("claude-code")).toEqual({ perCall: CLAUDE_CODE_SCAFFOLD_TOKENS, schema: true }); + }); + + it("keeps Claude Code's scaffolding inside what the live run measured", () => { + // Java fixture, 2.1.322, 48 operation calls: billed − estimated prompt = +2 292…+2 617, + // less the ~498-token operation schema → 1 794…2 119 of scaffolding. + expect(CLAUDE_CODE_SCAFFOLD_TOKENS).toBeGreaterThanOrEqual(1794); + expect(CLAUDE_CODE_SCAFFOLD_TOKENS).toBeLessThanOrEqual(2119); + }); +}); + describe("resolveProvider", () => { it("auto picks the one provider that is configured", () => { expect(resolveProvider("auto", OR)).toMatchObject({ provider: "openrouter", missing: [] }); diff --git a/website/content/docs/explanation/explaining-bottom-up.md b/website/content/docs/explanation/explaining-bottom-up.md index 7a5d443..7fe52b9 100644 --- a/website/content/docs/explanation/explaining-bottom-up.md +++ b/website/content/docs/explanation/explaining-bottom-up.md @@ -187,7 +187,9 @@ calls it will make, the estimated prompt tokens per level — and makes no call. needs no API key at all, which means the plan is inspectable by someone who has not decided to spend anything yet. An **estimate** prints the volume: calls, input and output tokens per level, and a cost when prices per million tokens are -supplied. Input is the rendered prompts at four characters per token; output is +supplied. Input is the rendered prompts at four characters per token — plus, +on Claude Code, the scaffolding and the response schema it adds to every prompt, +about 1 850 tokens a call before the schema; output is one measured figure per block asked for — 470 tokens for an operation, 530 for a type or a module — plus 120 per word the prompt asks to define and 125 per glossary entry, fitted on a live run over Spring PetClinic with the model's diff --git a/website/content/docs/how-to/explain-cost.md b/website/content/docs/how-to/explain-cost.md index 332364e..08aff47 100644 --- a/website/content/docs/how-to/explain-cost.md +++ b/website/content/docs/how-to/explain-cost.md @@ -99,7 +99,11 @@ without `CLOUDFLARE_AI_GATEWAY_ID` the account's default gateway is used. Claude Code runs in headless mode (`claude -p`), one process per call, Sonnet by default (`--model sonnet`); it spends the subscription — the cost the run reports is the CLI's `total_cost_usd` at list price — and `--max-tokens` does -not apply. The fingerprint carries the slug as requested (`sonnet`) and each +not apply. Every `claude -p` prompt carries Claude Code's own scaffolding and +the response schema, so its estimate adds 1 850 tokens a call plus the schema +and says so (`plus 1 850 per call and the response schema that claude-code +adds to every prompt`): on the Java fixture that is 280 481 input tokens +against 114 136 for a key provider, for the same 68 calls. The fingerprint carries the slug as requested (`sonnet`) and each record's `model` the id that served (`claude-sonnet-5-5`), so a new Sonnet behind the alias does not re-explain what was explained; a full id in `--model` does. `--claude-path` implies `--provider claude-code` under `auto` and is