@use-aistack/cli 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/harness/cursor/worker.ts","../src/trace.ts","../src/harness/cursor/local.ts","../../pricing/src/table.ts","../../pricing/src/index.ts","../src/harness/shared/aggregate.ts","../src/harness/shared/window.ts","../src/harness/cursor/evidence.ts"],"sourcesContent":["// The Cursor history read, off the main thread (#420). See\n// `readLocalOffThread` in local.ts for why: cursor-history walks the whole\n// global database synchronously, and on the main thread that freezes the\n// terminal for as long as the walk takes.\n\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport { enableTrace } from \"../../trace.js\";\nimport { type CursorWorkerMessage, readLocalOnce } from \"./local.js\";\n\nconst port = parentPort;\nif (!port) throw new Error(\"cursor worker started without a parent port\");\nconst post = (message: CursorWorkerMessage) => port.postMessage(message);\nconst input = workerData as { root: string; before: string; trace: boolean };\nif (input.trace) enableTrace();\n\nreadLocalOnce(input.root, input.before, (files, total) =>\n\tpost({ kind: \"progress\", files, ...(total !== undefined ? { total } : {}) }),\n).then(\n\t(read) => post({ kind: \"result\", read }),\n\t() => post({ kind: \"error\" }),\n);\n","// Verbose diagnostics for a sync that looks stuck.\n//\n// The interactive spinner repaints on a timer, so a phase that blocks the event\n// loop (a synchronous SQLite walk, a large transcript parse) leaves the LAST\n// message on screen and reads as a hang at the wrong step. A user who reports\n// \"it hangs at X\" is then pointing at the phase that finished. This sink prints\n// every phase as it starts, with the seconds since the command began, so the\n// report names the phase that is actually running and how long it took.\n//\n// Enabled by `sync --verbose` or `AISTACK_DEBUG=1`. Every line goes to stderr,\n// so the MCP server's stdout protocol and a piped summary stay clean. Nothing\n// here prints a path, a prompt, or a database value: counts and durations only.\n\nlet sink: ((line: string) => void) | null = null;\nlet startedAtMs = 0;\n\nconst stderrSink = (line: string) => {\n\tprocess.stderr.write(`${line}\\n`);\n};\n\n/** True when the environment asks for diagnostics without a flag. */\nexport function traceRequestedByEnv(env = process.env): boolean {\n\tconst value = env.AISTACK_DEBUG?.trim().toLowerCase();\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\nexport function enableTrace(\n\twrite: (line: string) => void = stderrSink,\n\tnow: () => number = () => performance.now(),\n): void {\n\tsink = write;\n\tstartedAtMs = now();\n}\n\nexport function disableTrace(): void {\n\tsink = null;\n}\n\nexport function traceEnabled(): boolean {\n\treturn sink !== null;\n}\n\nfunction elapsedLabel(): string {\n\tconst seconds = (performance.now() - startedAtMs) / 1000;\n\treturn `+${seconds.toFixed(seconds < 10 ? 2 : 1)}s`;\n}\n\n/** One diagnostic line. A no-op unless tracing is on, so callers never guard. */\nexport function trace(message: string): void {\n\tif (!sink) return;\n\tsink(`[aistack ${elapsedLabel().padStart(7)}] ${message}`);\n}\n\n/**\n * Time one step. Returns a function that prints `label · N ms` plus an optional\n * result note, so a caller writes `const done = traceTimer(\"x\"); ...; done(\"ok\")`.\n */\nexport function traceTimer(label: string): (note?: string) => void {\n\tif (!sink) return () => {};\n\tconst started = performance.now();\n\treturn (note) => {\n\t\tconst ms = Math.round(performance.now() - started);\n\t\ttrace(`${label} · ${ms} ms${note ? ` · ${note}` : \"\"}`);\n\t};\n}\n\n/** The facts a bug report needs first, printed once when tracing starts. */\nexport function traceEnvironment(facts: {\n\tcliVersion: string;\n\tbaseUrl: string;\n\ttrigger?: string;\n}): void {\n\ttrace(\n\t\t`aistack ${facts.cliVersion} · node ${process.versions.node} · ${process.platform}-${process.arch} · ${facts.baseUrl}${facts.trigger ? ` · trigger ${facts.trigger}` : \"\"}`,\n\t);\n}\n","import { existsSync } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport path from \"node:path\";\nimport { Worker } from \"node:worker_threads\";\nimport type { Session, SessionReadContext } from \"cursor-history\";\nimport { trace, traceEnabled, traceTimer } from \"../../trace.js\";\nimport { asObj, asStr } from \"../shared/aggregate.js\";\nimport { emptyScanStats, type ScanStats } from \"../shared/window.js\";\nimport {\n\ttype LocalSession,\n\ttype TokenEvidence,\n\ttokenEvidence,\n} from \"./evidence.js\";\n\n/** Cursor's user-data override is a workspaceStorage path, as in cursor-history. */\nexport function dataPath(\n\tenv = process.env,\n\thome = homedir(),\n\tplatform = process.platform,\n): string {\n\tif (env.CURSOR_DATA_PATH) return path.resolve(env.CURSOR_DATA_PATH);\n\tconst base =\n\t\tplatform === \"darwin\"\n\t\t\t? path.join(home, \"Library\", \"Application Support\")\n\t\t\t: platform === \"win32\"\n\t\t\t\t? env.APPDATA || path.join(home, \"AppData\", \"Roaming\")\n\t\t\t\t: env.XDG_CONFIG_HOME || path.join(home, \".config\");\n\treturn path.join(base, \"Cursor\", \"User\", \"workspaceStorage\");\n}\nexport const storeRoot = () =>\n\tprocess.env.CURSOR_STORE_ROOT || path.join(homedir(), \".cursor\");\nexport const globalDb = (root: string) =>\n\tpath.join(path.dirname(root), \"globalStorage\", \"state.vscdb\");\n\nasync function exists(file: string): Promise<boolean> {\n\ttry {\n\t\tawait stat(file);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn (error as NodeJS.ErrnoException).code !== \"ENOENT\";\n\t}\n}\nexport async function hasLocalSource(root = dataPath()): Promise<boolean> {\n\treturn (\n\t\tawait Promise.all(\n\t\t\t[\n\t\t\t\troot,\n\t\t\t\tglobalDb(root),\n\t\t\t\tpath.join(storeRoot(), \"projects\"),\n\t\t\t\tpath.join(storeRoot(), \"chats\"),\n\t\t\t\tpath.join(storeRoot(), \"acp-sessions\"),\n\t\t\t].map(exists),\n\t\t)\n\t).some(Boolean);\n}\n\ntype Sqlite = import(\"node:sqlite\").DatabaseSync;\n/** Supplemental read only for fields the selected reader flattens. No transcript parser. */\nexport async function readTokenEvidence(\n\troot: string,\n\tsession: Session,\n): Promise<Map<string, TokenEvidence>> {\n\tconst out = new Map<string, TokenEvidence>();\n\tif (!session.messages.some((m) => m.identityOrigin?.startsWith(\"composer\")))\n\t\treturn out;\n\tconst file = globalDb(root);\n\tif (!(await exists(file))) return out;\n\tconst { DatabaseSync } = await import(\"node:sqlite\");\n\tconst db: Sqlite = new DatabaseSync(file, { readOnly: true });\n\ttry {\n\t\tdb.exec(\"BEGIN\");\n\t\tconst table = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'cursorDiskKV'\",\n\t\t\t)\n\t\t\t.get();\n\t\tif (!table) return out;\n\t\tconst query = db.prepare(`SELECT json_object(\n\t\t\t'tokenCount', json_extract(value, '$.tokenCount'),\n\t\t\t'usage', json_extract(value, '$.usage'),\n\t\t\t'contextWindowStatusAtCreation', json_extract(value, '$.contextWindowStatusAtCreation'),\n\t\t\t'promptDryRunInfo', json_extract(value, '$.promptDryRunInfo')) AS evidence\n\t\t\tFROM cursorDiskKV WHERE key = ?`);\n\t\tfor (const message of session.messages) {\n\t\t\tif (!message.id || message.identityOrigin !== \"composer-native\") continue;\n\t\t\tconst row = query.get(`bubbleId:${session.id}:${message.id}`);\n\t\t\tif (typeof row?.evidence === \"string\")\n\t\t\t\tout.set(message.id, tokenEvidence(JSON.parse(row.evidence)));\n\t\t}\n\t\t// Older Composer headers can retain inline bubbles instead of split keys.\n\t\tconst header = db\n\t\t\t.prepare(\n\t\t\t\t\"SELECT json_extract(value, '$.conversation') AS conversation FROM cursorDiskKV WHERE key = ?\",\n\t\t\t)\n\t\t\t.get(`composerData:${session.id}`);\n\t\tif (typeof header?.conversation === \"string\") {\n\t\t\tconst conversation: unknown = JSON.parse(header.conversation);\n\t\t\tif (Array.isArray(conversation))\n\t\t\t\tfor (const [index, raw] of conversation.entries()) {\n\t\t\t\t\tconst obj = asObj(raw);\n\t\t\t\t\tconst id = asStr(obj?.bubbleId) ?? asStr(obj?.id) ?? `msg:${index}`;\n\t\t\t\t\tif (!out.has(id)) out.set(id, tokenEvidence(raw));\n\t\t\t\t}\n\t\t}\n\t\treturn out;\n\t} finally {\n\t\tdb.close();\n\t}\n}\n\nasync function sourceStamp(root: string): Promise<string> {\n\tconst values = await Promise.all(\n\t\t[globalDb(root), `${globalDb(root)}-wal`].map(async (file) => {\n\t\t\ttry {\n\t\t\t\tconst info = await stat(file);\n\t\t\t\treturn `${info.size}:${info.mtimeMs}`;\n\t\t\t} catch {\n\t\t\t\treturn \"unavailable\";\n\t\t\t}\n\t\t}),\n\t);\n\treturn values.join(\"/\");\n}\n\nexport type LocalRead = {\n\tsessions: LocalSession[];\n\tcomplete: boolean;\n\tstats: ScanStats;\n};\n/**\n * One read per root per process.\n *\n * A sync asks this adapter four times (detect twice, scan twice), and every\n * read walks the whole global database: on a 1.6 GB `state.vscdb` the session\n * listing alone costs tens of seconds of CPU. Four walks read as a hang; one is\n * a wait. The memo is keyed by root alone, not by the source stamp: while\n * Cursor is open it appends to the write-ahead log continuously, so a stamp\n * taken after the first read never matches and the read would repeat. A sync\n * is one moment, and the read itself marks its result incomplete when the\n * source moved under it (see `readLocalOnce`).\n */\nconst localReads = new Map<\n\tstring,\n\t{ stamp: string; read: Promise<LocalRead> }\n>();\n\n/** Tests only: forget the reads this process made. */\nexport function forgetLocalReads(): void {\n\tlocalReads.clear();\n}\n\n/** Errors never escape with paths, prompts or database values. */\nexport async function readLocal(\n\troot = dataPath(),\n\tonProgress?: (files: number, total?: number) => void,\n): Promise<LocalRead> {\n\tconst held = localReads.get(root);\n\tif (held) {\n\t\ttrace(\"cursor · reusing this run's history read\");\n\t\treturn held.read;\n\t}\n\t// Nothing to walk, nothing to remember: an install that appears later in\n\t// the same process (tests do this) must still be read.\n\tif (!(await hasLocalSource(root))) {\n\t\ttrace(\"cursor · no local source\");\n\t\treturn { sessions: [], complete: true, stats: emptyScanStats() };\n\t}\n\tconst stamp = await sourceStamp(root);\n\tconst read = readLocalOffThread(root, stamp, onProgress);\n\tlocalReads.set(root, { stamp, read });\n\treturn read;\n}\n\n/**\n * The bundled worker next to the CLI entry (`tsup` emits `cursor-worker.js`\n * beside `index.js`). Absent when running from source, where the read stays\n * inline; `AISTACK_CURSOR_INLINE=1` forces inline in a build too.\n */\nfunction workerFile(): URL | null {\n\tif (process.env.AISTACK_CURSOR_INLINE === \"1\") return null;\n\tconst url = new URL(\"./cursor-worker.js\", import.meta.url);\n\treturn existsSync(url) ? url : null;\n}\n\n/**\n * The read walks the whole global database synchronously: cursor-history's\n * session listing alone is tens of seconds of CPU on a database past a\n * gigabyte. On the main thread that freezes the terminal; in a worker the\n * board keeps drawing and the other harnesses keep scanning (#420). The\n * worker returns the same `LocalRead` (sessions are plain data, token\n * evidence is a Map), so the caller cannot tell which thread read it.\n */\nasync function readLocalOffThread(\n\troot: string,\n\tbefore: string,\n\tonProgress?: (files: number, total?: number) => void,\n): Promise<LocalRead> {\n\tconst file = workerFile();\n\tif (!file) return readLocalOnce(root, before, onProgress);\n\treturn new Promise<LocalRead>((resolve) => {\n\t\tconst fallback = () => resolve(readLocalOnce(root, before, onProgress));\n\t\tlet settled = false;\n\t\tconst settle = (fn: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tfn();\n\t\t};\n\t\tconst worker = new Worker(file, {\n\t\t\tworkerData: { root, before, trace: traceEnabled() },\n\t\t});\n\t\tworker.on(\"message\", (message: CursorWorkerMessage) => {\n\t\t\tif (message.kind === \"progress\")\n\t\t\t\tonProgress?.(message.files, message.total);\n\t\t\telse if (message.kind === \"result\") settle(() => resolve(message.read));\n\t\t\telse\n\t\t\t\tsettle(() => {\n\t\t\t\t\ttrace(\"cursor · worker failed, reading inline\");\n\t\t\t\t\tfallback();\n\t\t\t\t});\n\t\t});\n\t\tworker.on(\"error\", () => settle(fallback));\n\t\tworker.on(\"exit\", (code) => {\n\t\t\tif (code !== 0) settle(fallback);\n\t\t});\n\t});\n}\n\nexport type CursorWorkerMessage =\n\t| { kind: \"progress\"; files: number; total?: number }\n\t| { kind: \"result\"; read: LocalRead }\n\t| { kind: \"error\" };\n\n/** The read itself, on whichever thread called it. */\nexport async function readLocalOnce(\n\troot: string,\n\tbefore: string,\n\tonProgress?: (files: number, total?: number) => void,\n): Promise<LocalRead> {\n\tconst stats = emptyScanStats();\n\tconst out: LocalRead = { sessions: [], complete: true, stats };\n\tif (!(await hasLocalSource(root))) {\n\t\ttrace(\"cursor · no local source\");\n\t\treturn out;\n\t}\n\ttrace(`cursor · global database ${await globalDbSize(root)}`);\n\tconst readDone = traceTimer(\"cursor history read\");\n\tlet context: SessionReadContext | undefined;\n\ttry {\n\t\tconst reader = await import(\"cursor-history\");\n\t\tconst options = {\n\t\t\tdataPath: root,\n\t\t\tsqliteDriver: \"node:sqlite\" as const,\n\t\t\tonDiagnostic: () => {\n\t\t\t\tout.complete = false;\n\t\t\t},\n\t\t\tsignal: AbortSignal.timeout(120_000),\n\t\t};\n\t\tcontext = reader.createSessionReadContext(options);\n\t\tconst config = { ...options, readContext: context };\n\t\tlet offset = 0;\n\t\twhile (true) {\n\t\t\t// The first page carries the whole workspace discovery, which walks\n\t\t\t// every bubble key in the global database before it returns.\n\t\t\tconst pageDone = traceTimer(\n\t\t\t\toffset === 0 ? \"cursor session listing\" : \"cursor session page\",\n\t\t\t);\n\t\t\tconst page = await reader.listSessionSummaries({\n\t\t\t\t...config,\n\t\t\t\toffset,\n\t\t\t\tlimit: 100,\n\t\t\t});\n\t\t\tpageDone(`${page.data.length} of ${page.pagination.total} sessions`);\n\t\t\tif (offset === 0) onProgress?.(0, page.pagination.total);\n\t\t\tfor (const summary of page.data) {\n\t\t\t\tstats.filesFound++;\n\t\t\t\tif (summary.resolutionState === \"ambiguous\") {\n\t\t\t\t\tout.complete = false;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst session = await reader.getSession(summary.id, config);\n\t\t\t\t\tif (\n\t\t\t\t\t\tsession.resolutionState !== \"complete\" ||\n\t\t\t\t\t\tsession.messages.some((m) => m.metadata?.corrupted)\n\t\t\t\t\t)\n\t\t\t\t\t\tout.complete = false;\n\t\t\t\t\tconst tokens = await readTokenEvidence(root, session);\n\t\t\t\t\tout.sessions.push({ session, tokens });\n\t\t\t\t\tstats.filesRead++;\n\t\t\t\t\tonProgress?.(stats.filesRead, page.pagination.total);\n\t\t\t\t} catch {\n\t\t\t\t\tout.complete = false;\n\t\t\t\t\tstats.filesUnreadable++;\n\t\t\t\t} finally {\n\t\t\t\t\tcontext.releaseSession(summary.id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!page.pagination.hasMore) break;\n\t\t\tif (page.data.length === 0 || offset >= 100_000) {\n\t\t\t\tout.complete = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toffset += page.data.length;\n\t\t}\n\t} catch {\n\t\tout.complete = false;\n\t\tstats.filesUnreadable++;\n\t} finally {\n\t\ttry {\n\t\t\tawait context?.dispose();\n\t\t} catch {\n\t\t\tout.complete = false;\n\t\t}\n\t}\n\tif (before !== (await sourceStamp(root))) out.complete = false;\n\treadDone(\n\t\t`${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? \"\" : \", incomplete\"}`,\n\t);\n\treturn out;\n}\n\nasync function globalDbSize(root: string): Promise<string> {\n\ttry {\n\t\tconst info = await stat(globalDb(root));\n\t\treturn `${(info.size / 1_048_576).toFixed(0)} MB`;\n\t} catch {\n\t\treturn \"absent\";\n\t}\n}\n","// The price table as data: dated periods keyed by model id (ADR-0012, #336).\n//\n// One shape serves three places. The Convex `modelPrices` table holds one row\n// per period. The `/api/prices` endpoint serves the same rows to the CLI. And\n// the constants in `index.ts` render themselves into the same rows, so the\n// bundled fallback and the served table go through one lookup.\n//\n// A period runs from its `from` until the next period's `from` for the same\n// (model, provider). There is no `to`. Cache tiers are ABSOLUTE rates per\n// period, never a vendor-level multiplier: models.dev reports them that way,\n// and a multiplier is wrong for at least one Google model.\n//\n// Every period names its `source`. That string is what a surface prints beside\n// a dollar figure, so the citation travels with the rate that produced it.\n\n/** The separator between a provider id and a model id in a pricing key. */\nexport const PROVIDER_SEPARATOR = \":\";\n\n/**\n * The citation for a model that runs on the user's own machine. It is not a\n * vendor list. It is the statement that no per-token charge exists.\n */\nexport const LOCAL_PRICING_TABLE_VERSION = \"local-no-charge\";\n\n/** One dated period, as stored, served and bundled. USD per million tokens. */\nexport type PriceRow = {\n\t/** The vendor's bare API id (the catalog slug). May carry `#fast`. */\n\tmodelSlug: string;\n\t/** Unset is the vendor's own rate. Set names a gateway with its own rate. */\n\tprovider?: string;\n\t/** Inclusive start, epoch ms. `0` means since the model existed. */\n\tfrom: number;\n\tinput: number;\n\toutput: number;\n\tcacheRead?: number;\n\tcacheWrite5m?: number;\n\tcacheWrite1h?: number;\n\t/** The table or dataset that priced this period. Printed beside every dollar. */\n\tsource: string;\n\t/**\n\t * Who sets the vendor rate. Wire-only: a served row carries the catalog's\n\t * provider so a `google:` key can reach a Google model's bare rate. Not a\n\t * column of `modelPrices`.\n\t */\n\tvendor?: Vendor;\n};\n\n/** A whole table, with the id the CLI prints when it says which table it used. */\nexport type PriceTable = {\n\tid: string;\n\trows: PriceRow[];\n};\n\n/**\n * Who sets the rate. A provider only reaches a vendor's rows when it IS that\n * vendor; a gateway re-serving the same model is a different price.\n */\nexport type Vendor = \"anthropic\" | \"openai\" | \"google\" | \"xai\" | \"local\";\n\n/** USD per million tokens, valid over `[from, to)`, with its citation. */\nexport type PricePeriod = {\n\t/** Inclusive lower bound, epoch ms. `null` = since the model existed. */\n\tfrom: number | null;\n\t/** Exclusive upper bound, epoch ms. `null` = still in effect. */\n\tto: number | null;\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite5m: number;\n\tcacheWrite1h: number;\n\tsource: string;\n};\n\n/**\n * Providers that ARE the vendor, so their rows price at that vendor's list.\n *\n * Deliberately absent, and each absence is a decision from ticket #122's\n * measurements: `opencode` (the opencode-zen gateway), `github-copilot`\n * (re-serves other vendors' slugs at its own terms), `openrouter`, `azure`,\n * `bedrock` and `vercel-ai-gateway` (resellers). A provider joins this map\n * when a harness is measured emitting it, never speculatively.\n */\nexport const PROVIDER_VENDOR: Record<string, Vendor> = {\n\tanthropic: \"anthropic\",\n\topenai: \"openai\",\n\tgoogle: \"google\",\n\txai: \"xai\",\n};\n\n/**\n * Explicit pricing equivalents that do not collapse catalog identity.\n *\n * Grok Build records `grok-4.6-build` for usage while identifying the selected\n * model as `grok-4.6`. The Build id remains the measured and catalog id. It may\n * borrow the base model's cited rate only when no exact rate exists.\n */\nexport const PRICING_ALIASES: Readonly<Record<string, string>> = {\n\t\"grok-4.6-build\": \"grok-4.6\",\n};\n\n/**\n * Providers that run the model on this machine. No API call, no per-token\n * charge. Ids as opencode and pi-mono spell them.\n */\nexport const LOCAL_PROVIDERS = new Set([\n\t\"ollama\",\n\t\"lmstudio\",\n\t\"llama.cpp\",\n\t\"llamacpp\",\n\t\"local\",\n]);\n\nconst FREE_PERIOD: PricePeriod = {\n\tfrom: null,\n\tto: null,\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite5m: 0,\n\tcacheWrite1h: 0,\n\tsource: LOCAL_PRICING_TABLE_VERSION,\n};\n\n/**\n * Split a pricing key into its provider and its model part.\n *\n * A key with no separator has no provider, which is what the single-vendor\n * adapters produce. The split is on the FIRST separator only, so an id that\n * carries its own colon (`ollama:llama3.2:3b`) keeps it.\n */\nexport function splitModelKey(modelKey: string): {\n\tprovider: string | null;\n\tmodel: string;\n} {\n\tconst at = modelKey.indexOf(PROVIDER_SEPARATOR);\n\tif (at === -1) return { provider: null, model: modelKey };\n\treturn {\n\t\tprovider: modelKey.slice(0, at),\n\t\tmodel: modelKey.slice(at + PROVIDER_SEPARATOR.length),\n\t};\n}\n\n/**\n * The alias rules of ADR-0012 decision 6, applied before any lookup: strip the\n * `provider:` prefix, the `#fast` suffix and a trailing `-YYYYMMDD` date. The\n * three parts come back separately so a caller can keep the ones it needs.\n */\nexport function parseMeasuredId(id: string): {\n\tprovider: string | null;\n\tslug: string;\n\tfast: boolean;\n} {\n\tconst { provider, model } = splitModelKey(id);\n\tconst [base, suffix] = model.split(\"#\");\n\treturn {\n\t\tprovider,\n\t\tslug: base.replace(/-\\d{8}$/, \"\"),\n\t\tfast: suffix === \"fast\",\n\t};\n}\n\nconst key = (slug: string, provider: string | null | undefined) =>\n\t`${provider ?? \"\"}\u0000${slug}`;\n\n/**\n * A table indexed for lookup: every (model, provider) with its periods in\n * order, each closed by the next one's start.\n */\nexport class PriceIndex {\n\tprivate readonly periods = new Map<string, PricePeriod[]>();\n\tprivate readonly vendors = new Map<string, Vendor>();\n\treadonly id: string;\n\n\tconstructor(table: PriceTable) {\n\t\tthis.id = table.id;\n\t\tconst groups = new Map<string, PriceRow[]>();\n\t\tfor (const row of table.rows) {\n\t\t\tconst k = key(row.modelSlug, row.provider);\n\t\t\tconst g = groups.get(k) ?? [];\n\t\t\tg.push(row);\n\t\t\tgroups.set(k, g);\n\t\t\tif (row.vendor && row.provider === undefined) {\n\t\t\t\tthis.vendors.set(row.modelSlug, row.vendor);\n\t\t\t}\n\t\t}\n\t\tfor (const [k, rows] of groups) {\n\t\t\trows.sort((a, b) => a.from - b.from);\n\t\t\tthis.periods.set(\n\t\t\t\tk,\n\t\t\t\trows.map((r, i) => ({\n\t\t\t\t\tfrom: r.from === 0 ? null : r.from,\n\t\t\t\t\tto: i + 1 < rows.length ? rows[i + 1].from : null,\n\t\t\t\t\tinput: r.input,\n\t\t\t\t\toutput: r.output,\n\t\t\t\t\tcacheRead: r.cacheRead ?? 0,\n\t\t\t\t\tcacheWrite5m: r.cacheWrite5m ?? 0,\n\t\t\t\t\tcacheWrite1h: r.cacheWrite1h ?? 0,\n\t\t\t\t\tsource: r.source,\n\t\t\t\t})),\n\t\t\t);\n\t\t}\n\t}\n\n\t/** The vendor a bare row belongs to, when the table says. */\n\tvendorOf(slug: string): Vendor | null {\n\t\treturn this.vendors.get(slug) ?? null;\n\t}\n\n\t/** True when the table holds any row at all for this (model, provider). */\n\thas(slug: string, provider: string | null): boolean {\n\t\treturn this.periods.has(key(slug, provider));\n\t}\n\n\t/** The periods for exactly this (model, provider). */\n\trowsFor(slug: string, provider: string | null): PricePeriod[] {\n\t\treturn this.periods.get(key(slug, provider)) ?? [];\n\t}\n\n\tget size(): number {\n\t\treturn this.periods.size;\n\t}\n}\n\n/**\n * Several tables layered: the first one that holds a key answers for it. The\n * CLI layers the served table over the bundled one; the backend layers\n * `modelPrices` over the same bundled one. The provider rule is stated here,\n * once, for both.\n */\nexport class Pricer {\n\tconstructor(\n\t\tprivate readonly layers: readonly PriceIndex[],\n\t\tprivate readonly vendorHint: (slug: string) => Vendor | null = () => null,\n\t) {}\n\n\t/** The ids of the layers, in lookup order. */\n\tget tableIds(): string[] {\n\t\treturn this.layers.map((l) => l.id);\n\t}\n\n\tprivate vendorOf(slug: string): Vendor | null {\n\t\tfor (const layer of this.layers) {\n\t\t\tconst v = layer.vendorOf(slug);\n\t\t\tif (v) return v;\n\t\t}\n\t\treturn this.vendorHint(slug);\n\t}\n\n\tprivate firstLayerWith(slug: string, provider: string | null) {\n\t\treturn this.layers.find((l) => l.has(slug, provider)) ?? null;\n\t}\n\n\tprivate lookupSlug(slug: string, provider: string | null): string | null {\n\t\tif (this.firstLayerWith(slug, provider)) return slug;\n\t\tconst alias = PRICING_ALIASES[slug];\n\t\treturn alias && this.firstLayerWith(alias, provider) ? alias : null;\n\t}\n\n\t/**\n\t * Every period that applies to a pricing key, or an empty list when none\n\t * can be cited.\n\t *\n\t * A bare key is the vendor's own rate. A local provider is free. A provider\n\t * with rows of its own uses them. A provider that IS the vendor reaches the\n\t * vendor's bare rows. Anything else (a gateway, an unknown provider) holds\n\t * no rate.\n\t */\n\tperiodsFor(modelKey: string): PricePeriod[] {\n\t\tconst { provider, model } = splitModelKey(modelKey);\n\t\tif (provider === null) {\n\t\t\tconst slug = this.lookupSlug(model, null);\n\t\t\treturn slug\n\t\t\t\t? (this.firstLayerWith(slug, null)?.rowsFor(slug, null) ?? [])\n\t\t\t\t: [];\n\t\t}\n\t\tif (LOCAL_PROVIDERS.has(provider)) return [FREE_PERIOD];\n\t\tconst ownSlug = this.lookupSlug(model, provider);\n\t\tif (ownSlug) {\n\t\t\treturn (\n\t\t\t\tthis.firstLayerWith(ownSlug, provider)?.rowsFor(ownSlug, provider) ?? []\n\t\t\t);\n\t\t}\n\t\tconst vendor = PROVIDER_VENDOR[provider];\n\t\tconst vendorSlug = this.lookupSlug(model, null);\n\t\tif (!vendor || !vendorSlug || this.vendorOf(vendorSlug) !== vendor)\n\t\t\treturn [];\n\t\treturn (\n\t\t\tthis.firstLayerWith(vendorSlug, null)?.rowsFor(vendorSlug, null) ?? []\n\t\t);\n\t}\n\n\tisLocal(modelKey: string): boolean {\n\t\tconst { provider } = splitModelKey(modelKey);\n\t\treturn provider !== null && LOCAL_PROVIDERS.has(provider);\n\t}\n\n\tisPriced(modelKey: string): boolean {\n\t\treturn this.periodsFor(modelKey).length > 0;\n\t}\n\n\t/**\n\t * The rate in effect at `atMs`, or `null` when the model is unknown or the\n\t * timestamp predates every period. A `null` timestamp also yields `null`:\n\t * inventing a price for an undated record would attribute the wrong rate.\n\t */\n\tpriceAt(modelKey: string, atMs: number | null): PricePeriod | null {\n\t\tif (atMs === null) return null;\n\t\tfor (const p of this.periodsFor(modelKey)) {\n\t\t\tif (\n\t\t\t\t(p.from === null || atMs >= p.from) &&\n\t\t\t\t(p.to === null || atMs < p.to)\n\t\t\t) {\n\t\t\t\treturn p;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Every rate that applies anywhere inside `[fromMs, toMs]`. */\n\tperiodsInWindow(\n\t\tmodelKey: string,\n\t\tfromMs: number,\n\t\ttoMs: number,\n\t): PricePeriod[] {\n\t\treturn this.periodsFor(modelKey).filter(\n\t\t\t(p) =>\n\t\t\t\t(p.from === null || p.from <= toMs) && (p.to === null || p.to > fromMs),\n\t\t);\n\t}\n\n\t/**\n\t * The citation for this key: the source of the period in effect at `atMs`,\n\t * or of the latest period when no time is given. `null` when unpriced.\n\t */\n\ttableFor(modelKey: string, atMs?: number): string | null {\n\t\tconst periods = this.periodsFor(modelKey);\n\t\tif (periods.length === 0) return null;\n\t\tif (atMs !== undefined) return this.priceAt(modelKey, atMs)?.source ?? null;\n\t\treturn periods[periods.length - 1].source;\n\t}\n}\n\n/** A stable id for a served table: the row count and a hash of the rows. */\nexport function priceTableId(rows: readonly PriceRow[]): string {\n\tconst text = rows\n\t\t.map(\n\t\t\t(r) =>\n\t\t\t\t`${r.modelSlug}|${r.provider ?? \"\"}|${r.from}|${r.input}|${r.output}|${r.cacheRead ?? \"\"}|${r.cacheWrite5m ?? \"\"}|${r.cacheWrite1h ?? \"\"}|${r.source}`,\n\t\t)\n\t\t.sort()\n\t\t.join(\"\\n\");\n\t// FNV-1a, 32-bit. Enough to tell two tables apart in a log line.\n\tlet h = 0x811c9dc5;\n\tfor (let i = 0; i < text.length; i++) {\n\t\th ^= text.charCodeAt(i);\n\t\th = Math.imul(h, 0x01000193) >>> 0;\n\t}\n\treturn `modelPrices/${rows.length}-${h.toString(16).padStart(8, \"0\")}`;\n}\n\n/**\n * Narrow untrusted JSON into a table. A row that fails the shape is dropped\n * rather than failing the whole fetch; a table with no rows is `null` so the\n * caller falls back to the bundled one.\n */\nexport function parsePriceTable(body: unknown): PriceTable | null {\n\tif (typeof body !== \"object\" || body === null) return null;\n\tconst b = body as { id?: unknown; rows?: unknown };\n\tif (typeof b.id !== \"string\" || !Array.isArray(b.rows)) return null;\n\tconst num = (v: unknown): v is number =>\n\t\ttypeof v === \"number\" && Number.isFinite(v) && v >= 0;\n\tconst opt = (v: unknown): number | undefined => (num(v) ? v : undefined);\n\tconst rows: PriceRow[] = [];\n\tfor (const raw of b.rows) {\n\t\tconst r = raw as Record<string, unknown>;\n\t\tif (\n\t\t\ttypeof r?.modelSlug !== \"string\" ||\n\t\t\tr.modelSlug.length === 0 ||\n\t\t\t!num(r.from) ||\n\t\t\t!num(r.input) ||\n\t\t\t!num(r.output) ||\n\t\t\ttypeof r.source !== \"string\"\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst vendor =\n\t\t\tr.vendor === \"anthropic\" ||\n\t\t\tr.vendor === \"openai\" ||\n\t\t\tr.vendor === \"google\" ||\n\t\t\tr.vendor === \"xai\" ||\n\t\t\tr.vendor === \"local\"\n\t\t\t\t? r.vendor\n\t\t\t\t: undefined;\n\t\trows.push({\n\t\t\tmodelSlug: r.modelSlug,\n\t\t\t...(typeof r.provider === \"string\" && r.provider.length > 0\n\t\t\t\t? { provider: r.provider }\n\t\t\t\t: {}),\n\t\t\tfrom: r.from,\n\t\t\tinput: r.input,\n\t\t\toutput: r.output,\n\t\t\t...(opt(r.cacheRead) !== undefined\n\t\t\t\t? { cacheRead: r.cacheRead as number }\n\t\t\t\t: {}),\n\t\t\t...(opt(r.cacheWrite5m) !== undefined\n\t\t\t\t? { cacheWrite5m: r.cacheWrite5m as number }\n\t\t\t\t: {}),\n\t\t\t...(opt(r.cacheWrite1h) !== undefined\n\t\t\t\t? { cacheWrite1h: r.cacheWrite1h as number }\n\t\t\t\t: {}),\n\t\t\tsource: r.source,\n\t\t\t...(vendor ? { vendor } : {}),\n\t\t});\n\t}\n\tif (rows.length === 0) return null;\n\treturn { id: b.id, rows };\n}\n","// Time-aware pinned price table for API-equivalent cost.\n//\n// Wayfinder ticket #37 (map #29), decision 8 of the wire-format grilling #33.\n// Moved out of the CLI by ticket #93 (map #76).\n//\n// WHY THIS IS A PACKAGE AND NOT A CLI FILE\n// Two programs price the same tokens. The CLI prices each response at ingest,\n// where the per-response timestamp still exists. The backend re-prices a\n// published snapshot at READ time, to fill the gaps a stale CLI table left\n// behind - one day of table drift published a stack at $14,764 when the same\n// tokens are worth at least $167,331 (#93). Two copies of a price table drift\n// against each other by construction, so there is one copy and both import it.\n//\n// WHY THIS IS A LIST OF PERIODS AND NOT A FLAT MAP\n// A published \"API-equivalent cost\" covers a rolling 30-day window, and a\n// window can straddle a repricing. On 2026-09-05 the window covers Aug 6 →\n// Sep 5, but `claude-sonnet-5`'s introductory rate ends Aug 31 - so 25 days\n// price at $2/$10 and 5 days at $3/$15. A flat table misprices one side or the\n// other for a month after every repricing, which breaks the honesty tenet the\n// measured layer is built on.\n//\n// So each model's price is a list of effective-from ranges, and every response\n// is priced at the rate in effect at ITS OWN timestamp. Cost therefore has to\n// accumulate at ingest (see analyzer.ts) - summing tokens per model and pricing\n// once at the end cannot express a mid-window rate change.\n//\n// Sources: Anthropic public list prices as of 2026-07-25 (cache multipliers\n// from https://platform.claude.com/docs/en/build-with-claude/prompt-caching:\n// 5m cache write = 1.25x input, 1h cache write = 2x input, read = 0.1x input)\n// and OpenAI public list prices as of 2026-08-02\n// (https://developers.openai.com/api/docs/pricing - cached input is 10% of\n// input, the same multiplier `cacheRead` already uses; Codex reports no cache\n// writes, so the write multipliers never fire for OpenAI rows).\n// Google public list prices as of 2026-08-09\n// (https://ai.google.dev/gemini-api/docs/pricing) were added by ticket #123.\n//\n// A read-time estimate cites the table of the model it priced, which is why the\n// table id sits on the rate rather than beside it.\n//\n// WHY A KEY CAN CARRY A PROVIDER\n// Claude Code and Codex each speak to one vendor, so a bare model id names a\n// rate without ambiguity. opencode and pi-mono route many providers, and two of\n// them RE-SERVE another vendor's models under that vendor's own slug: the\n// opencode-zen gateway and github-copilot both emit `gemini-3-pro-preview`, at\n// prices no list page states (ticket #122). Pricing a re-served model at the\n// vendor's list rate would invent a figure and could overstate, which the\n// lower-bound tenet forbids.\n//\n// So a multi-provider adapter keys its rows `provider:model`, and only a\n// provider this table maps to a vendor reaches that vendor's rates. Everything\n// else - gateways, unknown providers - holds no rate and lands in\n// `unpricedTokens`, which is the honest outcome and needs no new machinery.\n//\n// The separator is `:` and not `/` on purpose: `sanitizeModelId` in the CLI\n// payload rewrites `/` to `-`, so a slash-keyed id would reach the backend as a\n// different string than the one this table holds, and the read-time re-pricer\n// would miss it.\n//\n// A LOCAL MODEL IS FREE, WHICH IS NOT THE SAME FACT AS UNPRICED\n// `ollama:qwen3-coder` costs nothing per token. `openrouter:qwen3-coder` costs\n// something this table cannot name. Both used to look identical - no row, no\n// rate, tokens excluded from coverage - so a local run read as a hole in the\n// table. Local providers now hold a real zero rate, cited as\n// `LOCAL_PRICING_TABLE_VERSION`. Their tokens count as covered and add $0.\n//\n// WHERE THE RATES LIVE NOW (#336, ADR-0012)\n// The constants below are the BUNDLED FALLBACK. The live table is the Convex\n// `modelPrices` table, served to the CLI at `/api/prices` and layered over\n// these constants by `layeredPricer`. `table.ts` holds the row shape and the\n// lookup both sides share; this file holds the constants and the module-level\n// functions the adapters call, which read whichever pricer is active.\n\nexport const PRICING_TABLE_VERSION = \"anthropic-list-2026-07-25\";\nexport const OPENAI_PRICING_TABLE_VERSION = \"openai-list-2026-08-02\";\nexport const GOOGLE_PRICING_TABLE_VERSION = \"google-list-2026-08-09\";\nexport const XAI_PRICING_TABLE_VERSION = \"models.dev@2026-08-29\";\n/**\n * The id the CLI prints when it priced against the bundled constants rather\n * than a table the server served (#336). Bump it when a constant changes.\n */\nexport const BUNDLED_PRICE_TABLE_ID = \"bundled-2026-09-10\";\n\nexport {\n\tLOCAL_PRICING_TABLE_VERSION,\n\tPRICING_ALIASES,\n\tPROVIDER_SEPARATOR,\n\tPriceIndex,\n\ttype PricePeriod,\n\ttype PriceRow,\n\tPricer,\n\ttype PriceTable,\n\tparseMeasuredId,\n\tparsePriceTable,\n\tpriceTableId,\n\tsplitModelKey,\n\ttype Vendor,\n} from \"./table.js\";\n\nimport {\n\tPROVIDER_SEPARATOR,\n\tPriceIndex,\n\ttype PricePeriod,\n\ttype PriceRow,\n\tPricer,\n\ttype PriceTable,\n\tsplitModelKey,\n\ttype Vendor,\n} from \"./table.js\";\n\nexport const CACHE_WRITE_5M_MULTIPLIER = 1.25;\nexport const CACHE_WRITE_1H_MULTIPLIER = 2.0;\nexport const CACHE_READ_MULTIPLIER = 0.1;\n\n/**\n * End of the `claude-sonnet-5` introductory rate. Anthropic documents it as \"in\n * effect through 2026-08-31\", so the post-intro period opens at the following\n * UTC midnight.\n *\n * The boundary is approximated in UTC because the announcement names a date,\n * not a timezone. A response written within a few hours of the boundary can\n * therefore be priced on the wrong side of it - worth a handful of cents on a\n * single day, and the alternative (guessing US/Pacific) is no more defensible.\n */\nexport const SONNET_5_INTRO_ENDS_MS = Date.UTC(2026, 8, 1); // 2026-09-01T00:00:00Z\n\n/**\n * How a vendor charges for cache traffic, as multipliers on its input rate.\n *\n * Only the bundled constants are written this way. A served period carries\n * absolute cache rates (ADR-0012 decision 4), and `cacheMultipliersFor` derives\n * the multipliers back from them for callers that still want the ratio.\n */\nexport type CacheMultipliers = {\n\twrite5m: number;\n\twrite1h: number;\n\tread: number;\n};\n\nconst DEFAULT_CACHE_MULTIPLIERS: CacheMultipliers = {\n\twrite5m: CACHE_WRITE_5M_MULTIPLIER,\n\twrite1h: CACHE_WRITE_1H_MULTIPLIER,\n\tread: CACHE_READ_MULTIPLIER,\n};\n\n/**\n * Cached input is 10% of input; a write is charged as plain input. Google\n * bills cache storage by the hour instead, which this table cannot see, so a\n * Google figure stays below the true one rather than above it.\n */\nconst GOOGLE_CACHE_MULTIPLIERS: CacheMultipliers = {\n\twrite5m: 1.0,\n\twrite1h: 1.0,\n\tread: 0.1,\n};\n\nconst XAI_CACHE_MULTIPLIERS: CacheMultipliers = {\n\twrite5m: 0,\n\twrite1h: 0,\n\tread: 0.25,\n};\n\n/** A bundled rate, before it is rendered into dated rows. */\ntype BundledPeriod = {\n\tfrom: number | null;\n\tinput: number;\n\toutput: number;\n};\n\ntype PriceEntry = {\n\tvendor: Vendor;\n\t/** The citation printed next to any dollar figure these rates produce. */\n\ttable: string;\n\tperiods: BundledPeriod[];\n\tcache: CacheMultipliers;\n};\n\nconst anthropic = (periods: BundledPeriod[]): PriceEntry => ({\n\tvendor: \"anthropic\",\n\ttable: PRICING_TABLE_VERSION,\n\tperiods,\n\tcache: DEFAULT_CACHE_MULTIPLIERS,\n});\nconst openai = (periods: BundledPeriod[]): PriceEntry => ({\n\tvendor: \"openai\",\n\ttable: OPENAI_PRICING_TABLE_VERSION,\n\tperiods,\n\tcache: DEFAULT_CACHE_MULTIPLIERS,\n});\nconst google = (periods: BundledPeriod[]): PriceEntry => ({\n\tvendor: \"google\",\n\ttable: GOOGLE_PRICING_TABLE_VERSION,\n\tperiods,\n\tcache: GOOGLE_CACHE_MULTIPLIERS,\n});\nconst xai = (periods: BundledPeriod[]): PriceEntry => ({\n\tvendor: \"xai\",\n\ttable: XAI_PRICING_TABLE_VERSION,\n\tperiods,\n\tcache: XAI_CACHE_MULTIPLIERS,\n});\nconst flat = (input: number, output: number): BundledPeriod[] => [\n\t{ from: null, input, output },\n];\n\n/**\n * The priced lanes (ADR-0012 decision 7): measured ids that carry a rate but\n * name no model a person can choose. They live here and never in the catalog\n * or in `modelPrices`, so the seed migration and the served table skip them.\n */\nexport const PRICED_LANES: ReadonlySet<string> = new Set([\"codex-auto-review\"]);\n\n/**\n * Only rates we can actually cite are encoded. Inventing historical periods to\n * make the table look complete would fabricate cost for old records, so every\n * model with one known rate gets one open-ended period.\n *\n * Where models.dev and a list page disagreed on 2026-08-29, models.dev won\n * (ADR-0012 decision 12): `gpt-5.6-sol` and `gemini-3.6-flash` below.\n */\nconst PRICES: Record<string, PriceEntry> = {\n\t\"claude-fable-5\": anthropic(flat(10, 50)),\n\t\"claude-mythos-5\": anthropic(flat(10, 50)),\n\t\"claude-opus-5\": anthropic(flat(5, 25)),\n\t\"claude-opus-4-8\": anthropic(flat(5, 25)),\n\t\"claude-opus-4-7\": anthropic(flat(5, 25)),\n\t\"claude-opus-4-6\": anthropic(flat(5, 25)),\n\t\"claude-sonnet-5\": anthropic([\n\t\t{ from: null, input: 2, output: 10 },\n\t\t{ from: SONNET_5_INTRO_ENDS_MS, input: 3, output: 15 },\n\t]),\n\t\"claude-sonnet-4-6\": anthropic(flat(3, 15)),\n\t\"claude-haiku-4-5\": anthropic(flat(1, 5)),\n\t// Fast mode (research preview) - Claude API only, Opus 5 / Opus 4.8 only.\n\t// Opus 4.7 fast mode was removed, so there is deliberately no 4-7 entry.\n\t\"claude-opus-5#fast\": anthropic(flat(10, 50)),\n\t\"claude-opus-4-8#fast\": anthropic(flat(10, 50)),\n\t// OpenAI (Codex) - standard-context tier (<272K; observed context window is\n\t// 258,400).\n\t\"gpt-5.5\": openai(flat(5, 30)),\n\t\"gpt-5.4\": openai(flat(2.5, 15)),\n\t\"gpt-5.4-mini\": openai(flat(0.75, 4.5)),\n\t\"gpt-5.3-codex\": openai(flat(1.75, 14)),\n\t// The gpt-5.6 family launched 2026-07-29; Terra and Luna were repriced on\n\t// 2026-07-30 (-20% / -80%). The one-day launch rates are not on the list\n\t// page and are NOT encoded - a July-29 Terra/Luna record underprices for\n\t// one day rather than carrying a rate we cannot cite (#72).\n\t// Sol: models.dev reports $4 / $20 on 2026-08-29; the earlier $5 / $30 is\n\t// not dated, so the lower rate prices the whole period (lower bound).\n\t\"gpt-5.6-sol\": openai(flat(4, 20)),\n\t\"gpt-5.6-terra\": openai(flat(2, 12)),\n\t\"gpt-5.6-luna\": openai(flat(0.2, 1.2)),\n\t// NOT on OpenAI's list page - an internal Codex routing label with no\n\t// official price (openai/codex#20981). Rate is the aggregator consensus\n\t// ($2.50 / $15.00), scoped in explicitly by ticket #72 because it carries\n\t// real token volume in Codex rollouts. A priced lane, see PRICED_LANES.\n\t\"codex-auto-review\": openai(flat(2.5, 15)),\n\t// Google (opencode, pi-mono) - Standard tier. Where a model is\n\t// context-tiered, the <=200K rate is encoded, exactly as the OpenAI rows\n\t// encode the standard-context tier: the payload carries no per-response\n\t// context length, so the cheaper side keeps the figure a lower bound.\n\t\"gemini-3.1-pro-preview\": google(flat(2, 12)),\n\t// models.dev reports $0.75 / $3.75 on 2026-08-29 (was $1.5 / $7.5).\n\t\"gemini-3.6-flash\": google(flat(0.75, 3.75)),\n\t\"gemini-3.5-flash\": google(flat(1.5, 9)),\n\t\"gemini-3-flash-preview\": google(flat(0.5, 3)),\n\t\"gemini-2.5-pro\": google(flat(1.25, 10)),\n\t\"gemini-2.5-flash\": google(flat(0.3, 2.5)),\n\t// RETIRED from Google's list page by 2026-08-09, and still the largest\n\t// single block of Google tokens measured in #122. Encoded at its launch\n\t// rate: real volume, a rate we can name. Announcement rate, <=200K tier.\n\t\"gemini-3-pro-preview\": google(flat(2, 12)),\n\t// A real Anthropic model with no row until #123. Measured in #122 as\n\t// `claude-opus-4-5-20251101`, which the dated-suffix rule strips to this key.\n\t\"claude-opus-4-5\": anthropic(flat(5, 25)),\n\t// models.dev's xAI row mirrored into the live table on 2026-08-29. Grok\n\t// Build's explicit `grok-4.6-build` pricing alias reaches this base rate.\n\t\"grok-4.6\": xai(flat(2, 6)),\n};\n\n/**\n * The constants above as dated rows. This is what the seed migration writes\n * into `modelPrices` and what the CLI prices against when the server's table\n * is out of reach. Cache tiers are rendered absolute here, once.\n */\nexport function bundledPriceTable(): PriceTable {\n\tconst rows: PriceRow[] = [];\n\tfor (const [modelSlug, entry] of Object.entries(PRICES)) {\n\t\tfor (const p of entry.periods) {\n\t\t\trows.push({\n\t\t\t\tmodelSlug,\n\t\t\t\tfrom: p.from ?? 0,\n\t\t\t\tinput: p.input,\n\t\t\t\toutput: p.output,\n\t\t\t\tcacheRead: p.input * entry.cache.read,\n\t\t\t\tcacheWrite5m: p.input * entry.cache.write5m,\n\t\t\t\tcacheWrite1h: p.input * entry.cache.write1h,\n\t\t\t\tsource: entry.table,\n\t\t\t\tvendor: entry.vendor,\n\t\t\t});\n\t\t}\n\t}\n\treturn { id: BUNDLED_PRICE_TABLE_ID, rows };\n}\n\nconst BUNDLED_INDEX = new PriceIndex(bundledPriceTable());\nconst BUNDLED_PRICER = new Pricer([BUNDLED_INDEX]);\n\n/** The pricer over the bundled constants alone. */\nexport function bundledPricer(): Pricer {\n\treturn BUNDLED_PRICER;\n}\n\n/**\n * A pricer that answers from `table` first and from the bundled constants for\n * every key the table lacks. The CLI installs the served table this way; the\n * backend builds the same shape over `modelPrices`.\n */\nexport function layeredPricer(\n\ttable: PriceTable,\n\tvendorHint?: (slug: string) => Vendor | null,\n): Pricer {\n\treturn new Pricer([new PriceIndex(table), BUNDLED_INDEX], vendorHint);\n}\n\n/**\n * The pricer the module-level functions below consult. The CLI's sync sets it\n * to the served table before scanning (#336) and every adapter prices through\n * it without knowing. Defaults to the bundled constants.\n */\nlet active: Pricer = BUNDLED_PRICER;\n\nexport function setActivePricer(pricer: Pricer | null): void {\n\tactive = pricer ?? BUNDLED_PRICER;\n}\n\n/** The ids of the tables the active pricer consults, served first. */\nexport function activePriceTableIds(): string[] {\n\treturn active.tableIds;\n}\n\n/**\n * Build the pricing key a multi-provider harness reports under. Pass the\n * harness's own provider id verbatim; this table decides what it means.\n */\nexport function modelKeyFor(provider: string, model: string): string {\n\treturn `${provider}${PROVIDER_SEPARATOR}${model}`;\n}\n\nexport type TokenCounts = {\n\tinput: number;\n\toutput: number;\n\tcacheWrite5m: number;\n\tcacheWrite1h: number;\n\t/** `cache_creation_input_tokens` not covered by the TTL breakdown; priced at the 5m rate. */\n\tcacheWriteUnsplit: number;\n\tcacheRead: number;\n};\n\n/**\n * Normalize an observed `message.model` into a pricing key. Handles the\n * dated-suffix variants (`claude-haiku-4-5-20251001`). The `#fast` suffix is\n * appended by the caller from `usage.speed`. A `provider:` prefix passes\n * through untouched, so a caller can normalize a composed key.\n */\nexport function normalizeModel(model: string): string {\n\tconst { provider, model: bare } = splitModelKey(model);\n\tconst [base, suffix] = bare.split(\"#\");\n\tconst stripped = base.replace(/-\\d{8}$/, \"\");\n\tconst normalized = suffix ? `${stripped}#${suffix}` : stripped;\n\treturn provider === null ? normalized : modelKeyFor(provider, normalized);\n}\n\n/**\n * Drop the analyzer's synthetic `#fast` suffix, leaving the id the payload\n * publishes.\n *\n * A `provider:` prefix SURVIVES this, and that is deliberate: the provider is\n * what tells `google:gemini-3-pro-preview` from\n * `github-copilot:gemini-3-pro-preview`, and the backend re-pricer needs that\n * difference at read time. Use `vendorModelId` where a human or the models\n * catalog needs the plain vendor id.\n */\nexport function baseModelId(modelKey: string): string {\n\treturn modelKey.split(\"#\")[0];\n}\n\n/**\n * The vendor-assigned id alone - no provider prefix, no `#fast`. This is the id\n * to show a reader and to match against the models catalog.\n */\nexport function vendorModelId(modelKey: string): string {\n\treturn splitModelKey(baseModelId(modelKey)).model;\n}\n\n/**\n * How this model's vendor charges for cache traffic, as ratios of the latest\n * period's input rate. Falls back to the Anthropic-shaped constants for a\n * model with no rate, so a caller that prices an unknown model still gets a\n * defined shape rather than a crash.\n */\nexport function cacheMultipliersFor(modelKey: string): CacheMultipliers {\n\tconst periods = active.periodsFor(modelKey);\n\tconst p = periods[periods.length - 1];\n\tif (!p) return DEFAULT_CACHE_MULTIPLIERS;\n\tif (p.input === 0) return { write5m: 0, write1h: 0, read: 0 };\n\t// Absolute rates back to ratios; rounded so 0.075 / 0.75 reads 0.1.\n\tconst ratio = (rate: number) => Math.round((rate / p.input) * 1e6) / 1e6;\n\treturn {\n\t\twrite5m: ratio(p.cacheWrite5m),\n\t\twrite1h: ratio(p.cacheWrite1h),\n\t\tread: ratio(p.cacheRead),\n\t};\n}\n\n/**\n * True when this key names a model that runs locally and therefore costs\n * nothing per token. A caller printing dollars uses this to say \"free\", never\n * \"unknown\".\n */\nexport function isLocalModel(modelKey: string): boolean {\n\treturn active.isLocal(modelKey);\n}\n\n/**\n * The rate in effect for `modelKey` at `atMs`, or `null` when the model is\n * unknown or the timestamp predates every period we can cite.\n *\n * A `null` timestamp also yields `null`: a record with no parseable timestamp\n * cannot be priced time-awarely, and inventing a price for it (say, today's)\n * would silently attribute the wrong rate. Its tokens surface as unpriced.\n */\nexport function priceAt(\n\tmodelKey: string,\n\tatMs: number | null,\n): PricePeriod | null {\n\treturn active.priceAt(modelKey, atMs);\n}\n\n/** True when we hold at least one citable rate for this model, at any time. */\nexport function isPricedModel(modelKey: string): boolean {\n\treturn active.isPriced(modelKey);\n}\n\n/**\n * The table id that cites this model's rates, or `null` when it has none.\n *\n * The citation belongs to the rate, not to the harness that reported it: a\n * read-time estimate is cited by the table it was drawn from, and one stack can\n * carry Anthropic and OpenAI rows at once.\n */\nexport function pricingTableFor(\n\tmodelKey: string,\n\tatMs?: number,\n): string | null {\n\treturn active.tableFor(modelKey, atMs);\n}\n\n/**\n * Every rate that applies to `modelKey` anywhere inside `[fromMs, toMs]`.\n *\n * This is the read-time counterpart of `priceAt`. A published snapshot has no\n * per-response timestamps left, so a re-pricer can only ask \"which rates could\n * this window have paid\", and then choose.\n */\nexport function pricePeriodsInWindow(\n\tmodelKey: string,\n\tfromMs: number,\n\ttoMs: number,\n): PricePeriod[] {\n\treturn active.periodsInWindow(modelKey, fromMs, toMs);\n}\n\n/** The dollars one period charges for these tokens. */\nexport function costAtPeriod(p: PricePeriod, t: TokenCounts): number {\n\tconst M = 1_000_000;\n\treturn (\n\t\t(t.input * p.input +\n\t\t\tt.output * p.output +\n\t\t\t(t.cacheWrite5m + t.cacheWriteUnsplit) * p.cacheWrite5m +\n\t\t\tt.cacheWrite1h * p.cacheWrite1h +\n\t\t\tt.cacheRead * p.cacheRead) /\n\t\tM\n\t);\n}\n\n/**\n * Cost of one response's tokens at the rate in effect at its own timestamp.\n * Returns `null` when no rate applies - the caller must surface that as\n * unpriced tokens rather than zeroing it.\n */\nexport function apiEquivalentCost(\n\tmodelKey: string,\n\tt: TokenCounts,\n\tatMs: number | null,\n): number | null {\n\tconst p = active.priceAt(modelKey, atMs);\n\tif (!p) return null;\n\treturn costAtPeriod(p, t);\n}\n","// Harness-agnostic aggregate machinery: the fold target every adapter fills,\n// and the finalize step that turns it into display-ready rows.\n//\n// Extracted from the Claude analyzer by ticket #67 (map #60) so the Codex\n// adapter can reuse the same totals, name hygiene, and model rows without\n// inheriting Claude's record-dedup logic. Everything here is pure - no I/O,\n// no console.\n\nimport { isPricedModel, type TokenCounts } from \"@aistack/pricing\";\n\n// ---------------------------------------------------------------------------\n// Narrowing helpers - records are untrusted external JSON\n// ---------------------------------------------------------------------------\n\nexport type Obj = Record<string, unknown>;\n\nexport const asObj = (v: unknown): Obj | null =>\n\ttypeof v === \"object\" && v !== null && !Array.isArray(v) ? (v as Obj) : null;\nexport const asStr = (v: unknown): string | null =>\n\ttypeof v === \"string\" && v.length > 0 ? v : null;\nexport const asNum = (v: unknown): number =>\n\ttypeof v === \"number\" && Number.isFinite(v) ? v : 0;\nexport const asArr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);\n\n/**\n * Every name that becomes a Map key or leaves this module goes through here.\n *\n * These are user-chosen strings (skill names, MCP servers, subagent types,\n * slash commands, model ids) and a hostile one is a real vector: control\n * characters move a terminal cursor, and an unterminated bidi override (U+202E)\n * reorders the rest of the rendered line - including the count and percentage\n * printed beside the name. Both survive `JSON.stringify`, which escapes C0 but\n * not bidi. See CVE-2021-42574 (\"Trojan Source\").\n *\n * Sanitizing at ingest rather than at print means the guarantee travels with\n * the module: `finalize()`'s output is safe for any consumer, not just the\n * renderer that happens to sit in front of it today.\n */\nconst NAME_UNSAFE_RE =\n\t// biome-ignore lint/suspicious/noControlCharactersInRegex: stripping them is the point\n\t/[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u061c\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2064\\u2066-\\u2069\\ufeff]/g;\nconst NAME_MAX = 64;\n\nexport function cleanName(s: string): string {\n\tconst stripped = s.replace(NAME_UNSAFE_RE, \"�\").trim();\n\tif (stripped.length === 0) return \"(unnamed)\";\n\treturn stripped.length > NAME_MAX\n\t\t? `${stripped.slice(0, NAME_MAX - 1)}…`\n\t\t: stripped;\n}\n\n/**\n * The same bar as `cleanName`, asked as a question.\n *\n * Used on names arriving from the NETWORK - the per-stack opt-ins the sync\n * config carries (#44). Those are the user's own strings, so the curated list's\n * conventional charset is the wrong bar: parentheses, accents and CJK are all\n * legitimate names someone runs. What is refused is what cannot be rendered\n * safely, which is exactly what `cleanName` strips on the way in.\n */\nexport function isDisplaySafeName(s: string): boolean {\n\tif (s.length === 0 || s.trim().length === 0) return false;\n\tif (s.length > NAME_MAX) return false;\n\t// A `g`-flagged regex carries `lastIndex` across `.test` calls, so this uses\n\t// a fresh non-global copy rather than the shared literal.\n\treturn !new RegExp(NAME_UNSAFE_RE.source).test(s);\n}\n\n/** `asStr` for anything that will be used as a name. */\nexport const asName = (v: unknown): string | null => {\n\tconst s = asStr(v);\n\treturn s === null ? null : cleanName(s);\n};\n\n// ---------------------------------------------------------------------------\n// Aggregate\n// ---------------------------------------------------------------------------\n\nexport type ModelUsage = TokenCounts & {\n\tmessages: number;\n\t/**\n\t * API-equivalent cost accumulated per response at that response's own rate\n\t * (#33 decision 8). Not derivable from the token totals above once a window\n\t * straddles a repricing.\n\t */\n\tcostUSD: number;\n\t/** Tokens whose own timestamp had no citable rate. Surfaced, never zeroed. */\n\tunpricedTokens: number;\n};\n\n/**\n * The fold target. `Seen` is the adapter's own dedup bookkeeping type -\n * Claude keys responses by `message.id`, Codex needs none - kept generic so\n * the shared shape does not import any one harness's record semantics.\n */\nexport type Aggregate<Seen = unknown> = {\n\t// provenance / scan health\n\tfiles: number;\n\tlines: number;\n\tparseErrors: number;\n\trecords: number;\n\tassistantRecords: number;\n\t/** Distinct API responses actually counted. */\n\tdistinctResponses: number;\n\t/** Extra records of a response already counted (same message.id AND requestId). */\n\tcontinuationsFolded: number;\n\t/** Same message.id under a NEW requestId - a genuine replay (e.g. /btw sidechain). */\n\trealReplaysFolded: number;\n\t/** Times a later record superseded an earlier one because it carried a larger total. */\n\tsupersededByLarger: number;\n\t/** Assistant records with no message.id - counted without dedup protection. */\n\tunkeyedResponses: number;\n\tsyntheticRecords: number;\n\tsyntheticTokens: number;\n\ttoolBlocksWithoutId: number;\n\t/** Responses whose first attempt ran on a different model (#33 decision 9). */\n\tfallbackAttempts: number;\n\tuntypedMirrors: number;\n\t/** Records with no parseable timestamp - cannot be priced time-awarely. */\n\tuntimestampedResponses: number;\n\tprojectDirs: Set<string>; // held only to count - names never leave this module\n\tccVersions: Set<string>;\n\tmirroredIterationTypes: Map<string, number>;\n\n\t// tokens\n\tbyModel: Map<string, ModelUsage>;\n\tsidechainTokens: number;\n\tmainTokens: number;\n\n\t// activity\n\tsessions: Set<string>;\n\tactiveDays: Set<string>; // UTC YYYY-MM-DD\n\tfirstTs: number | null;\n\tlastTs: number | null;\n\n\t// tools / skills / mcp / agents\n\ttoolCalls: Map<string, number>;\n\tskillCalls: Map<string, number>;\n\tmcpServerCalls: Map<string, number>;\n\tmcpToolCalls: Map<string, number>;\n\tsubagentCalls: Map<string, number>;\n\tslashCommands: Map<string, number>;\n\ttoolCallDedup: Set<string>;\n\n\t// content-block shape\n\tthinkingBlocks: number;\n\ttextBlocks: number;\n\twebSearchRequests: number;\n\twebFetchRequests: number;\n\n\t// adapter-owned dedup bookkeeping\n\tseen: Map<string, Seen>;\n\n\t// THE PER-DAY SEAM (#307, ADR-0010). The same response stream that fills\n\t// the window totals above also lands in one bucket per UTC date here, so a\n\t// fold over the days equals the window up to rounding. Nothing in these\n\t// maps is a share or a mean: `usage/days.ts` turns them into the wire.\n\tusageDays: Map<string, UsageDayAcc>;\n\t/** Session id -> earliest in-window timestamp. A session belongs to the day it STARTED. */\n\tsessionStarts: Map<string, number>;\n};\n\n/** One model's response sums inside one UTC day. */\nexport type UsageDayModel = {\n\tcounts: TokenCounts;\n\t/** Sum of the responses that had a citable rate at their own timestamp. */\n\tcostUSD: number;\n\t/** Tokens of the responses that had none. Surfaced, never zeroed. */\n\tunpricedTokens: number;\n};\n\nexport type UsageDayAcc = {\n\tmodels: Map<string, UsageDayModel>;\n\t/** Tokens of sidechain (subagent) responses, all models. */\n\tsubagentTokens: number;\n\tsyntheticTokens: number;\n\t/** Local project directories touched this day. Hashed before they leave. */\n\tprojectDirs: Set<string>;\n};\n\nexport const utcDateOf = (ms: number): string =>\n\tnew Date(ms).toISOString().slice(0, 10);\n\nfunction usageDayAcc(agg: Aggregate<never> | Aggregate<unknown>, tsMs: number) {\n\tconst date = utcDateOf(tsMs);\n\tlet day = agg.usageDays.get(date);\n\tif (!day) {\n\t\tday = {\n\t\t\tmodels: new Map(),\n\t\t\tsubagentTokens: 0,\n\t\t\tsyntheticTokens: 0,\n\t\t\tprojectDirs: new Set(),\n\t\t};\n\t\tagg.usageDays.set(date, day);\n\t}\n\treturn day;\n}\n\n/**\n * Land one response's tokens on the day of its own timestamp. `sign` is -1\n * when an adapter retracts a response it counted before (Claude's dedup). An\n * untimestamped response has no day and stays in the window totals only.\n */\nexport function noteUsageResponse(\n\tagg: Aggregate<never> | Aggregate<unknown>,\n\tresponse: {\n\t\ttsMs: number | null;\n\t\tmodelKey: string;\n\t\tcounts: TokenCounts;\n\t\tcostUSD: number | null;\n\t\tsidechain?: boolean;\n\t},\n\tsign: 1 | -1 = 1,\n): void {\n\tif (response.tsMs === null) return;\n\tconst day = usageDayAcc(agg, response.tsMs);\n\tlet m = day.models.get(response.modelKey);\n\tif (!m) {\n\t\tm = {\n\t\t\tcounts: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheWrite5m: 0,\n\t\t\t\tcacheWrite1h: 0,\n\t\t\t\tcacheWriteUnsplit: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t},\n\t\t\tcostUSD: 0,\n\t\t\tunpricedTokens: 0,\n\t\t};\n\t\tday.models.set(response.modelKey, m);\n\t}\n\tconst c = response.counts;\n\tm.counts.input += sign * c.input;\n\tm.counts.output += sign * c.output;\n\tm.counts.cacheWrite5m += sign * c.cacheWrite5m;\n\tm.counts.cacheWrite1h += sign * c.cacheWrite1h;\n\tm.counts.cacheWriteUnsplit += sign * c.cacheWriteUnsplit;\n\tm.counts.cacheRead += sign * c.cacheRead;\n\tif (response.costUSD === null) m.unpricedTokens += sign * countsTotal(c);\n\telse m.costUSD += sign * response.costUSD;\n\tif (response.sidechain) day.subagentTokens += sign * countsTotal(c);\n}\n\nexport function noteSyntheticTokens(\n\tagg: Aggregate<never> | Aggregate<unknown>,\n\ttsMs: number | null,\n\ttokens: number,\n): void {\n\tif (tsMs === null) return;\n\tusageDayAcc(agg, tsMs).syntheticTokens += tokens;\n}\n\n/** Remember the earliest timestamp seen for a session: that is the day it started. */\nexport function noteSessionStart(\n\tagg: Aggregate<never> | Aggregate<unknown>,\n\tsessionId: string,\n\ttsMs: number | null,\n): void {\n\tif (tsMs === null) return;\n\tconst held = agg.sessionStarts.get(sessionId);\n\tif (held === undefined || tsMs < held) agg.sessionStarts.set(sessionId, tsMs);\n}\n\n/** A project belongs to every day it was touched. */\nexport function noteProjectDay(\n\tagg: Aggregate<never> | Aggregate<unknown>,\n\tdirectory: string,\n\ttsMs: number | null,\n): void {\n\tif (tsMs === null) return;\n\tusageDayAcc(agg, tsMs).projectDirs.add(directory);\n}\n\nexport function createAggregate<Seen = unknown>(): Aggregate<Seen> {\n\treturn {\n\t\tfiles: 0,\n\t\tlines: 0,\n\t\tparseErrors: 0,\n\t\trecords: 0,\n\t\tassistantRecords: 0,\n\t\tdistinctResponses: 0,\n\t\tcontinuationsFolded: 0,\n\t\trealReplaysFolded: 0,\n\t\tsupersededByLarger: 0,\n\t\tunkeyedResponses: 0,\n\t\tsyntheticRecords: 0,\n\t\tsyntheticTokens: 0,\n\t\ttoolBlocksWithoutId: 0,\n\t\tfallbackAttempts: 0,\n\t\tuntypedMirrors: 0,\n\t\tuntimestampedResponses: 0,\n\t\tprojectDirs: new Set(),\n\t\tccVersions: new Set(),\n\t\tmirroredIterationTypes: new Map(),\n\t\tbyModel: new Map(),\n\t\tsidechainTokens: 0,\n\t\tmainTokens: 0,\n\t\tsessions: new Set(),\n\t\tactiveDays: new Set(),\n\t\tfirstTs: null,\n\t\tlastTs: null,\n\t\ttoolCalls: new Map(),\n\t\tskillCalls: new Map(),\n\t\tmcpServerCalls: new Map(),\n\t\tmcpToolCalls: new Map(),\n\t\tsubagentCalls: new Map(),\n\t\tslashCommands: new Map(),\n\t\ttoolCallDedup: new Set(),\n\t\tthinkingBlocks: 0,\n\t\ttextBlocks: 0,\n\t\twebSearchRequests: 0,\n\t\twebFetchRequests: 0,\n\t\tseen: new Map(),\n\t\tusageDays: new Map(),\n\t\tsessionStarts: new Map(),\n\t};\n}\n\nexport const bump = (m: Map<string, number>, k: string, n = 1) =>\n\tm.set(k, (m.get(k) ?? 0) + n);\n\nexport function emptyUsage(): ModelUsage {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheWrite5m: 0,\n\t\tcacheWrite1h: 0,\n\t\tcacheWriteUnsplit: 0,\n\t\tcacheRead: 0,\n\t\tmessages: 0,\n\t\tcostUSD: 0,\n\t\tunpricedTokens: 0,\n\t};\n}\n\nexport const countsTotal = (t: TokenCounts): number =>\n\tt.input +\n\tt.output +\n\tt.cacheWrite5m +\n\tt.cacheWrite1h +\n\tt.cacheWriteUnsplit +\n\tt.cacheRead;\n\n/**\n * Fold one priced usage delta into the per-model totals. The Claude adapter\n * has its own apply/retract pair (dedup can un-count a response); an adapter\n * whose records are already deltas - Codex - adds through here.\n */\nexport function addModelUsage(\n\tagg: Aggregate<never> | Aggregate<unknown>,\n\tmodelKey: string,\n\tcounts: TokenCounts,\n\tcostUSD: number | null,\n\tmessages = 1,\n\t/**\n\t * Where the response sits in time, for the per-day seam (#307). An adapter\n\t * that passes nothing keeps the window totals right and lands no day.\n\t */\n\tat?: { tsMs: number | null; sidechain?: boolean },\n): void {\n\tif (at) {\n\t\tnoteUsageResponse(agg, {\n\t\t\ttsMs: at.tsMs,\n\t\t\tmodelKey,\n\t\t\tcounts,\n\t\t\tcostUSD,\n\t\t\t...(at.sidechain ? { sidechain: true } : {}),\n\t\t});\n\t}\n\tlet m = agg.byModel.get(modelKey);\n\tif (!m) {\n\t\tm = emptyUsage();\n\t\tagg.byModel.set(modelKey, m);\n\t}\n\tm.messages += messages;\n\tm.input += counts.input;\n\tm.output += counts.output;\n\tm.cacheWrite5m += counts.cacheWrite5m;\n\tm.cacheWrite1h += counts.cacheWrite1h;\n\tm.cacheWriteUnsplit += counts.cacheWriteUnsplit;\n\tm.cacheRead += counts.cacheRead;\n\tif (costUSD === null) m.unpricedTokens += countsTotal(counts);\n\telse m.costUSD += costUSD;\n}\n\n// ---------------------------------------------------------------------------\n// Finalize - the shape the wire payload is derived from\n// ---------------------------------------------------------------------------\n\nexport type ModelRow = {\n\t/** Pricing key: normalized vendor id, plus `#fast` when speed was fast. */\n\tmodelKey: string;\n\ttokens: TokenCounts;\n\ttotalTokens: number;\n\tmessages: number;\n\tshare: number;\n\t/** Accumulated at each response's own rate. `null` when nothing was priced. */\n\tcostUSD: number | null;\n\t/** Tokens inside this row that no rate covered. */\n\tunpricedTokens: number;\n};\n\nexport type Finalized = {\n\tmodels: ModelRow[];\n\ttotalTokens: number;\n\ttotalCostUSD: number;\n\tunpricedModels: string[];\n\tunpricedTokens: number;\n\tcacheHitShare: number;\n\tsidechainShare: number;\n\tactiveDays: number;\n\tfirstTs: number | null;\n\tlastTs: number | null;\n\tsessions: number;\n\tprojects: number;\n\ttools: Array<[string, number]>;\n\tskills: Array<[string, number]>;\n\tmcpServers: Array<[string, number]>;\n\tsubagents: Array<[string, number]>;\n\tslashCommands: Array<[string, number]>;\n\ttotalToolCalls: number;\n\t/** Newest harness version observed, or null when none was recorded. */\n\tharnessVersion: string | null;\n};\n\nfunction buildModelRows(agg: Aggregate): {\n\trows: ModelRow[];\n\ttotalTokens: number;\n\ttotalCostUSD: number;\n\tunpricedModels: string[];\n\tunpricedTokens: number;\n} {\n\tconst rows: ModelRow[] = [];\n\tlet totalTokens = 0;\n\tlet totalCostUSD = 0;\n\tconst unpricedModels: string[] = [];\n\tlet unpricedTokens = 0;\n\n\tfor (const [modelKey, u] of agg.byModel) {\n\t\tconst tokens: TokenCounts = {\n\t\t\tinput: u.input,\n\t\t\toutput: u.output,\n\t\t\tcacheWrite5m: u.cacheWrite5m,\n\t\t\tcacheWrite1h: u.cacheWrite1h,\n\t\t\tcacheWriteUnsplit: u.cacheWriteUnsplit,\n\t\t\tcacheRead: u.cacheRead,\n\t\t};\n\t\tconst sum = countsTotal(tokens);\n\t\ttotalTokens += sum;\n\t\tif (u.unpricedTokens > 0) {\n\t\t\tunpricedModels.push(modelKey);\n\t\t\tunpricedTokens += u.unpricedTokens;\n\t\t}\n\t\ttotalCostUSD += u.costUSD;\n\t\trows.push({\n\t\t\tmodelKey,\n\t\t\ttokens,\n\t\t\ttotalTokens: sum,\n\t\t\tmessages: u.messages,\n\t\t\tshare: 0,\n\t\t\t// A model we hold no rate for at all reports null rather than $0.00,\n\t\t\t// so \"we can't price this\" never reads as \"this was free\".\n\t\t\tcostUSD: isPricedModel(modelKey) ? u.costUSD : null,\n\t\t\tunpricedTokens: u.unpricedTokens,\n\t\t});\n\t}\n\tfor (const r of rows) r.share = totalTokens ? r.totalTokens / totalTokens : 0;\n\trows.sort(\n\t\t(a, b) =>\n\t\t\tb.totalTokens - a.totalTokens || a.modelKey.localeCompare(b.modelKey),\n\t);\n\treturn { rows, totalTokens, totalCostUSD, unpricedModels, unpricedTokens };\n}\n\nfunction computeCacheHitShare(rows: ModelRow[]): number {\n\tlet cacheRead = 0;\n\tlet inputClass = 0;\n\tfor (const r of rows) {\n\t\tcacheRead += r.tokens.cacheRead;\n\t\tinputClass +=\n\t\t\tr.tokens.input +\n\t\t\tr.tokens.cacheRead +\n\t\t\tr.tokens.cacheWrite5m +\n\t\t\tr.tokens.cacheWrite1h +\n\t\t\tr.tokens.cacheWriteUnsplit;\n\t}\n\treturn inputClass ? cacheRead / inputClass : 0;\n}\n\n/**\n * Newest observed harness version, compared numerically per dotted segment\n * so `2.1.9` doesn't sort above `2.1.220`.\n */\nexport function newestVersion(versions: Iterable<string>): string | null {\n\tlet best: string | null = null;\n\tlet bestParts: number[] = [];\n\tfor (const v of versions) {\n\t\tconst parts = v.split(\".\").map((p) => Number.parseInt(p, 10));\n\t\tif (parts.some((n) => !Number.isFinite(n))) continue;\n\t\tif (best === null || compareParts(parts, bestParts) > 0) {\n\t\t\tbest = v;\n\t\t\tbestParts = parts;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction compareParts(a: number[], b: number[]): number {\n\tconst len = Math.max(a.length, b.length);\n\tfor (let i = 0; i < len; i++) {\n\t\tconst d = (a[i] ?? 0) - (b[i] ?? 0);\n\t\tif (d !== 0) return d;\n\t}\n\treturn 0;\n}\n\nexport function finalize(agg: Aggregate): Finalized {\n\tconst { rows, totalTokens, totalCostUSD, unpricedModels, unpricedTokens } =\n\t\tbuildModelRows(agg);\n\n\tconst byCount = (m: Map<string, number>): Array<[string, number]> =>\n\t\t[...m.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));\n\n\tlet totalToolCalls = 0;\n\tfor (const v of agg.toolCalls.values()) totalToolCalls += v;\n\tfor (const v of agg.mcpToolCalls.values()) totalToolCalls += v;\n\n\tconst sideTotal = agg.sidechainTokens + agg.mainTokens;\n\n\treturn {\n\t\tmodels: rows,\n\t\ttotalTokens,\n\t\ttotalCostUSD,\n\t\tunpricedModels,\n\t\tunpricedTokens,\n\t\tcacheHitShare: computeCacheHitShare(rows),\n\t\tsidechainShare: sideTotal ? agg.sidechainTokens / sideTotal : 0,\n\t\tactiveDays: agg.activeDays.size,\n\t\tfirstTs: agg.firstTs,\n\t\tlastTs: agg.lastTs,\n\t\tsessions: agg.sessions.size,\n\t\tprojects: agg.projectDirs.size,\n\t\ttools: byCount(agg.toolCalls),\n\t\tskills: byCount(agg.skillCalls),\n\t\tmcpServers: byCount(agg.mcpServerCalls),\n\t\tsubagents: byCount(agg.subagentCalls),\n\t\tslashCommands: byCount(agg.slashCommands),\n\t\ttotalToolCalls,\n\t\tharnessVersion: newestVersion(agg.ccVersions),\n\t};\n}\n","// The rolling window and the scan-health shape every adapter reports.\n// Shared so the payload builder and each harness scanner agree by import\n// rather than by convention (#67).\n\n/** Rolling window locked by the owner in the #32 prototype resolution. */\nexport const DEFAULT_WINDOW_DAYS = 30;\n\n/**\n * UTC midnight opening a rolling window of `days` calendar days ending on the\n * day containing `now` (inclusive). `days = 30` therefore spans today plus the\n * 29 preceding days.\n *\n * Defined once and shared by the scan filter and the payload's `window.from`, so\n * the reported window and the records actually counted cannot drift apart.\n */\nexport function windowStartMs(now: number, days: number): number {\n\tconst startOfToday = Date.UTC(\n\t\tnew Date(now).getUTCFullYear(),\n\t\tnew Date(now).getUTCMonth(),\n\t\tnew Date(now).getUTCDate(),\n\t);\n\treturn startOfToday - (days - 1) * 86_400_000;\n}\n\nexport type ScanStats = {\n\t/** Files found on disk before any window filter. */\n\tfilesFound: number;\n\t/** Files actually opened and read. */\n\tfilesRead: number;\n\t/** Files skipped because their mtime predates the window. */\n\tfilesSkippedByMtime: number;\n\t/** Files skipped because a resolved path was already scanned (overlapping roots). */\n\tfilesSkippedAsDuplicate: number;\n\t/**\n\t * Files that could not be read (permissions, or pruned mid-scan). Counted\n\t * rather than thrown: an unhandled read error would surface the absolute path\n\t * AND the munged project directory in the crash output, which is exactly what\n\t * this tool promises never to emit.\n\t */\n\tfilesUnreadable: number;\n\t/**\n\t * Files excluded because they fail the genuine-rollout fingerprint (#73):\n\t * another tool wrote them into the harness's log directory, so their usage\n\t * would distort the numbers. Codex sets this; Claude has no known impostors.\n\t */\n\tfilesForeign: number;\n\t/**\n\t * LOCAL-ONLY detail behind the counts above. `buildPayload` copies coverage\n\t * fields one by one, so nothing below can reach the wire.\n\t *\n\t * `session_meta.originator` values seen on foreign files, value → file count.\n\t */\n\tforeignOriginators: Map<string, number>;\n\t/** LOCAL-ONLY: one `{path relative to the scan root, error class}` per unreadable file. */\n\tunreadableFiles: Array<{ path: string; reason: string }>;\n\t/** Subset of `filesUnreadable`: `.zst` rollouts this Node runtime cannot decompress. */\n\tfilesZstdUnsupported: number;\n};\n\nexport function emptyScanStats(): ScanStats {\n\treturn {\n\t\tfilesFound: 0,\n\t\tfilesRead: 0,\n\t\tfilesSkippedByMtime: 0,\n\t\tfilesSkippedAsDuplicate: 0,\n\t\tfilesUnreadable: 0,\n\t\tfilesForeign: 0,\n\t\tforeignOriginators: new Map(),\n\t\tunreadableFiles: [],\n\t\tfilesZstdUnsupported: 0,\n\t};\n}\n","import type { Message, Session } from \"cursor-history\";\nimport { asObj, asStr } from \"../shared/aggregate.js\";\n\nexport type Buckets = {\n\tinput?: number;\n\toutput?: number;\n\tcacheRead?: number;\n\tcacheWrite?: number;\n};\nexport type TokenEvidence = Buckets & {\n\tinputSource?: \"reported\" | \"context\" | \"dry-run\" | \"text\";\n\toutputSource?: \"reported\" | \"text\";\n};\nexport type Contribution = {\n\tsession: string;\n\tid?: string;\n\tnativeId?: string;\n\ttsMs: number;\n\tmodel: string;\n\tbuckets: TokenEvidence;\n\tsource: \"api\" | \"local\";\n\tsidechain?: boolean;\n};\nexport type LocalSession = {\n\tsession: Session;\n\t/** Keyed raw token scalars only. The reader's flattened pair loses zero/presence. */\n\ttokens: Map<string, TokenEvidence>;\n};\n\nexport function timestamp(value: unknown): number | null {\n\tconst n =\n\t\ttypeof value === \"number\"\n\t\t\t? value\n\t\t\t: typeof value === \"string\"\n\t\t\t\t? /^\\d+$/.test(value)\n\t\t\t\t\t? Number(value)\n\t\t\t\t\t: Date.parse(value)\n\t\t\t\t: NaN;\n\treturn Number.isFinite(n) && n > 0 && n < 8.64e15 ? n : null;\n}\nexport function count(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0\n\t\t? value\n\t\t: undefined;\n}\n\n/** Direct buckets win individually, including explicit zero. No cents conversion. */\nexport function tokenEvidence(value: unknown): TokenEvidence {\n\tconst raw = asObj(value) ?? {};\n\tconst direct = asObj(raw.tokenCount);\n\tconst usage = asObj(raw.usage);\n\tfor (const [obj, fields] of [\n\t\t[\n\t\t\tdirect,\n\t\t\t[\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\"],\n\t\t],\n\t\t[\n\t\t\tusage,\n\t\t\t[\n\t\t\t\t\"input_tokens\",\n\t\t\t\t\"output_tokens\",\n\t\t\t\t\"cache_read_input_tokens\",\n\t\t\t\t\"cache_creation_input_tokens\",\n\t\t\t],\n\t\t],\n\t] as const) {\n\t\tfor (const field of fields)\n\t\t\tif (obj?.[field] != null && count(obj[field]) === undefined)\n\t\t\t\tthrow new Error(\"Invalid Cursor token evidence\");\n\t}\n\tconst out: TokenEvidence = {};\n\tout.input = count(direct?.inputTokens) ?? count(usage?.input_tokens);\n\tout.output = count(direct?.outputTokens) ?? count(usage?.output_tokens);\n\tout.cacheRead =\n\t\tcount(direct?.cacheReadTokens) ?? count(usage?.cache_read_input_tokens);\n\tout.cacheWrite =\n\t\tcount(direct?.cacheWriteTokens) ??\n\t\tcount(usage?.cache_creation_input_tokens);\n\tif (out.input !== undefined) out.inputSource = \"reported\";\n\tif (out.output !== undefined) out.outputSource = \"reported\";\n\tif (out.input === undefined) {\n\t\tconst context = count(asObj(raw.contextWindowStatusAtCreation)?.tokensUsed);\n\t\tif (context !== undefined) {\n\t\t\tout.input = context;\n\t\t\tout.inputSource = \"context\";\n\t\t} else if (typeof raw.promptDryRunInfo === \"string\") {\n\t\t\ttry {\n\t\t\t\tconst dry = asObj(JSON.parse(raw.promptDryRunInfo));\n\t\t\t\tconst estimate =\n\t\t\t\t\tcount(asObj(dry?.fullConversationTokenCount)?.numTokens) ??\n\t\t\t\t\tcount(asObj(dry?.userMessageTokenCount)?.numTokens);\n\t\t\t\tif (estimate !== undefined) {\n\t\t\t\t\tout.input = estimate;\n\t\t\t\t\tout.inputSource = \"dry-run\";\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t/* optional estimate */\n\t\t\t}\n\t\t}\n\t}\n\treturn out;\n}\n\nconst directTimes = new Set([\n\t\"composer-created-at\",\n\t\"composer-timing\",\n\t\"store-turn-timing\",\n]);\n/** Interpolate only date attribution. This does not establish call latency. */\nexport function messageTimes(\n\tsession: Session,\n\tapi: Contribution[] = [],\n): Array<number | null> {\n\tconst times = session.messages.map((m) =>\n\t\tdirectTimes.has(m.timestampSource ?? \"\") ? timestamp(m.timestamp) : null,\n\t);\n\tconst anchors: Array<{ index: number; time: number }> = [];\n\tfor (const [index, time] of times.entries())\n\t\tif (time !== null) anchors.push({ index, time });\n\tconst start =\n\t\tsession.createdAtSource !== \"epoch-unknown\"\n\t\t\t? timestamp(session.timestamp)\n\t\t\t: null;\n\tconst end =\n\t\tsession.lastUpdatedAtSource !== \"epoch-unknown\"\n\t\t\t? timestamp(session.metadata?.lastModified)\n\t\t\t: null;\n\tconst apiTimes = api\n\t\t.filter((e) => e.session === session.id)\n\t\t.map((e) => e.tsMs);\n\tif (!anchors.some((a) => a.index === 0)) {\n\t\tconst time = start ?? (apiTimes.length ? Math.min(...apiTimes) : null);\n\t\tif (time !== null) anchors.unshift({ index: -1, time });\n\t}\n\tconst last = session.messages.length;\n\tif (last && !anchors.some((a) => a.index === last - 1)) {\n\t\tconst time = end ?? (apiTimes.length ? Math.max(...apiTimes) : null);\n\t\tif (time !== null) anchors.push({ index: last, time });\n\t}\n\tfor (let i = 0; i < times.length; i++) {\n\t\tif (times[i] !== null) continue;\n\t\tconst before = anchors.filter((a) => a.index < i).at(-1);\n\t\tconst after = anchors.find((a) => a.index > i);\n\t\tif (before && after && after.time >= before.time)\n\t\t\ttimes[i] = Math.round(\n\t\t\t\tbefore.time +\n\t\t\t\t\t((after.time - before.time) * (i - before.index)) /\n\t\t\t\t\t\t(after.index - before.index),\n\t\t\t);\n\t\telse times[i] = before?.time ?? after?.time ?? null;\n\t}\n\treturn times;\n}\n\nexport function localContributions(\n\tlocal: LocalSession,\n\tapi: Contribution[] = [],\n): Contribution[] {\n\tconst { session, tokens } = local;\n\tconst times = messageTimes(session, api);\n\tconst out: Contribution[] = [];\n\tlet pending: Message | undefined;\n\tconst seen = new Set<string>();\n\tfor (const [i, message] of session.messages.entries()) {\n\t\tif (message.id && seen.has(message.id)) continue;\n\t\tif (message.id) seen.add(message.id);\n\t\tif (message.role === \"user\") {\n\t\t\tpending = message;\n\t\t\tcontinue;\n\t\t}\n\t\tconst own = tokens.get(message.id ?? \"\") ?? {};\n\t\tconst user = tokens.get(pending?.id ?? \"\") ?? {};\n\t\tconst input = own.input !== undefined ? own : user;\n\t\tconst buckets: TokenEvidence = {\n\t\t\t...own,\n\t\t\tinput:\n\t\t\t\tinput.input ??\n\t\t\t\t(pending ? Math.ceil(pending.content.length / 4) : undefined),\n\t\t\tinputSource: input.inputSource ?? (pending ? \"text\" : undefined),\n\t\t\toutput: own.output ?? Math.ceil(message.content.length / 4),\n\t\t\toutputSource: own.outputSource ?? \"text\",\n\t\t};\n\t\tpending = undefined;\n\t\tconst tsMs = times[i];\n\t\tif (tsMs === null) continue;\n\t\tout.push({\n\t\t\tsession: session.id,\n\t\t\t...(message.id ? { id: message.id } : {}),\n\t\t\t...(message.identityOrigin === \"composer-native\" && message.id\n\t\t\t\t? { nativeId: message.id }\n\t\t\t\t: {}),\n\t\t\ttsMs,\n\t\t\tmodel: asStr(message.model) ?? \"unknown\",\n\t\t\tbuckets,\n\t\t\tsource: \"local\",\n\t\t\t...(message.isSidechain ? { sidechain: true } : {}),\n\t\t});\n\t}\n\treturn out;\n}\n\n/** API events without a response join supersede the conversation's UTC-day total. */\nexport function reconcile(\n\tlocal: Contribution[],\n\tapi: Contribution[],\n): Contribution[] {\n\tconst grain = (c: Contribution) =>\n\t\t`${c.session}\\0${new Date(c.tsMs).toISOString().slice(0, 10)}`;\n\tconst reported = api.filter((row) =>\n\t\tObject.values(row.buckets).some((value) => typeof value === \"number\"),\n\t);\n\tconst grains = new Set(reported.map(grain));\n\treturn [...local.filter((c) => !grains.has(grain(c))), ...reported];\n}\n"],"mappings":";;;AAKA,SAAS,YAAY,kBAAkB;;;ACQvC,IAAI,OAAwC;AAC5C,IAAI,cAAc;AAElB,IAAM,aAAa,CAAC,SAAiB;AACpC,UAAQ,OAAO,MAAM,GAAG,IAAI;AAAA,CAAI;AACjC;AAQO,SAAS,YACf,QAAgC,YAChC,MAAoB,MAAM,YAAY,IAAI,GACnC;AACP,SAAO;AACP,gBAAc,IAAI;AACnB;AA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