// THE MODEL LOG's writer and readers (demo epic D3; the shape is ./callLog.ts). // // A run opens a ModelLogWriter over its files and runs its body inside // `runWithModelLog`; every model call under it — structuredAnswer on either // provider, each turn of the agent loop, a Claude Code session's answer — goes // through ONE function, `recordModelCall`, which finds the writer in the async // context and appends the call. Outside a run (a test calling a task directly, // a CLI run with no log) there is no writer and nothing is recorded. // // A RECORD NEVER FAILS THE RUN: every append is caught and the first failure // logged once. Writes are queued one at a time, in order, per file, across // every writer in the process (two media drafts on one iteration share its // files), so a run's number and its call ids are allocated in order. // // SERVER-ONLY (node:async_hooks, node:fs). One storage and one queue per // process, on globalThis (the house pattern: Next may load a module twice). import { AsyncLocalStorage } from "node:async_hooks"; import { appendFile, mkdir, open, stat } from "node:fs/promises"; import { createReadStream } from "node:fs"; import os from "node:os"; import path from "node:path"; import { createInterface } from "node:readline"; import { keyRedactor } from "./anthropic"; import type { LlmConfig } from "./config"; import { ANSWER_CAP_CHARS, CALLS_FILE, CALLS_MAX_BYTES, CALLS_MAX_CALLS, CALLS_TEXT_FILE, CALLS_TEXT_MAX_BYTES, HEAD_CHARS, ITEM_TEXT_CHARS, WHY_CHARS, MODEL_LOG_VERSION, PROMPT_CAP_CHARS, answerText, boundDecision, boundItems, foldModelLogInto, headOf, newModelLogState, outcomeOfItems, SCRUB_MARGIN_CHARS, scrubBounded, scrubText, type CallDecision, type CallItem, type CallOutcome, type ModelCallRow, type ModelCallText, type ModelDecisionRow, type ModelLog, type ModelLogFullRow, type ModelLogRunRow, type ModelLogState, type ModelRoute, type Scrub, } from "./callLog"; export type ModelLogFiles = { calls: string; text: string }; export const modelLogFilesIn = (dir: string): ModelLogFiles => ({ calls: path.join(dir, CALLS_FILE), text: path.join(dir, CALLS_TEXT_FILE) }); // ─── The per-file queue ─── const QUEUE_KEY = Symbol.for("archilyzer.modelLog.queues"); function queues(): Map> { const g = globalThis as unknown as Record> | undefined>; return (g[QUEUE_KEY] ??= new Map()); } function enqueue(file: string, op: () => Promise): Promise { const q = queues(); const prev = q.get(file) ?? Promise.resolve(); const next = prev.then(op, op); const tail = next.then( () => undefined, () => undefined, ); q.set(file, tail); void tail.then(() => { if (q.get(file) === tail) q.delete(file); }); return next; } const compactJson = (v: unknown) => { try { return JSON.stringify(v) ?? ""; } catch { return String(v); } }; // The configured API key's redaction, resolved the first time a text is // actually redacted — inside a record, never per call: reading the key is a // stat and a file read when it lives in a key file, and a call made with no // log open must not pay for it. export function lazyKeyRedactor(cfg: LlmConfig["anthropic"] | undefined): (s: string) => string { let r: ((s: string) => string) | null = null; return (s) => (r ??= keyRedactor(cfg))(s); } // ─── The writer ─── // The secrets and roots every record of this process is scrubbed of: the // editor's WORKER_TOKEN, an API key and every other variable of the // environment named like a credential (…TOKEN, …KEY, …SECRET, …PASSWORD, // …COOKIE, …AUTH), the // home directory, the checkout. const SECRET_ENV_NAME = /(?:^|_)(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|COOKIES?|AUTH)$/i; export function processScrub(extraRoots: readonly string[] = []): Scrub { const env = process.env; // A credential by its name only when it reads like one (16 characters, no // space): a short or worded value would take ordinary words out of a prompt. const named = Object.entries(env) .filter(([k, v]) => SECRET_ENV_NAME.test(k) && !!v && v.trim().length >= 16 && !/\s/.test(v.trim())) .map(([, v]) => v); const secrets = [...new Set([env.WORKER_TOKEN, env.ANTHROPIC_API_KEY, ...named].filter((s): s is string => !!s && s.trim().length >= 8).map((s) => s.trim()))] // A value that is a path (a key FILE) is not a secret; the roots take paths. .filter((s) => !s.startsWith("/")) .sort((a, b) => b.length - a.length); const roots = [os.homedir(), process.cwd(), ...extraRoots].filter((r) => !!r && r !== "/"); return { secrets, roots }; } // A failed call's message may name the host it was sent to (ollama's base // URL): an error keeps its words, never an address. const URL_IN_ERROR = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>()]+/gi; // … nor the address a connection was refused at (ECONNREFUSED 10.0.0.5:11434). const ADDRESS_IN_ERROR = /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b|\[[0-9a-f:]*:[0-9a-f:]+\](?::\d+)?|(? s.replace(URL_IN_ERROR, "").replace(ADDRESS_IN_ERROR, ""); // A text whose scrubbed length is this much under its raw length was cut // before the scrub (a scrub alone shortens by less than a margin). const SCRUB_SLACK = SCRUB_MARGIN_CHARS; // Items past what a row keeps are not scrubbed at all (MAX_ITEMS = 40). const MAX_RECORD_ITEMS = 64; export type ModelCallEntry = { phase?: string; label?: string; model: string; route: ModelRoute; // The text sent: the system prompt and the rest (the user turn, an agent // turn's new messages). Never a header, a key or a URL. system?: string; prompt: string; answer: unknown; seconds: number; tokensIn?: number; tokensOut?: number; error?: string; decision?: CallDecision; items?: CallItem[]; // One call's own redaction (the API client's key), on top of the writer's. redact?: (s: string) => string; }; // What a caller holds to say, once code has used an answer, what it did. // Handed to structuredAnswer as `call.slot`; a no-op when nothing recorded. export class CallSlot { #writer: ModelLogWriter | null = null; #id: Promise | null = null; // The call's own redaction (the API client's key): what code says about the // answer afterwards is scrubbed of it as the call was. #redact: ((s: string) => string) | undefined; bind(writer: ModelLogWriter, id: Promise, redact?: (s: string) => string): void { this.#writer = writer; this.#id = id; this.#redact = redact; } get recorded(): boolean { return !!this.#writer; } // The call's decision (and its items'). Items alone: the decision is what // they add up to. decide(outcome: CallOutcome, why: string, items?: CallItem[]): void { if (!this.#writer || !this.#id) return; this.#writer.decide(this.#id, { outcome, why }, items, this.#redact); } items(items: CallItem[]): void { if (!this.#writer || !this.#id || !items.length) return; this.#writer.decide(this.#id, null, items, this.#redact); } } export class ModelLogWriter { readonly files: ModelLogFiles; readonly task: string; readonly jobId: string | undefined; readonly model: string | undefined; readonly scrub: Scrub; // The article and iteration the log is of, when it is an iteration's. readonly where: { article: string; iteration: number } | undefined; private readonly now: () => Date; private readonly log: ((line: string) => void) | undefined; private run: number | null = null; private seq = 0; private failed = false; private textFull = false; private readonly textMaxBytes: number; // The log's own cap: the calls it held when this run began plus this run's, // and its size. Full: one `full` row, then nothing more from this writer. private held = 0; private full = false; private readonly maxCalls: number; private readonly maxBytes: number; private pending: Promise = Promise.resolve(); constructor(o: { files: ModelLogFiles; task: string; jobId?: string; model?: string; where?: { article: string; iteration: number }; scrub?: Scrub; now?: () => Date; log?: (line: string) => void; textMaxBytes?: number; maxCalls?: number; maxBytes?: number }) { this.files = o.files; this.textMaxBytes = o.textMaxBytes ?? CALLS_TEXT_MAX_BYTES; this.maxCalls = o.maxCalls ?? CALLS_MAX_CALLS; this.maxBytes = o.maxBytes ?? CALLS_MAX_BYTES; this.where = o.where; this.task = o.task; this.jobId = o.jobId; this.model = o.model; this.scrub = o.scrub ?? processScrub(); this.now = o.now ?? (() => new Date()); this.log = o.log; } private fail(err: unknown) { if (!this.failed) this.log?.(`model log not kept: ${(err as Error)?.message ?? String(err)}`); this.failed = true; } private queue(op: () => Promise): Promise { const p = enqueue(this.files.calls, op).catch((err) => { this.fail(err); return null; }); this.pending = Promise.all([this.pending, p]); return p; } // This run's number, allocated (with its `run` row) on the first write. private async ensureRun(): Promise { if (this.run !== null) return this.run; const before = await readModelLog(this.files); const max = before.runs.reduce((m, r) => Math.max(m, r.run), 0); this.run = max + 1; this.held = before.calls.length; this.full = !!before.full; const row: ModelLogRunRow = { v: MODEL_LOG_VERSION, t: "run", run: this.run, at: this.now().toISOString(), task: this.task, ...(this.jobId ? { jobId: this.jobId } : {}), ...(this.model ? { model: this.model } : {}) }; await mkdir(path.dirname(this.files.calls), { recursive: true }); await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); return this.run; } // Starts the run now (its `run` row), so a page sees the run before its first call. start(): Promise { return this.queue(() => this.ensureRun()); } // True once the log is at its cap; the first time, the `full` row is // written and the run is told. private async atCap(run: number): Promise { if (this.full) return true; const bytes = await stat(this.files.calls).then( (st) => st.size, () => 0, ); if (this.held < this.maxCalls && bytes < this.maxBytes) return false; this.full = true; const row: ModelLogFullRow = { v: MODEL_LOG_VERSION, t: "full", at: this.now().toISOString(), run, calls: this.held, bytes }; await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); this.log?.(`model log: full (${this.held.toLocaleString("en-US")} calls, ${Math.round(bytes / 1e6)} MB) — later calls are not recorded`); return true; } record(e: ModelCallEntry): Promise { const at = this.now().toISOString(); return this.queue(async () => { const run = await this.ensureRun(); if (await this.atCap(run)) return null; const id = `${run}.${++this.seq}`; const clean = (s: string) => { const r = e.redact ? e.redact(s) : s; return scrubText(r, this.scrub); }; // Each text is cut to what is kept of it (and a margin) BEFORE the // scrub: a megabyte of prompt is never scrubbed to keep 40,000 characters. const bounded = (s: string, cap: number) => scrubBounded(s, cap, clean); const rawSystem = e.system ?? ""; const rawPrompt = e.prompt ?? ""; const rawAnswer = answerText(e.answer); const system = bounded(rawSystem, PROMPT_CAP_CHARS); const prompt = bounded(rawPrompt, PROMPT_CAP_CHARS); const answer = bounded(rawAnswer, ANSWER_CAP_CHARS); const boundItem = (i: CallItem) => ({ ...i, text: bounded(String(i.text ?? ""), ITEM_TEXT_CHARS), why: bounded(String(i.why ?? ""), WHY_CHARS) }); const items = boundItems(e.items?.slice(0, MAX_RECORD_ITEMS).map(boundItem)); const decision = e.decision ? boundDecision({ ...e.decision, why: bounded(String(e.decision.why ?? ""), WHY_CHARS) }) : items ? { outcome: outcomeOfItems(items), why: "" } : { outcome: "n/a" as const, why: e.error ? "the call failed" : "" }; const row: ModelCallRow = { v: MODEL_LOG_VERSION, t: "call", id, run, at, task: this.task, phase: e.phase || this.task, ...(e.label ? { label: bounded(e.label, 120).slice(0, 120) } : {}), model: e.model, route: e.route, // What was sent and what came back, in characters (before the scrub). promptChars: rawSystem.length + rawPrompt.length, promptHead: headOf(prompt || system), answerChars: rawAnswer.length, // A structured answer's head is its compact JSON (the whole text keeps it laid out). answerHead: headOf(typeof e.answer === "string" || e.answer === undefined ? answer : bounded(compactJson(e.answer), HEAD_CHARS * 2)), seconds: Math.round((Number.isFinite(e.seconds) ? e.seconds : 0) * 10) / 10, ...(typeof e.tokensIn === "number" ? { tokensIn: e.tokensIn } : {}), ...(typeof e.tokensOut === "number" ? { tokensOut: e.tokensOut } : {}), ...(e.error ? { error: scrubErrorUrls(bounded(e.error, 600)).slice(0, 600) } : {}), decision, ...(items ? { items } : {}), }; // The prompt cap is on the system and the rest together, the system first. const sys = system.slice(0, PROMPT_CAP_CHARS); const rest = prompt.slice(0, Math.max(0, PROMPT_CAP_CHARS - sys.length)); const keptAnswer = answer.slice(0, ANSWER_CAP_CHARS); const text: ModelCallText = { v: MODEL_LOG_VERSION, id, system: sys, prompt: rest, ...(sys.length < system.length || rest.length < prompt.length || system.length < rawSystem.length - SCRUB_SLACK || prompt.length < rawPrompt.length - SCRUB_SLACK ? { promptCut: true as const } : {}), answer: keptAnswer, ...(keptAnswer.length < answer.length || rawAnswer.length > ANSWER_CAP_CHARS + SCRUB_MARGIN_CHARS ? { answerCut: true as const } : {}), }; // The text first: a row the list shows has its text to expand — until // the text file is full (CALLS_TEXT_MAX_BYTES): then the row alone is // kept, and the panel says the call's text was not. const line = `${JSON.stringify(text)}\n`; const held = await stat(this.files.text).then( (st) => st.size, () => 0, ); if (held + Buffer.byteLength(line) <= this.textMaxBytes) await appendFile(this.files.text, line); else if (!this.textFull) { this.textFull = true; this.log?.(`model log: the calls' text is full (${Math.round(this.textMaxBytes / 1e6)} MB) — later calls keep their row, not their whole text`); } await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); this.held++; return id; }); } decide(id: Promise, decision: CallDecision | null, items?: CallItem[], redact?: (s: string) => string): void { const at = this.now().toISOString(); void this.queue(async () => { const call = await id; if (!call) return; // A full log takes nothing more, a decision included. if (this.full) return; const clean = (s: string) => scrubText(redact ? redact(s) : s, this.scrub); const bounded = (s: string, cap: number) => scrubBounded(String(s ?? ""), cap, clean); const b = boundItems(items?.slice(0, MAX_RECORD_ITEMS).map((i) => ({ ...i, text: bounded(i.text, ITEM_TEXT_CHARS), why: bounded(i.why, WHY_CHARS) }))); const row: ModelDecisionRow = { v: MODEL_LOG_VERSION, t: "decision", call, at, ...(decision ? { decision: boundDecision({ ...decision, why: bounded(decision.why, WHY_CHARS) }) } : {}), ...(b ? { items: b } : {}), }; await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); }); } // Every queued write, done (never rejects). async flush(): Promise { let seen: Promise | null = null; while (seen !== this.pending) { seen = this.pending; await seen.catch(() => {}); } } } // ─── The context ─── // A job's local calls, counted wherever they were recorded (its own log or an // iteration's inside it): what the usage ledger is told when the job ends. export type LocalCallTally = Map; // `onInner`: told where a nested log is (an iteration's, inside a job's own), // so the job can say where its calls went. export type InnerLogWhere = { article: string; iteration: number }; type Ctx = { writer: ModelLogWriter; tally?: LocalCallTally; onInner?: (where: InnerLogWhere) => void }; const ALS_KEY = Symbol.for("archilyzer.modelLog.context"); function storage(): AsyncLocalStorage { const g = globalThis as unknown as Record | undefined>; return (g[ALS_KEY] ??= new AsyncLocalStorage()); } // A nested log takes the call (the innermost wins); the tally is the outer one's. export function runWithModelLog(writer: ModelLogWriter | null, fn: () => T, o: { tally?: LocalCallTally; onInner?: (where: InnerLogWhere) => void } = {}): T { if (!writer) return fn(); const outer = storage().getStore(); const tally = o.tally ?? outer?.tally; if (outer?.onInner && writer.where) { try { outer.onInner(writer.where); } catch { // a pointer never stops the run } } return storage().run({ writer, ...(tally ? { tally } : {}), ...(o.onInner ? { onInner: o.onInner } : {}) }, fn); } export function currentModelLog(): ModelLogWriter | null { return storage().getStore()?.writer ?? null; } // THE ONE RECORDING FUNCTION: every model call on every route comes here. // Nothing is recorded outside a run's log; `slot` (when given) is bound to the // call so the caller can say what code did with the answer. export function recordModelCall(e: ModelCallEntry, slot?: CallSlot): void { const ctx = storage().getStore(); const w = ctx?.writer; if (!w) return; if (ctx.tally && e.route === "local") { const key = `${e.model}\u0000${w.task}\u0000${w.where?.article ?? ""}\u0000${w.where?.iteration ?? 0}`; const t = ctx.tally.get(key) ?? { model: e.model, task: w.task, article: w.where?.article ?? "", iteration: w.where?.iteration ?? 0, calls: 0, tokensIn: 0, tokensOut: 0 }; t.calls++; t.tokensIn += e.tokensIn ?? 0; t.tokensOut += e.tokensOut ?? 0; ctx.tally.set(key, t); } try { const id = w.record(e); slot?.bind(w, id, e.redact); } catch { // a record never stops the run } } // A Claude Code session's answer (the `code` route): the request the plan // handed it, and what it posted. Its seconds are the session's, unknown here. // `llm`: the run's config, whose API key (if any) is scrubbed from it too. export function recordSessionAnswer(e: { phase?: string; label?: string; system: string; prompt: string; answer: unknown; llm?: LlmConfig }, slot?: CallSlot): void { const { llm, ...rest } = e; recordModelCall({ ...rest, label: e.label ?? "a Claude Code session's answer", model: "claude-code", route: "claude-code", seconds: 0, redact: lazyKeyRedactor(llm?.anthropic) }, slot); } // ─── Reading ─── // A poll reads only what was appended: per file, the fold so far and the // offset it reached (whole lines only — a line still being written waits for // the next read). A file that shrank or was replaced is read again from its // start. At most READ_CACHE_FILES logs are held (each at most CALLS_MAX_BYTES // of rows); the oldest read goes first. type ReadState = { ino: number; born: number; offset: number; state: ModelLogState }; const READ_CACHE_FILES = 24; const READ_KEY = Symbol.for("archilyzer.modelLog.readers"); function readers(): Map { const g = globalThis as unknown as Record | undefined>; return (g[READ_KEY] ??= new Map()); } const snapshot = (st: ModelLogState): ModelLog => ({ runs: [...st.runs], calls: [...st.calls], ...(st.full ? { full: true } : {}) }); export async function readModelLog(files: ModelLogFiles): Promise { const cache = readers(); const file = files.calls; // One read of a file at a time, in this process: two polls never fold the same bytes twice. return enqueue(`read:${file}`, async () => { const st = await stat(file).catch(() => null); if (!st) { cache.delete(file); return { runs: [], calls: [] }; } let entry = cache.get(file); if (!entry || entry.ino !== st.ino || entry.born !== st.birthtimeMs || st.size < entry.offset) entry = { ino: st.ino, born: st.birthtimeMs, offset: 0, state: newModelLogState() }; if (st.size > entry.offset) { const fh = await open(file, "r"); try { const want = st.size - entry.offset; const buf = Buffer.allocUnsafe(want); let got = 0; while (got < want) { const { bytesRead } = await fh.read(buf, got, want - got, entry.offset + got); if (!bytesRead) break; got += bytesRead; } const end = buf.subarray(0, got).lastIndexOf(0x0a); if (end >= 0) { foldModelLogInto(entry.state, buf.subarray(0, end).toString("utf8")); entry.offset += end + 1; } } finally { await fh.close(); } } cache.delete(file); cache.set(file, entry); // most recently read last while (cache.size > READ_CACHE_FILES) cache.delete(cache.keys().next().value!); return snapshot(entry.state); }); } // One call's whole text, read line by line until its id (never the whole file // into memory at once); null when it has none. export async function readModelCallText(files: ModelLogFiles, id: string): Promise { let stream: ReturnType; try { stream = createReadStream(files.text, { encoding: "utf8" }); } catch { return null; } const want = `"id":${JSON.stringify(id)}`; try { const rl = createInterface({ input: stream, crlfDelay: Infinity }); for await (const line of rl) { if (!line.includes(want)) continue; try { const r = JSON.parse(line) as ModelCallText; if (r && r.v === MODEL_LOG_VERSION && r.id === id) { rl.close(); stream.destroy(); return r; } } catch { // a torn line } } } catch (err) { if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; throw err; } finally { stream.destroy(); } return null; }