// THE GENERATION USAGE LEDGER (release 27, S6; D6) — one JSON line per model // per finished Claude API generation job, appended to `paths.generationUsageFile` // (editor state, never inside the corpus). The daily cap reads the day's total // from it; a job shows its own rows' sum. The digest's metered lane, which // kept costs only in log lines, is the precedent this replaces with a file. // // The day is UTC. A line that does not parse is skipped, never fatal. import { appendFile, mkdir, readFile } from "node:fs/promises"; import path from "node:path"; export type GenerationUsageRow = { at: string; day: string; jobId: string; article: string; iteration: number; task: string; model: string; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; usd: number; // "local": a local model's calls (demo epic D3) — cost 0, never counted // against the cap; the ledger is the proof a run stayed local. Absent: an // API row (every row before D3). route?: "api" | "local"; calls?: number; }; export const utcDay = (d: Date = new Date()) => d.toISOString().slice(0, 10); export async function appendGenerationUsage(file: string, rows: readonly GenerationUsageRow[]): Promise { if (!rows.length) return; await mkdir(path.dirname(file), { recursive: true }); await appendFile(file, rows.map((r) => `${JSON.stringify(r)}\n`).join("")); } export async function readGenerationUsage(file: string): Promise { let text: string; try { text = await readFile(file, "utf8"); } catch { return []; } const out: GenerationUsageRow[] = []; for (const line of text.split("\n")) { if (!line.trim()) continue; try { const r = JSON.parse(line) as GenerationUsageRow; if (r && typeof r.usd === "number" && typeof r.day === "string") out.push(r); } catch { // a torn line is skipped } } return out; } export const isLocalUsage = (r: Pick) => r.route === "local"; // The day's API spend: its total and how many jobs it took (local rows apart). export async function dayUsage(file: string, day: string = utcDay()): Promise<{ day: string; usd: number; jobs: number }> { const rows = (await readGenerationUsage(file)).filter((r) => r.day === day && !isLocalUsage(r)); const usd = Math.round(rows.reduce((s, r) => s + r.usd, 0) * 10_000) / 10_000; return { day, usd, jobs: new Set(rows.map((r) => r.jobId)).size }; } // The refusal for a job that would start past the daily cap, or null. export function dailyCapRefusal(day: { day: string; usd: number }, daily: number): string | null { if (!(daily > 0) || day.usd < daily) return null; return ( `the day's Claude API spend is $${day.usd.toFixed(2)} (${day.day}, UTC), at or past the $${daily.toFixed(2)} ` + "daily cap (settings.generation.caps.daily) — refused; it resets at midnight UTC" ); } // The models the day's generation called, on which route: what proves a run // stayed local (a local-only day lists no Claude model). export type UsageModel = { model: string; route: "api" | "local"; calls: number; jobs: number; inputTokens: number; outputTokens: number }; export async function dayModels(file: string, day: string = utcDay()): Promise { const rows = (await readGenerationUsage(file)).filter((r) => r.day === day); return usageModelsOf(rows); } export function usageModelsOf(rows: readonly GenerationUsageRow[]): UsageModel[] { const by = new Map }>(); for (const r of rows) { const route = isLocalUsage(r) ? "local" : "api"; const k = `${route}:${r.model}`; const m = by.get(k) ?? { model: r.model, route, calls: 0, jobs: 0, inputTokens: 0, outputTokens: 0, ids: new Set() }; m.calls += typeof r.calls === "number" ? r.calls : 0; m.inputTokens += r.inputTokens || 0; m.outputTokens += r.outputTokens || 0; m.ids.add(r.jobId); by.set(k, m); } return [...by.values()].map(({ ids, ...m }) => ({ ...m, jobs: ids.size })).sort((a, b) => a.route.localeCompare(b.route) || b.jobs - a.jobs || a.model.localeCompare(b.model)); } // The task a ledger row is of, as settings.generation names it (a frame // scan's job writes "frame-scan"). const TASK_ALIASES: Record = { "frame-scan": "frames" }; // Each task's last run in the ledger (demo epic D3, the settings page): the // newest job of the task, the models it called and on which route. export type LastRun = { at: string; jobId: string; models: string[]; route: "api" | "local" | "mixed" }; export function lastRunsByTask(rows: readonly GenerationUsageRow[]): Record { const jobs = new Map; routes: Set<"api" | "local"> }>(); for (const r of rows) { if (!r.jobId || !r.task) continue; const task = TASK_ALIASES[r.task] ?? r.task; const j = jobs.get(`${task}\u0000${r.jobId}`) ?? { task, at: r.at, models: new Set(), routes: new Set<"api" | "local">() }; j.models.add(r.model); j.routes.add(isLocalUsage(r) ? "local" : "api"); if (r.at > j.at) j.at = r.at; jobs.set(`${task}\u0000${r.jobId}`, j); } const out: Record = {}; for (const [key, j] of jobs) { const jobId = key.slice(key.indexOf("\u0000") + 1); if (out[j.task] && out[j.task]!.at >= j.at) continue; out[j.task] = { at: j.at, jobId, models: [...j.models].sort(), route: j.routes.size > 1 ? "mixed" : [...j.routes][0]! }; } return out; }