Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 7e1410ceae0d2d15ac8a90de503153b596e47380
parent c37861b682b206da3561fdfea0ab9aae98aa6bae
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 07:06:06 -0500

common: the model log keeps the text sent to the model and nothing else -- no key, no WORKER_TOKEN, no host path (demo epic D3, item 4)

Every record is scrubbed before it is written: the run's API key (the
client's own key, redacted on every route -- a local prompt too -- and a
Claude Code session's answer through its run's config), the editor's
WORKER_TOKEN and ANTHROPIC_API_KEY from the environment, and absolute paths
under the home directory, the checkout and the store's roots (each marked
[secret] / [redacted] / <path>, never dropped silently). The key never
leaves the client: AnthropicClient.redactText and keyRedactor hand out a
redaction, not the key.

callLogPrivacy.test.ts injects a fake key, a fake WORKER_TOKEN, an
Authorization header and host paths into the prompt and the answer of every
route (local structured, extractor and agent; API structured, extractor and
agent; a Claude Code session) and finds none in calls.jsonl or
calls-text.jsonl, nor the model host's URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
Mcommon/controller/jobModelLog.ts | 3++-
Mcommon/lib/llm/agent.ts | 5+++--
Mcommon/lib/llm/anthropic.ts | 20++++++++++++++++++++
Mcommon/lib/llm/callLog-server.ts | 34+++++++++++++++++++++++++++++-----
Mcommon/lib/llm/callLog.test.ts | 4++--
Mcommon/lib/llm/callLog.ts | 23+++++++++++++++++++++++
Acommon/lib/llm/callLogPrivacy.test.ts | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/llm/structured.ts | 8++++++--
Mcommon/lib/report/draft/tasks/clipsSuggest.ts | 2+-
Mcommon/lib/report/draft/tasks/llmText.ts | 8+++++++-
Mcommon/lib/report/draft/tasks/proposeGroups.ts | 2+-
Mcommon/lib/report/draft/tasks/run.ts | 3++-
Mcommon/lib/report/draft/tasks/videoAssist.ts | 2+-
13 files changed, 206 insertions(+), 17 deletions(-)

diff --git a/common/controller/jobModelLog.ts b/common/controller/jobModelLog.ts @@ -10,7 +10,7 @@ // SERVER-ONLY. import path from "node:path"; -import { ModelLogWriter, modelLogFilesIn, runWithModelLog, type LocalCallTally, type ModelLogFiles } from "../lib/llm/callLog-server"; +import { ModelLogWriter, modelLogFilesIn, processScrub, runWithModelLog, type LocalCallTally, type ModelLogFiles } from "../lib/llm/callLog-server"; import { appendGenerationUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import type { Paths } from "../lib/paths"; @@ -37,6 +37,7 @@ export function modelLogged<R>(o: { paths: UsagePaths; task: string; model?: str task: o.task, jobId: ctx.jobId, ...(o.model ? { model: o.model } : {}), + scrub: processScrub([path.dirname(o.paths.generationUsageFile)]), log: onLog, }); const tally: LocalCallTally = new Map(); diff --git a/common/lib/llm/agent.ts b/common/lib/llm/agent.ts @@ -20,6 +20,7 @@ import { CancelledError, cacheControl, isStrictModel, + keyRedactor, textOf, toolUsesOf, type ContentBlock, @@ -358,7 +359,7 @@ async function runClaude(o: AgentOptions): Promise<AgentResult> { const before = o.meter.usd; const t0 = Date.now(); const turnRecord = (answer: string, extra: { tokensIn?: number; tokensOut?: number; error?: string }) => - recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "api", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra }); + recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "api", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra, redact: (s) => client.redactText(s) }); try { res = await client.messages(body, { meter: o.meter, signal: o.signal }); } catch (err) { @@ -478,7 +479,7 @@ async function runLocal(o: AgentOptions): Promise<AgentResult> { const fresh = messagesText(messages.slice(turn === 0 ? 1 : recorded)); const t0 = Date.now(); const turnRecord = (answer: string, extra: { tokensIn?: number; tokensOut?: number; error?: string }) => - recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "local", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra }); + recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "local", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra, redact: keyRedactor(o.llm.anthropic) }); try { reply = await ollamaChat(cfg, { model: o.model, messages, tools, signal: o.signal }); } catch (err) { diff --git a/common/lib/llm/anthropic.ts b/common/lib/llm/anthropic.ts @@ -144,6 +144,20 @@ export function redact(text: string, key: string | undefined): string { return out; } +// A text with the configured key taken out, whatever route the text went to +// (the model log's records: a local prompt is scrubbed of it too). No key +// configured, or one that does not read: the text as it is. +export function keyRedactor(cfg: AnthropicConfig | undefined): (text: string) => string { + if (!cfg) return (t) => t; + let key: string | undefined; + try { + key = readApiKey(cfg); + } catch { + key = undefined; + } + return (t) => redact(t, key); +} + // ─── Errors ─── export class AnthropicError extends Error { @@ -249,6 +263,12 @@ export class AnthropicClient { return this.describe(); } + // A text with this client's key taken out (the model log's records): the + // key itself never leaves the client. + redactText(text: string): string { + return redact(text, this.#key); + } + private key(): string { this.#key ??= readApiKey(this.#cfg); return this.#key; diff --git a/common/lib/llm/callLog-server.ts b/common/lib/llm/callLog-server.ts @@ -18,8 +18,11 @@ import { AsyncLocalStorage } from "node:async_hooks"; import { appendFile, mkdir, readFile } 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, @@ -32,6 +35,7 @@ import { foldModelLog, headOf, outcomeOfItems, + scrubText, type CallDecision, type CallItem, type CallOutcome, @@ -41,6 +45,7 @@ import { type ModelLog, type ModelLogRunRow, type ModelRoute, + type Scrub, } from "./callLog"; export type ModelLogFiles = { calls: string; text: string }; @@ -80,6 +85,16 @@ const compactJson = (v: unknown) => { // ─── The writer ─── +// The secrets and roots every record of this process is scrubbed of: the +// editor's WORKER_TOKEN and an API key in the environment, the home directory, +// the checkout. +export function processScrub(extraRoots: readonly string[] = []): Scrub { + const env = process.env; + const secrets = [env.WORKER_TOKEN, env.ANTHROPIC_API_KEY].filter((s): s is string => !!s && s.trim().length >= 8).map((s) => s.trim()); + const roots = [os.homedir(), process.cwd(), ...extraRoots].filter((r) => !!r && r !== "/"); + return { secrets, roots }; +} + export type ModelCallEntry = { phase?: string; label?: string; @@ -96,6 +111,8 @@ export type ModelCallEntry = { 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. @@ -127,6 +144,7 @@ export class ModelLogWriter { 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; @@ -136,12 +154,13 @@ export class ModelLogWriter { private failed = false; private pending: Promise<unknown> = Promise.resolve(); - constructor(o: { files: ModelLogFiles; task: string; jobId?: string; model?: string; where?: { article: string; iteration: number }; now?: () => Date; log?: (line: string) => void }) { + constructor(o: { files: ModelLogFiles; task: string; jobId?: string; model?: string; where?: { article: string; iteration: number }; scrub?: Scrub; now?: () => Date; log?: (line: string) => void }) { this.files = o.files; 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; } @@ -182,7 +201,10 @@ export class ModelLogWriter { return this.queue(async () => { const run = await this.ensureRun(); const id = `${run}.${++this.seq}`; - const clean = (s: string) => s; + const clean = (s: string) => { + const r = e.redact ? e.redact(s) : s; + return scrubText(r, this.scrub); + }; const system = clean(e.system ?? ""); const prompt = clean(e.prompt ?? ""); const answer = clean(answerText(e.answer)); @@ -235,7 +257,7 @@ export class ModelLogWriter { void this.queue(async () => { const call = await id; if (!call) return; - const clean = (s: string) => s; + const clean = (s: string) => scrubText(s, this.scrub); const b = boundItems(items?.map((i) => ({ ...i, text: clean(i.text), why: clean(i.why) }))); const row: ModelDecisionRow = { v: MODEL_LOG_VERSION, @@ -308,8 +330,10 @@ export function recordModelCall(e: ModelCallEntry, slot?: CallSlot): void { // 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. -export function recordSessionAnswer(e: { phase?: string; label?: string; system: string; prompt: string; answer: unknown }, slot?: CallSlot): void { - recordModelCall({ ...e, label: e.label ?? "a Claude Code session's answer", model: "claude-code", route: "claude-code", seconds: 0 }, slot); +// `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: keyRedactor(llm?.anthropic) }, slot); } // ─── Reading ─── diff --git a/common/lib/llm/callLog.test.ts b/common/lib/llm/callLog.test.ts @@ -32,7 +32,7 @@ const schema = { type: "object", properties: { terms: { type: "array", items: { async function tmpLog(task = "sweep") { const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); const files = modelLogFilesIn(dir); - const writer = new ModelLogWriter({ files, task, jobId: "job-1", model: "qwen3:8b" }); + const writer = new ModelLogWriter({ files, task, jobId: "job-1", model: "qwen3:8b", scrub: {} }); return { dir, files, writer, done: () => rm(dir, { recursive: true, force: true }) }; } @@ -65,7 +65,7 @@ test("the rows: a run row first, then each call; a decision folded into its call assert.match(text!.answer, /"items"/); assert.equal(await readModelCallText(t.files, "9.9"), null); // A second writer on the same files is run 2. - const w2 = new ModelLogWriter({ files: t.files, task: "narrate" }); + const w2 = new ModelLogWriter({ files: t.files, task: "narrate", scrub: {} }); await runWithModelLog(w2, async () => recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 0 })); await w2.flush(); const again = await readModelLog(t.files); diff --git a/common/lib/llm/callLog.ts b/common/lib/llm/callLog.ts @@ -25,6 +25,11 @@ // "meaning-check") and its `decision` — through structuredAnswer's `call` // option and its CallSlot (callLog-server.ts), never a new row kind. // +// PRIVACY. `system` and `prompt` are the text sent to the model and nothing +// else (no header, no key, no URL of the model's host); every text is scrubbed +// of the run's secrets (the API key, the editor's WORKER_TOKEN) and of host +// paths before it is written (`scrubText`). +// // A reader skips a line that does not parse and a row of an unknown version; // a later version adds fields, never renames one. @@ -104,6 +109,24 @@ export function headOf(text: string): string { return more ? `${head}…` : head; } +// What a scrub removes: exact secret values, and absolute paths under the +// host's own roots (the home directory, the checkout, the data roots). +export type Scrub = { secrets?: readonly string[]; roots?: readonly string[] }; + +const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +// A home directory on any of the usual systems, even when it is not ours. +const HOME_PATH = /(?:\/home\/|\/Users\/|\/root\/|\/run\/media\/|\/mnt\/|\/media\/)[^\s"'`<>()[\]{},;]*/g; + +export function scrubText(text: string, s: Scrub = {}): string { + let out = text; + for (const secret of s.secrets ?? []) { + if (secret && secret.length >= 8) out = out.split(secret).join("[secret]"); + } + const roots = [...new Set((s.roots ?? []).filter((r) => r && r.length > 1 && r.startsWith("/")).map((r) => r.replace(/\/+$/, "")))].sort((a, b) => b.length - a.length); + for (const r of roots) out = out.replace(new RegExp(`${escapeRe(r)}(?:/[^\\s"'\`<>()[\\]{},;]*)?`, "g"), "<path>"); + return out.replace(HOME_PATH, "<path>"); +} + // An answer as the record keeps it: a string as it is, anything else as JSON. export function answerText(answer: unknown): string { if (typeof answer === "string") return answer; diff --git a/common/lib/llm/callLogPrivacy.test.ts b/common/lib/llm/callLogPrivacy.test.ts @@ -0,0 +1,109 @@ +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, toolUseBlock, turn, type FakeAnthropic } from "../../testing/llm/fakeAnthropic.mjs"; +import { jsonReply, reply, startFakeOllama, type FakeOllama } from "../../testing/llm/fakeOllama.mjs"; +import { runAgent } from "./agent"; +import { scrubText } from "./callLog"; +import { ModelLogWriter, modelLogFilesIn, recordSessionAnswer, runWithModelLog } from "./callLog-server"; +import { Meter } from "./meter"; +import { structuredAnswer } from "./structured"; +import { plainAnswer } from "../report/draft/tasks/llmText"; + +// Run with: pnpm -C common exec tsx --test lib/llm/callLogPrivacy.test.ts +// +// THE MODEL LOG KEEPS THE TEXT SENT TO THE MODEL, AND NOTHING ELSE (demo epic +// D3, item 4): on every route a record holds no API key, no WORKER_TOKEN, no +// Authorization header's secret and no host path — even when the prompt +// itself carries them (a transcript can say anything). The secrets below are +// recognisable and injected into each prompt and answer to prove it. + +const TOKEN = "worker-token-0000-TEST-never-real"; +const HOST_PATH = path.join(os.homedir(), "Projects", "yt-dlp-transcript-browser", "transcripts", "reports", "a", "iteration.json"); +const POISON = `see ${HOST_PATH} and /home/someone/secret/file.txt; Authorization: Bearer ${TOKEN}; x-api-key: ${FAKE_KEY}`; +const schema = { type: "object", properties: { terms: { type: "array", items: { type: "string" } } }, required: ["terms"] }; + +let ol: FakeOllama; +let api: FakeAnthropic; +let saved: string | undefined; + +before(async () => { + saved = process.env.WORKER_TOKEN; + process.env.WORKER_TOKEN = TOKEN; + ol = await startFakeOllama({ turns: [jsonReply({ terms: [POISON] }), reply(POISON), reply("done")] }); + api = await startFakeAnthropic({ + turns: [turn([toolUseBlock("answer", { terms: [POISON] })]), textTurn(POISON), toolTurn("lookup", { q: POISON }), textTurn(`read: ${POISON}`)], + }); +}); + +after(async () => { + if (saved === undefined) delete process.env.WORKER_TOKEN; + else process.env.WORKER_TOKEN = saved; + await ol.close(); + await api.close(); +}); + +function assertClean(text: string, where: string) { + assert.ok(text.length > 0, `${where}: something was recorded`); + assert.ok(!text.includes(FAKE_KEY), `${where}: the API key`); + assert.ok(!text.includes(FAKE_KEY.slice(0, 16)), `${where}: a run of the API key`); + assert.ok(!text.includes(TOKEN), `${where}: the WORKER_TOKEN`); + assert.ok(!text.includes(os.homedir()), `${where}: the home directory`); + assert.ok(!text.includes("/home/someone"), `${where}: a host path`); + assert.ok(!text.includes(api.url) && !text.includes(ol.url), `${where}: the model host's URL`); +} + +test("every route's record holds no key, no WORKER_TOKEN and no host path", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-privacy-")); + try { + // An API config whose key is the fake's, read from the config's own env + // (never process.env): the client's redaction is what keeps it out. + const llm = { ollama: { baseUrl: ol.url }, anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY } } }; + const meter = new Meter(); + const routes: [string, () => Promise<unknown>][] = [ + ["local structured", () => structuredAnswer({ llm, model: "qwen3:8b", system: `System ${POISON}`, user: `User ${POISON}`, schema, meter })], + ["local extractor", () => plainAnswer({ llm, model: "qwen3:8b", system: "S", user: POISON, meter })], + ["local agent", () => runAgent({ llm, model: "qwen3:8b", system: POISON, user: POISON, meter, tools: [] })], + ["api structured", () => structuredAnswer({ llm, model: "claude-haiku-4-5", system: POISON, user: POISON, schema, meter })], + ["api extractor", () => plainAnswer({ llm, model: "claude-haiku-4-5", system: "S", user: POISON, meter })], + [ + "api agent", + () => + runAgent({ + llm, + model: "claude-haiku-4-5", + system: POISON, + user: POISON, + meter, + tools: [{ name: "lookup", description: "look", inputSchema: { type: "object", properties: { q: { type: "string" } } }, run: async () => `result ${POISON}` }], + }), + ], + ["claude-code", async () => recordSessionAnswer({ system: POISON, prompt: POISON, answer: { ops: [POISON] }, llm })], + ]; + for (const [name, call] of routes) { + const files = modelLogFilesIn(path.join(dir, name.replace(/\s+/g, "-"))); + // The process's scrub (WORKER_TOKEN from the environment, the home + // directory, the checkout), as every run's writer has it. + const w = new ModelLogWriter({ files, task: "sweep" }); + await runWithModelLog(w, call); + await w.flush(); + assertClean(await readFile(files.calls, "utf8"), `${name}: calls.jsonl`); + assertClean(await readFile(files.text, "utf8"), `${name}: calls-text.jsonl`); + // What was scrubbed is said, never dropped silently. + assert.match(await readFile(files.text, "utf8"), /\[secret\]|\[redacted\]/, `${name}: the secret is marked`); + assert.match(await readFile(files.text, "utf8"), /<path>/, `${name}: the path is marked`); + } + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("scrubText: secrets and roots out, words of a transcript untouched", () => { + const s = { secrets: ["abcdefgh-secret"], roots: ["/srv/archive"] }; + assert.equal(scrubText("he said abcdefgh-secret at /srv/archive/x.json today", s), "he said [secret] at <path> today"); + assert.equal(scrubText("a short one: abc", { secrets: ["abc"] }), "a short one: abc", "a secret under 8 characters is not a secret"); + assert.equal(scrubText("the 5/10 split and and/or rules", s), "the 5/10 split and and/or rules"); + assert.equal(scrubText("files in /home/ann/.config/x", {}), "files in <path>"); +}); diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -14,6 +14,7 @@ import { AnthropicClient, AnthropicError, isStrictModel, + keyRedactor, toolUsesOf, type ContentBlock, type MessagesResponse, @@ -72,7 +73,7 @@ export type StructuredCallMeta = { phase?: string; label?: string; slot?: CallSl // What one structured answer cost, summed over its attempts, and the text it // last sent (the model log's record). -type Spent = { tokensIn: number; tokensOut: number; any: boolean; sent: string }; +type Spent = { tokensIn: number; tokensOut: number; any: boolean; sent: string; redact?: (s: string) => string }; const spend = (s: Spent, u: Usage | undefined) => { if (!u) return; const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0); @@ -83,7 +84,7 @@ const spend = (s: Spent, u: Usage | undefined) => { export async function structuredAnswer<T>(o: Opts): Promise<T> { const route = providerOf(o.model); - const spent: Spent = { tokensIn: 0, tokensOut: 0, any: false, sent: o.user }; + const spent: Spent = { tokensIn: 0, tokensOut: 0, any: false, sent: o.user, redact: keyRedactor(o.llm.anthropic) }; const t0 = Date.now(); const images = o.images?.length ? `\n\n[${o.images.length} image${o.images.length === 1 ? "" : "s"} sent with this prompt]` : ""; const record = (answer: unknown, error?: unknown) => @@ -99,6 +100,7 @@ export async function structuredAnswer<T>(o: Opts): Promise<T> { seconds: (Date.now() - t0) / 1000, ...(spent.any ? { tokensIn: spent.tokensIn, tokensOut: spent.tokensOut } : {}), ...(error !== undefined ? { error: (error as Error)?.message ?? String(error) } : {}), + ...(spent.redact ? { redact: spent.redact } : {}), }, o.call?.slot, ); @@ -114,6 +116,8 @@ export async function structuredAnswer<T>(o: Opts): Promise<T> { async function claudeAnswer<T>(o: Opts, spent: Spent): Promise<T> { const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); + const configured = spent.redact; + spent.redact = (s) => client.redactText(configured ? configured(s) : s); const strict = isStrictModel(o.model); try { return await claudeTry<T>(client, o, strict, spent); diff --git a/common/lib/report/draft/tasks/clipsSuggest.ts b/common/lib/report/draft/tasks/clipsSuggest.ts @@ -205,7 +205,7 @@ export async function runClipsSuggest( if (input.answers !== undefined) { // The `code` route: a Claude Code session's answer, read as a model's is. const all = suggestPrompt(items); - recordSessionAnswer({ phase: "labels", system: all.system, prompt: all.user, answer: input.answers }); + recordSessionAnswer({ phase: "labels", system: all.system, prompt: all.user, answer: input.answers, llm: deps.llm }); const r = parseSuggestAnswer(input.answers, items.map((i) => i.id)); if (!r.ok) throw new ClipsSuggestRefusal(`the session's answers are refused: ${r.error}`); fresh.push(...r.items); diff --git a/common/lib/report/draft/tasks/llmText.ts b/common/lib/report/draft/tasks/llmText.ts @@ -7,6 +7,7 @@ import { AnthropicClient, anthropicConfigOf, isStrictModel, + keyRedactor, ollamaChat, ollamaConfigOf, promptCapOf, @@ -34,6 +35,7 @@ export async function plainAnswer(o: { }): Promise<string> { const route = providerOf(o.model); const t0 = Date.now(); + let redact: ((s: string) => string) | undefined = keyRedactor(o.llm.anthropic); const record = (answer: string, tokens: { tokensIn?: number; tokensOut?: number }, error?: unknown) => recordModelCall( { @@ -47,11 +49,13 @@ export async function plainAnswer(o: { seconds: (Date.now() - t0) / 1000, ...tokens, ...(error !== undefined ? { error: (error as Error)?.message ?? String(error) } : {}), + ...(redact ? { redact } : {}), }, o.call?.slot, ); try { - return await plainAnswerOn(o, record); + const configured = redact; + return await plainAnswerOn(o, record, (r) => (redact = (s) => r(configured ? configured(s) : s))); } catch (err) { record("", {}, err); throw err; @@ -61,9 +65,11 @@ export async function plainAnswer(o: { async function plainAnswerOn( o: Parameters<typeof plainAnswer>[0], record: (answer: string, tokens: { tokensIn?: number; tokensOut?: number }) => void, + setRedact: (r: (s: string) => string) => void, ): Promise<string> { if (providerOf(o.model) === "api") { const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); + setRedact((s) => client.redactText(s)); const res = await client.messages( { model: o.model, diff --git a/common/lib/report/draft/tasks/proposeGroups.ts b/common/lib/report/draft/tasks/proposeGroups.ts @@ -244,7 +244,7 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG log(`propose-groups ${input.project}: a Claude Code session's answer (prompt ${GROUPS_PROMPT_VERSION})`); raw = input.answers; const pr = groupsPrompt({ manifest, request, model: CODE_PRICED, llm: deps.llm }); - recordSessionAnswer({ phase: "groups", system: pr.system, prompt: pr.user, answer: raw }, slot); + recordSessionAnswer({ phase: "groups", system: pr.system, prompt: pr.user, answer: raw, llm: deps.llm }, slot); } else { const pr = groupsPrompt({ manifest, request, model: input.model, llm: deps.llm }); log(`propose-groups ${input.project} on ${input.model}: one ask, ~${pr.tokens} prompt tokens (prompt ${GROUPS_PROMPT_VERSION})`); diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts @@ -9,7 +9,7 @@ import { CancelledError, Meter, type ModelTally } from "../../../llm"; import { currentJobContext } from "../../../jobContext"; -import { ModelLogWriter, modelLogFilesIn, runWithModelLog } from "../../../llm/callLog-server"; +import { ModelLogWriter, modelLogFilesIn, processScrub, runWithModelLog } from "../../../llm/callLog-server"; import { addIterationUsage, appendIterationTurns, @@ -178,6 +178,7 @@ export async function runOnIteration( ...((o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId) ? { jobId: o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId } : {}), model: o.step?.model ?? o.trace?.model ?? it.model, where: { article, iteration: n }, + scrub: processScrub(Object.values(storePaths).filter((v): v is string => typeof v === "string")), now, log, }); diff --git a/common/lib/report/draft/tasks/videoAssist.ts b/common/lib/report/draft/tasks/videoAssist.ts @@ -231,7 +231,7 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD log(`video-assist ${input.project}: a Claude Code session's answer (prompt ${ASSIST_PROMPT_VERSION})`); raw = input.answers; const pr = assistPrompt({ manifest, request, scope, model: "claude-sonnet-5-5", llm: deps.llm }); - recordSessionAnswer({ phase: "assist", system: pr.system, prompt: pr.user, answer: raw }, slot); + recordSessionAnswer({ phase: "assist", system: pr.system, prompt: pr.user, answer: raw, llm: deps.llm }, slot); } else { const pr = assistPrompt({ manifest, request, scope, model: input.model, llm: deps.llm }); log(`video-assist ${input.project} on ${input.model} (${scope}): one ask, ~${pr.tokens} prompt tokens (prompt ${ASSIST_PROMPT_VERSION})`);