// A GENERATION JOB'S MODEL LOG when it has no iteration (demo epic D3; the // shape is lib/llm/callLog.ts): a verdict proposal, a frame scan, the clip // finder, the video assistant, claim groups, a triage, the verdict bench, a // learning pass. Its calls go to `/calls//` (beside // the usage ledger: editor state, never the corpus). A job over an iteration // records into the iteration's own files instead (tasks/run.ts opens that // log inside this one, and the inner one wins); this one stays empty and // is never created; `where.json` there points at the iteration instead, so // the job's page can find its calls (`locateJobModelLog`). // // SERVER-ONLY. import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { iterationDir } from "../lib/report/iterations"; import { ModelLogWriter, modelLogFilesIn, processScrub, readModelLog, runWithModelLog, type InnerLogWhere, type LocalCallTally, type ModelLogFiles } from "../lib/llm/callLog-server"; import { appendGenerationUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import type { Paths } from "../lib/paths"; import { isReportId } from "../lib/report/schema"; type UsagePaths = Pick; export function jobModelLogDir(paths: UsagePaths, jobId: string): string { if (!/^[A-Za-z0-9._-]+$/.test(jobId) || /^\.+$/.test(jobId)) throw new Error(`not a job id: ${JSON.stringify(jobId)}`); return path.join(path.dirname(paths.generationUsageFile), "calls", jobId); } export function jobModelLogFiles(paths: UsagePaths, jobId: string): ModelLogFiles { return modelLogFilesIn(jobModelLogDir(paths, jobId)); } export const WHERE_FILE = "where.json"; type JobFn = (onLog: (line: string) => void, signal: AbortSignal, setProgress: any, ctx: { jobId: string }) => Promise; // The job's `fn`, run inside its own model log; when it ends, its local calls // go to the usage ledger (route "local", cost 0) — API spend is recorded by // each job as before, never here. export function modelLogged(o: { paths: UsagePaths; task: string; model?: string }, fn: JobFn): JobFn { return async (onLog, signal, setProgress, ctx) => { const writer = new ModelLogWriter({ files: jobModelLogFiles(o.paths, ctx.jobId), 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(); const dir = jobModelLogDir(o.paths, ctx.jobId); let pointed: Promise | null = null; const onInner = (where: InnerLogWhere) => { pointed ??= mkdir(dir, { recursive: true }) .then(() => writeFile(path.join(dir, WHERE_FILE), `${JSON.stringify({ v: 1, article: where.article, n: where.iteration })}\n`)) .catch((e) => onLog(`model log pointer not kept: ${(e as Error).message}`)); }; try { return await runWithModelLog(writer, () => fn(onLog, signal, setProgress, ctx), { tally, onInner }); } finally { await writer.flush(); await pointed; await appendLocalUsage(o.paths, ctx.jobId, tally).catch((e) => onLog(`local usage not recorded: ${(e as Error).message}`)); } }; } export async function appendLocalUsage(paths: UsagePaths, jobId: string, tally: LocalCallTally, now: Date = new Date()): Promise { const rows: GenerationUsageRow[] = [...tally.values()].map((t) => ({ at: now.toISOString(), day: utcDay(now), jobId, article: t.article, iteration: t.iteration, task: t.task, model: t.model, inputTokens: t.tokensIn, outputTokens: t.tokensOut, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 0, route: "local", calls: t.calls, })); await appendGenerationUsage(paths.generationUsageFile, rows); } // Where a job's calls are: its own log, else the iteration its pointer names // (checked: that log holds a run of this job). Null: none recorded (yet). export async function locateJobModelLog( paths: UsagePaths & { articlesDir: string; exportIndexDir: string }, jobId: string, ): Promise<{ files: ModelLogFiles; where: { article: string; n: number } | null } | null> { const own = jobModelLogFiles(paths, jobId); if (await stat(own.calls).then(() => true, () => false)) return { files: own, where: null }; const raw = await readFile(path.join(jobModelLogDir(paths, jobId), WHERE_FILE), "utf8").catch(() => null); if (!raw) return null; let w: { article?: unknown; n?: unknown }; try { w = JSON.parse(raw); } catch { return null; } // The pointer names an article and an iteration, and nothing else: a name // that is not a report id never reaches a path. if (typeof w.article !== "string" || !isReportId(w.article) || !Number.isInteger(w.n) || (w.n as number) < 1) return null; const files = modelLogFilesIn(iterationDir(paths, w.article, w.n as number)); const log = await readModelLog(files); if (!log.runs.some((r) => r.jobId === jobId)) return null; return { files, where: { article: w.article, n: w.n as number } }; }