opencode-usage-insights 0.3.1 → 0.4.1

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.
Files changed (57) hide show
  1. package/README.md +67 -542
  2. package/dist/core.d.ts +15 -1
  3. package/dist/gui-experimental.cjs +3 -3
  4. package/dist/index.d.ts +0 -47
  5. package/dist/index.js +1734 -1209
  6. package/dist/index.js.map +23 -16
  7. package/dist/line.d.ts +1 -0
  8. package/dist/panel-data.d.ts +9 -2
  9. package/dist/recorder.d.ts +1 -0
  10. package/dist/rpc.d.ts +4 -4
  11. package/dist/rpc.js +5 -5
  12. package/dist/rpc.js.map +3 -3
  13. package/dist/settings-client.d.ts +29 -0
  14. package/dist/settings-rpc.d.ts +746 -0
  15. package/dist/settings.d.ts +114 -0
  16. package/dist/sidebar.d.ts +3 -3
  17. package/dist/stats/aggregates.d.ts +15 -3
  18. package/dist/stats/constants.d.ts +7 -0
  19. package/dist/stats/db.d.ts +8 -128
  20. package/dist/stats/legacy.d.ts +25 -0
  21. package/dist/stats/maintenance.d.ts +1 -1
  22. package/dist/stats/migrate.d.ts +7 -0
  23. package/dist/stats/ndjson.d.ts +16 -0
  24. package/dist/stats/open.d.ts +15 -0
  25. package/dist/stats/paths.d.ts +5 -4
  26. package/dist/stats/queries.d.ts +30 -35
  27. package/dist/stats/records.d.ts +94 -0
  28. package/dist/stats/schema.d.ts +26 -0
  29. package/dist/stats-client.d.ts +9 -0
  30. package/dist/stats-worker.js +597 -367
  31. package/dist/stats-worker.js.map +17 -12
  32. package/dist/text.d.ts +2 -0
  33. package/dist/tui-settings.d.ts +18 -0
  34. package/dist/tui.d.ts +1 -57
  35. package/dist/tui.js +974 -158
  36. package/dist/tui.js.map +17 -13
  37. package/docs/cli.md +24 -0
  38. package/docs/configuration.md +108 -0
  39. package/docs/costs.md +44 -0
  40. package/docs/demo.md +94 -68
  41. package/docs/desktop.md +91 -0
  42. package/docs/images/desktop-overview-annotated.png +0 -0
  43. package/docs/images/desktop-overview.png +0 -0
  44. package/docs/images/desktop-settings.png +0 -0
  45. package/docs/images/desktop-turns-go-annotated.png +0 -0
  46. package/docs/images/desktop-turns.png +0 -0
  47. package/docs/images/line.png +0 -0
  48. package/docs/images/panel-cache.png +0 -0
  49. package/docs/images/panel-help.png +0 -0
  50. package/docs/images/panel-latency.png +0 -0
  51. package/docs/images/panel-overview.png +0 -0
  52. package/docs/images/panel-providers.png +0 -0
  53. package/docs/images/sidebar.png +0 -0
  54. package/docs/internals.md +87 -36
  55. package/docs/privacy.md +60 -0
  56. package/docs/tui.md +175 -0
  57. package/package.json +8 -7
@@ -1,23 +1,28 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/stats/db.ts", "../src/stats/paths.ts", "../src/text.ts", "../src/service.ts", "../src/limits.ts", "../src/core.ts", "../src/stats/queries.ts", "../src/stats/aggregates.ts", "../src/quota.ts", "../src/panel-data.ts", "../src/panel-build.ts", "../src/pricing.ts", "../src/stats/maintenance.ts", "../src/stats-worker.ts"],
3
+ "sources": ["../src/stats/schema.ts", "../src/stats/open.ts", "../src/stats/paths.ts", "../src/stats/constants.ts", "../src/stats/legacy.ts", "../src/text.ts", "../src/stats/records.ts", "../src/stats/migrate.ts", "../src/service.ts", "../src/limits.ts", "../src/core.ts", "../src/stats/queries.ts", "../src/stats/aggregates.ts", "../src/quota.ts", "../src/panel-data.ts", "../src/panel-build.ts", "../src/pricing.ts", "../src/stats/maintenance.ts", "../src/stats-worker.ts"],
4
4
  "sourcesContent": [
5
- "import { Database } from \"bun:sqlite\"\nimport { chmodSync, mkdirSync } from \"node:fs\"\nimport { dirname } from \"node:path\"\nimport { ensureRegularFile } from \"./paths\"\nimport { isToken, sanitizeLabel, TEXT_LIMIT } from \"../text\"\n\n/**\n * Persistent usage store. One SQLite database holds every recorded step,\n * prompt, event and session row — and nothing else: the recorder only writes\n * what a view reads.\n *\n * The database is opened in WAL mode with a busy timeout so the server\n * recorder process and the TUI reader process can share it safely. The two\n * sides open it differently on purpose:\n *\n * - `openStatsDb` writes: schema, migrations and recording (the server).\n * - `openStatsDbReadOnly` only reads (the TUI), so no view can change the file\n * and no reader pays for a schema write.\n * - `openStatsDbWrite` is a short-lived maintenance connection (prune, wipe, vacuum)\n * that gives up quickly instead of holding the recorder up.\n */\n\nexport const SCHEMA_VERSION = 11\n\n/** Longest title or path kept: a label on a line, not a document. */\nconst LABEL_LIMIT = 4 * TEXT_LIMIT\n\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS sessions (\n session_id TEXT PRIMARY KEY,\n parent_id TEXT,\n directory TEXT,\n title TEXT,\n started_at INTEGER,\n updated_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n session_id TEXT NOT NULL,\n message_id TEXT NOT NULL,\n created_at INTEGER,\n PRIMARY KEY (session_id, message_id)\n);\nCREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);\n\nCREATE TABLE IF NOT EXISTS steps (\n message_id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n parent_id TEXT,\n provider_id TEXT,\n model_id TEXT,\n variant TEXT,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n reasoning_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read INTEGER NOT NULL DEFAULT 0,\n cache_write INTEGER NOT NULL DEFAULT 0,\n cost REAL NOT NULL DEFAULT 0,\n list_cost REAL,\n created_at INTEGER,\n streamed_at INTEGER,\n completed_at INTEGER,\n finish TEXT,\n recorded_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS steps_session ON steps(session_id, created_at);\nCREATE INDEX IF NOT EXISTS steps_model ON steps(provider_id, model_id, variant);\nCREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);\n-- Every range filter and every ordering compares the step's own clock, which\n-- falls back to the recording time for a step that was already in flight when\n-- the plugin loaded. The index has to cover that expression, or every ranged\n-- view is a full table scan.\nCREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));\nCREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));\n\nCREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n kind TEXT NOT NULL,\n message_id TEXT,\n at INTEGER,\n data TEXT\n);\nCREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);\nCREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);\n\n-- Usage the host reports with no assistant step of its own: the compaction\n-- summarisation and the session-title generation. The host publishes it as\n-- session.usage.recorded with a source other than generate, and includes it in\n-- the session's own cost/token totals. Primary key is the host event ID, so a\n-- replayed event never counts twice.\nCREATE TABLE IF NOT EXISTS usage (\n id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n source TEXT NOT NULL,\n at INTEGER,\n cost REAL NOT NULL DEFAULT 0,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n reasoning_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read INTEGER NOT NULL DEFAULT 0,\n cache_write INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);\nCREATE INDEX IF NOT EXISTS usage_at ON usage(at);\n`\n\n/** Tables carried by `exportNdjson` / `importNdjson`, in import-safe order. */\nexport const TABLES = [\"sessions\", \"prompts\", \"events\", \"steps\", \"usage\"] as const\n\nexport type TableName = (typeof TABLES)[number]\n\nexport type StepRecord = {\n messageID: string\n sessionID: string\n parentID?: string | undefined\n /** The provider the model ran through, as OpenCode configured it (`opencode-go`). */\n providerID?: string | undefined\n modelID?: string | undefined\n variant?: string | undefined\n input?: number | undefined\n output?: number | undefined\n reasoning?: number | undefined\n cacheRead?: number | undefined\n cacheWrite?: number | undefined\n cost?: number | undefined\n /**\n * List-price estimate for a step the host reported as costing nothing.\n * `0` means a known free model; `NULL` means charged money or an unknown\n * price.\n */\n listCost?: number | undefined\n createdAt?: number | undefined\n streamedAt?: number | undefined\n completedAt?: number | undefined\n finish?: string | undefined\n /** Clock of the recording itself, defaults to `Date.now()`. */\n recordedAt?: number | undefined\n}\n\nexport type PromptRecord = {\n sessionID: string\n messageID: string\n createdAt?: number | undefined\n}\n\nexport type EventRecord = {\n sessionID: string\n kind: string\n messageID?: string | undefined\n at?: number | undefined\n data?: unknown\n}\n\n/**\n * Usage with no assistant step behind it (a compaction or a title generation).\n * `id` is the host event ID: it is the primary key, so a replay is ignored\n * instead of counted again.\n */\nexport type UsageRecord = {\n id: string\n sessionID: string\n source: string\n at?: number | undefined\n cost?: number | undefined\n input?: number | undefined\n output?: number | undefined\n reasoning?: number | undefined\n cacheRead?: number | undefined\n cacheWrite?: number | undefined\n}\n\nexport type SessionRecord = {\n sessionID: string\n parentID?: string | undefined\n directory?: string | undefined\n title?: string | undefined\n startedAt?: number | undefined\n updatedAt?: number | undefined\n}\n\nfunction jsonText(value: unknown): string | null {\n if (value === undefined || value === null) return null\n if (typeof value === \"string\") return value\n try {\n return JSON.stringify(value)\n } catch {\n return null\n }\n}\n\n/**\n * Numeric fields arrive from the host event stream, which the plugin treats as\n * untrusted: a single `NaN` bound to a NOT NULL column makes SQLite reject the\n * whole statement, and the recorder's defensive catch would then silently lose\n * the step. Every number is therefore forced into a finite, non-negative value\n * before it reaches the database.\n */\nfunction finite(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0\n}\n\nfunction tokenCount(value: unknown): number {\n return Math.max(0, Math.floor(finite(value)))\n}\n\nfunction timestamp(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null\n}\n\n/**\n * Columns and tables the recorder used to write and no view ever read. They are\n * dropped from an existing database, together with the rows of the events that\n * followed the same fate, so a long-lived file shrinks instead of carrying dead\n * weight forever.\n *\n * `router` is here because the gateway that named the routing endpoint in a\n * response header (`x-opencode-endpoint-id`) stopped naming one: the identity a\n * step is grouped by is the provider the model ran through, and the endpoint a\n * gateway happened to route to is no longer observable at all.\n */\nconst REMOVED_COLUMNS = [\"provider_state\", \"upstream\", \"upstream_source\", \"upstream_model\", \"tps\", \"router\"] as const\nconst REMOVED_EVENT_KINDS = [\"execution\", \"step-failed\", \"model-selected\", \"usage-recorded\"] as const\n\nfunction dropUnused(db: Database): void {\n const objects = db.query(\"SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')\").all() as {\n name: string\n type: string\n }[]\n const tables = new Set(objects.filter((row) => row.type === \"table\").map((row) => row.name))\n const indexes = new Set(objects.filter((row) => row.type === \"index\").map((row) => row.name))\n\n if (tables.has(\"http_responses\")) db.exec(\"DROP TABLE http_responses\")\n // These indexes read a column that is about to go: SQLite refuses to drop an\n // indexed column, so the index goes first.\n if (indexes.has(\"steps_upstream\")) db.exec(\"DROP INDEX steps_upstream\")\n if (indexes.has(\"steps_router\")) db.exec(\"DROP INDEX steps_router\")\n\n const columns = new Set((db.query(\"PRAGMA table_info(steps)\").all() as { name: string }[]).map((column) => column.name))\n for (const name of REMOVED_COLUMNS) {\n if (columns.has(name)) db.exec(`ALTER TABLE steps DROP COLUMN ${name}`)\n }\n\n if (tables.has(\"events\")) {\n const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(\", \")\n db.exec(`DELETE FROM events WHERE kind IN (${kinds})`)\n }\n}\n\n/**\n * Add the columns a newer recorder writes. `CREATE TABLE IF NOT EXISTS` does\n * not touch a table that already exists, so a column added to `SCHEMA` after a\n * database was created has to be added here too. The check is idempotent and\n * also heals a database a half-applied run left behind.\n */\nfunction addMissing(db: Database): void {\n const columns = new Set((db.query(\"PRAGMA table_info(steps)\").all() as { name: string }[]).map((column) => column.name))\n if (columns.size > 0 && !columns.has(\"list_cost\")) {\n db.exec(\"ALTER TABLE steps ADD COLUMN list_cost REAL\")\n }\n}\n\n/**\n * Older recorders inserted a compaction event on every delivery, and the host\n * replays events on reconnect: the same compaction can be stored several times.\n * Keep one row per exact duplicate before the unique key is installed, so the\n * event count and any future cost aggregation stay honest.\n */\nfunction dedupeEvents(db: Database): void {\n const table = db.query(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'\").get()\n if (table === null) return\n db.exec(`DELETE FROM events\n WHERE kind = 'compaction' AND message_id IS NULL\n AND rowid NOT IN (\n SELECT MIN(rowid) FROM events\n WHERE kind = 'compaction' AND message_id IS NULL\n GROUP BY session_id, at, data\n )`)\n db.exec(`DELETE FROM events\n WHERE message_id IS NOT NULL\n AND rowid NOT IN (\n SELECT MIN(rowid) FROM events\n WHERE message_id IS NOT NULL\n GROUP BY kind, message_id\n )`)\n}\n\n/**\n * A host event ID identifies one event: a replay must not insert a second row.\n * The index is partial because historical rows carry no ID.\n */\nfunction addEventKey(db: Database): void {\n const table = db.query(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'\").get()\n if (table === null) return\n db.exec(\"CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL\")\n}\n\n/**\n * Older recorders kept only the compaction event, never `session.usage.recorded`.\n * The event's payload already carries the cost and tokens, so recovering it\n * makes the fix retroactive for compactions. A row gets a stable synthetic ID;\n * `INSERT OR IGNORE` makes the recovery idempotent. Only historical rows\n * (`message_id IS NULL`) are considered: from this version on the recorder\n * stores the usage event itself, and backfilling again would count it twice.\n */\nfunction backfillCompactionUsage(db: Database): void {\n const tables = new Set(\n (db.query(\"SELECT name FROM sqlite_master WHERE type = 'table'\").all() as { name: string }[]).map((row) => row.name),\n )\n if (!tables.has(\"events\") || !tables.has(\"usage\")) return\n db.exec(`INSERT OR IGNORE INTO usage (\n id, session_id, source, at, cost,\n input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write\n )\n SELECT 'compaction:' || rowid, session_id, 'compaction', at,\n MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),\n MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),\n MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),\n MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),\n MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),\n MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))\n FROM events\n WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL\n AND json_valid(data)`)\n}\n\n/**\n * Bring an existing file up to date: drop what no view reads, add what a newer\n * recorder writes, repair the event log a replayed write duplicated, and\n * recover the compaction usage older versions left in the event payload. Every\n * step is idempotent.\n */\nfunction migrate(db: Database): void {\n dropUnused(db)\n addMissing(db)\n dedupeEvents(db)\n backfillCompactionUsage(db)\n addEventKey(db)\n}\n\n/**\n * The file holds session titles, project directories and usage history, so it\n * is created for the user alone. Windows takes its access from the parent\n * directory's ACL, which is not something a plugin should rewrite.\n */\nconst POSIX = process.platform !== \"win32\"\n\nfunction hardenDirectory(path: string): void {\n if (!POSIX) return\n try {\n chmodSync(path, 0o700)\n } catch {\n // A shared or read-only directory: the database is still usable.\n }\n}\n\nfunction hardenFiles(path: string): void {\n if (!POSIX || path === \":memory:\") return\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600)\n } catch {\n // The WAL and the shared-memory file are created on the first write and\n // removed on the last close, so one of them is often simply absent.\n }\n }\n}\n\n/** Directory for a database path, created private on POSIX. */\nfunction prepareDirectory(path: string): void {\n if (path === \":memory:\") return\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n hardenDirectory(dirname(path))\n}\n\n/** Open (creating when needed) the stats database and apply the schema. */\nexport function openStatsDb(path: string): Database {\n if (path !== \":memory:\") ensureRegularFile(path)\n prepareDirectory(path)\n const db = new Database(path, { create: true })\n db.exec(\"PRAGMA journal_mode = WAL\")\n db.exec(\"PRAGMA busy_timeout = 5000\")\n db.exec(\"PRAGMA synchronous = NORMAL\")\n db.exec(SCHEMA)\n migrate(db)\n db.query(\"INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\").run(\n String(SCHEMA_VERSION),\n )\n // The schema write is what creates the WAL and its shared-memory file.\n hardenFiles(path)\n return db\n}\n\n/**\n * Reader connection for the TUI: no schema, no migration, no write. It throws\n * when the database is absent or was never written by the recorder, so the\n * caller can say so instead of showing an empty panel.\n */\nexport function openStatsDbReadOnly(path: string): Database {\n ensureRegularFile(path)\n const db = new Database(path, { readonly: true })\n try {\n db.query(\"SELECT 1 FROM steps LIMIT 1\").get()\n } catch (error) {\n db.close()\n throw error\n }\n return db\n}\n\n/**\n * Short-lived write connection for maintenance. The busy timeout is short on\n * purpose: a prune, wipe or vacuum that cannot take the lock must fail in front of\n * the user, not hold the recorder's response path for seconds.\n */\nexport function openStatsDbWrite(path: string): Database {\n if (path !== \":memory:\") ensureRegularFile(path)\n prepareDirectory(path)\n const db = new Database(path, { create: true })\n db.exec(\"PRAGMA busy_timeout = 250\")\n db.exec(\"PRAGMA synchronous = NORMAL\")\n hardenFiles(path)\n return db\n}\n\n/**\n * Insert or refresh an assistant step. Idempotent by message ID so replayed\n * events, restarts and NDJSON imports never duplicate usage. A non-null field\n * (the provider, the model, the finish reason) survives a re-record with `NULL`\n * through COALESCE. `list_cost` follows the opposite rule: a step that becomes\n * charged loses its estimate, and an estimate survives a replay that carries\n * no price table.\n *\n * The provider is the identity every view groups by, so it is validated as a\n * token before it is stored: a value that is not a provider id is recorded as\n * absent instead of becoming a grouping key.\n */\nexport function recordStep(db: Database, record: StepRecord): void {\n const cost = Math.max(0, finite(record.cost))\n const listCost =\n cost <= 0 && typeof record.listCost === \"number\" && Number.isFinite(record.listCost) && record.listCost >= 0\n ? record.listCost\n : null\n db.query(\n `INSERT INTO steps (\n message_id, session_id, parent_id, provider_id, model_id, variant,\n input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,\n created_at, streamed_at, completed_at, finish, recorded_at\n ) VALUES (\n $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,\n $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,\n $createdAt, $streamedAt, $completedAt, $finish, $recordedAt\n )\n ON CONFLICT(message_id) DO UPDATE SET\n session_id = excluded.session_id,\n parent_id = COALESCE(excluded.parent_id, steps.parent_id),\n provider_id = COALESCE(excluded.provider_id, steps.provider_id),\n model_id = COALESCE(excluded.model_id, steps.model_id),\n variant = COALESCE(excluded.variant, steps.variant),\n input_tokens = excluded.input_tokens,\n output_tokens = excluded.output_tokens,\n reasoning_tokens = excluded.reasoning_tokens,\n cache_read = excluded.cache_read,\n cache_write = excluded.cache_write,\n cost = excluded.cost,\n -- A step that starts being charged loses its estimate; an estimate is\n -- kept when a replayed event arrives without a price table.\n list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,\n created_at = COALESCE(excluded.created_at, steps.created_at),\n streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),\n completed_at = COALESCE(excluded.completed_at, steps.completed_at),\n finish = COALESCE(excluded.finish, steps.finish),\n recorded_at = excluded.recorded_at`,\n ).run({\n $messageID: record.messageID,\n $sessionID: record.sessionID,\n $parentID: record.parentID ?? null,\n $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,\n $modelID: record.modelID ?? null,\n $variant: record.variant ?? null,\n $input: tokenCount(record.input),\n $output: tokenCount(record.output),\n $reasoning: tokenCount(record.reasoning),\n $cacheRead: tokenCount(record.cacheRead),\n $cacheWrite: tokenCount(record.cacheWrite),\n $cost: cost,\n $listCost: listCost,\n $createdAt: timestamp(record.createdAt),\n $streamedAt: timestamp(record.streamedAt),\n $completedAt: timestamp(record.completedAt),\n $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),\n $recordedAt: timestamp(record.recordedAt) ?? Date.now(),\n })\n}\n\n/**\n * Insert usage that has no assistant step of its own. The host event ID is the\n * primary key: a replayed event is ignored, so the totals never double count a\n * compaction or a title generation delivered more than once.\n */\nexport function recordUsage(db: Database, record: UsageRecord): void {\n if (typeof record.id !== \"string\" || record.id === \"\") return\n if (typeof record.sessionID !== \"string\" || record.sessionID === \"\") return\n db.query(\n `INSERT INTO usage (\n id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write\n ) VALUES (\n $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite\n ) ON CONFLICT(id) DO NOTHING`,\n ).run({\n $id: record.id,\n $sessionID: record.sessionID,\n $source: sanitizeLabel(record.source, 64),\n $at: timestamp(record.at) ?? Date.now(),\n $cost: Math.max(0, finite(record.cost)),\n $input: tokenCount(record.input),\n $output: tokenCount(record.output),\n $reasoning: tokenCount(record.reasoning),\n $cacheRead: tokenCount(record.cacheRead),\n $cacheWrite: tokenCount(record.cacheWrite),\n })\n}\n\nexport function recordPrompt(db: Database, record: PromptRecord): void {\n db.query(\n `INSERT INTO prompts (session_id, message_id, created_at)\n VALUES ($sessionID, $messageID, $createdAt)\n ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`,\n ).run({\n $sessionID: record.sessionID,\n $messageID: record.messageID,\n $createdAt: timestamp(record.createdAt),\n })\n}\n\nexport function recordEvent(db: Database, record: EventRecord): void {\n db.query(\n `INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)\n VALUES ($sessionID, $kind, $messageID, $at, $data)`,\n ).run({\n $sessionID: record.sessionID,\n $kind: sanitizeLabel(record.kind, 64),\n $messageID: record.messageID ?? null,\n $at: timestamp(record.at) ?? Date.now(),\n $data: jsonText(record.data),\n })\n}\n\nexport function upsertSession(db: Database, record: SessionRecord): void {\n db.query(\n `INSERT INTO sessions (session_id, parent_id, directory, title, started_at, updated_at)\n VALUES ($sessionID, $parentID, $directory, $title, $startedAt, $updatedAt)\n ON CONFLICT(session_id) DO UPDATE SET\n parent_id = COALESCE(excluded.parent_id, sessions.parent_id),\n directory = COALESCE(excluded.directory, sessions.directory),\n title = COALESCE(excluded.title, sessions.title),\n started_at = COALESCE(sessions.started_at, excluded.started_at),\n updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`,\n ).run({\n $sessionID: record.sessionID,\n $parentID: record.parentID ?? null,\n // Titles are written by a model and directories come from the host: both\n // are displayed, so neither may carry control characters into a terminal.\n $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),\n $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),\n $startedAt: timestamp(record.startedAt),\n $updatedAt: timestamp(record.updatedAt),\n })\n}\n\n/** Dump every table as NDJSON (`{\"table\": \"...\", \"row\": {...}}` per line). */\nexport function exportNdjson(db: Database): string {\n const lines: string[] = []\n for (const table of TABLES) {\n const rows = db.query(`SELECT * FROM ${table}`).all() as Record<string, unknown>[]\n for (const row of rows) lines.push(JSON.stringify({ table, row }))\n }\n return lines.length > 0 ? `${lines.join(\"\\n\")}\\n` : \"\"\n}\n\n/** Column shape an import has to respect: the type and the NOT NULL rules. */\ntype ImportColumn = {\n name: string\n /** Declared affinity: `INTEGER`, `REAL`, `TEXT`, `BLOB` or empty. */\n type: string\n notNull: boolean\n primaryKey: boolean\n /** A column with a default may be left out of the import entirely. */\n hasDefault: boolean\n}\n\nfunction numericAffinity(type: string): boolean {\n const upper = type.toUpperCase()\n return upper.includes(\"INT\") || upper.includes(\"REAL\") || upper.includes(\"NUM\") || upper.includes(\"DEC\") || upper.includes(\"DOUB\")\n}\n\n/**\n * One imported value, forced into the shape of its column. Text is sanitized\n * and capped like everything else that is displayed; a number that is not a\n * finite number becomes NULL, so a crafted dump cannot store `NaN` or a\n * string where a view does arithmetic.\n */\nfunction importValue(value: unknown, column: ImportColumn): string | number | null {\n if (value === null || value === undefined) return null\n if (numericAffinity(column.type)) {\n const parsed = typeof value === \"number\" ? value : Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null\n if (typeof value === \"boolean\") return value ? 1 : 0\n if (typeof value === \"object\") return sanitizeLabel(JSON.stringify(value) ?? \"\", LABEL_LIMIT)\n return sanitizeLabel(String(value), LABEL_LIMIT)\n}\n\n/**\n * Load an `exportNdjson` dump back in. Rows are inserted with `OR IGNORE`, so\n * importing the same dump twice is harmless. Unknown tables and rows that are\n * not objects are rejected; a row that cannot fill a required column is\n * skipped rather than aborting the rest of the import. A column the row does\n * not carry is left to its default, the same way a hand-written insert is.\n */\nexport function importNdjson(db: Database, text: string): number {\n const columns = new Map<TableName, ImportColumn[]>()\n for (const table of TABLES) {\n const info = db.query(`PRAGMA table_info(${table})`).all() as {\n name: string\n type: string\n notnull: number\n pk: number\n dflt_value: string | null\n }[]\n columns.set(\n table,\n info.map((column) => ({\n name: column.name,\n type: column.type,\n notNull: column.notnull === 1,\n primaryKey: column.pk > 0,\n hasDefault: column.dflt_value !== null,\n })),\n )\n }\n\n let imported = 0\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim()\n if (!trimmed) continue\n let parsed: { table?: string; row?: Record<string, unknown> }\n try {\n parsed = JSON.parse(trimmed) as { table?: string; row?: Record<string, unknown> }\n } catch {\n continue\n }\n const table = parsed.table as TableName | undefined\n const row = parsed.row\n if (!table || !row || !(TABLES as readonly string[]).includes(table)) continue\n const shape = columns.get(table) ?? []\n if (shape.length === 0) continue\n const names: string[] = []\n const values: (string | number)[] = []\n let importable = true\n for (const column of shape) {\n const value = importValue(row[column.name], column)\n if (value !== null) {\n names.push(column.name)\n values.push(value)\n continue\n }\n // NULL for a column that cannot hold one has no default to fall back on,\n // and a NULL in a text primary key is a key the database cannot use; an\n // INTEGER PRIMARY KEY is a rowid, so leaving it out assigns one.\n const required = (column.notNull || (column.primaryKey && !numericAffinity(column.type))) && !column.hasDefault\n if (required) {\n importable = false\n break\n }\n }\n if (!importable) continue\n // The database's money rule is an invariant, not a convention: a step that\n // was charged has no list estimate. A hand-written or foreign dump may\n // carry both, which every cost total would then add twice. Negative token\n // counts and costs are nonsense and would poison the sums.\n const tokenNames = [\"input_tokens\", \"output_tokens\", \"reasoning_tokens\", \"cache_read\", \"cache_write\"]\n for (const name of tokenNames) {\n const index = names.indexOf(name)\n if (index !== -1 && typeof values[index] === \"number\") values[index] = Math.max(0, Math.floor(values[index] as number))\n }\n const costIndex = names.indexOf(\"cost\")\n if (costIndex !== -1 && typeof values[costIndex] === \"number\") {\n const cost = Math.max(0, values[costIndex] as number)\n values[costIndex] = cost\n const listIndex = names.indexOf(\"list_cost\")\n if (table === \"steps\" && cost > 0 && listIndex !== -1) {\n names.splice(listIndex, 1)\n values.splice(listIndex, 1)\n }\n }\n const placeholders = names.map(() => \"?\").join(\", \")\n db.query(`INSERT OR IGNORE INTO ${table} (${names.join(\", \")}) VALUES (${placeholders})`).run(...values)\n imported += 1\n }\n return imported\n}\n",
6
- "import { homedir } from \"node:os\"\nimport { join } from \"node:path\"\nimport { statSync } from \"node:fs\"\n\n/**\n * SQLite database used when no `db` option is configured: the per-user state\n * directory of the current OS, never a shared temp directory.\n *\n * The subdirectory is the plugin's package name, never a generic one: the\n * `opencode` tree is shared with OpenCode itself and with every other plugin,\n * so a `stats/` of our own would be a collision waiting to happen.\n *\n * - Windows: `%LOCALAPPDATA%\\opencode\\opencode-usage-insights\\usage.db`\n * - macOS: `~/Library/Application Support/opencode/opencode-usage-insights/usage.db`\n * - Linux/other: `$XDG_STATE_HOME/opencode/opencode-usage-insights/usage.db`,\n * falling back to `~/.local/state/opencode/opencode-usage-insights/usage.db`\n *\n * Pure by design so every OS can be asserted from any machine.\n */\nexport function defaultDbPath(env: Record<string, string | undefined> = process.env, platform: string = process.platform): string {\n const name = join(\"opencode\", \"opencode-usage-insights\", \"usage.db\")\n if (platform === \"win32\") {\n return join(env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\"), name)\n }\n if (platform === \"darwin\") {\n return join(homedir(), \"Library\", \"Application Support\", name)\n }\n return join(env.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\"), name)\n}\n\n/**\n * Expand a leading `~` (or `~/`), so a configured path reads the way every\n * shell does. Windows accepts the backslash form too.\n */\nexport function expandHome(path: string, home: string = homedir()): string {\n if (path === \"~\") return home\n if (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) return join(home, path.slice(2))\n return path\n}\n\n/**\n * Resolve the effective database path: explicit plugin option first, then the\n * `OPENCODE_USAGE_INSIGHTS_DB` escape hatch (handy for dev and tests), then\n * the per-OS state directory. A leading `~` is expanded in all three.\n */\nexport function resolveDbPath(\n configured?: string | undefined,\n env: Record<string, string | undefined> = process.env,\n platform: string = process.platform,\n): string {\n const home = env.HOME ?? env.USERPROFILE ?? homedir()\n if (configured) return expandHome(configured, home)\n if (env.OPENCODE_USAGE_INSIGHTS_DB) return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home)\n return defaultDbPath(env, platform)\n}\n\n/**\n * A configured path must not be a directory, a device or a FIFO: SQLite would\n * fail obscurely, or write where nobody expects it. Symlinks to a regular file\n * are followed (`statSync`, not `lstat`) because moving the state directory to\n * another disk is a legitimate setup. A missing file is fine — the plugin\n * creates it.\n */\nexport function ensureRegularFile(path: string): void {\n let stats\n try {\n stats = statSync(path)\n } catch {\n return\n }\n if (!stats.isFile()) throw new Error(`not a regular file: ${path}`)\n}\n",
7
- "/**\n * Text hygiene for everything that reaches a terminal.\n *\n * Some of what the plugin displays is not written by the user: a model writes\n * a session title, an NDJSON export can come from anywhere. A control\n * character in any of those is interpreted by the terminal that renders it\n * (title changes, cursor moves, colours), so every such string is stripped of\n * control characters before it is stored or drawn.\n *\n * The rule is deliberately blunt: drop C0 controls, DEL and the C1 block, keep\n * everything else (the text is otherwise arbitrary Unicode), and cap the\n * length so a hostile value cannot bloat the database or the frame. Layout is\n * never touched: whitespace is preserved, because callers build indentation\n * into the strings they truncate.\n */\n\n/** Longest value kept by default: a title, an id or a path, not a document. */\nexport const TEXT_LIMIT = 512\n\n/**\n * Strip control characters and cap the length. Newlines and tabs go too: a\n * line is one line, and the renderers lay out their own spacing.\n */\nexport function sanitizeText(value: string, limit = TEXT_LIMIT): string {\n if (limit <= 0) return \"\"\n let cleaned = \"\"\n for (const character of value) {\n const code = character.codePointAt(0) ?? 0\n if (code <= 0x1f || code === 0x7f || (code >= 0x80 && code <= 0x9f)) continue\n cleaned += character\n if (cleaned.length >= limit) break\n }\n return cleaned\n}\n\n/** `sanitizeText` without the layout, for a stored label: trimmed as well. */\nexport function sanitizeLabel(value: string, limit = TEXT_LIMIT): string {\n return sanitizeText(value, limit).trim()\n}\n\n/**\n * A single identifier token: the shape a provider id or a model id has. Used\n * to validate the values that become grouping keys in the database, so a\n * configured provider cannot inject anything into an identity a view groups\n * by. Case is left alone: the provider is shown as it is configured, and\n * folding it would report a provider the user never chose.\n */\nconst TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/\n\nexport function isToken(value: string, limit = 64): boolean {\n return value.length > 0 && value.length <= limit && TOKEN.test(value)\n}\n",
5
+ "import type { Database } from \"bun:sqlite\"\n\n/**\n * The persisted shape. Kept separate from opening and recording so a migration\n * can read it without pulling in the recorder or the import layer.\n */\n\nexport const SCHEMA_VERSION = 14\n\nexport const SCHEMA = `\nCREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS sessions (\n session_id TEXT PRIMARY KEY,\n parent_id TEXT,\n directory TEXT,\n title TEXT,\n started_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n session_id TEXT NOT NULL,\n message_id TEXT NOT NULL,\n created_at INTEGER,\n PRIMARY KEY (session_id, message_id)\n);\nCREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);\n\nCREATE TABLE IF NOT EXISTS steps (\n message_id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n provider_id TEXT,\n model_id TEXT,\n variant TEXT,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n reasoning_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read INTEGER NOT NULL DEFAULT 0,\n cache_write INTEGER NOT NULL DEFAULT 0,\n cost REAL NOT NULL DEFAULT 0,\n list_cost REAL,\n created_at INTEGER,\n first_token_at INTEGER,\n streamed_at INTEGER,\n completed_at INTEGER,\n finish TEXT,\n recorded_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS steps_session ON steps(session_id, created_at);\nCREATE INDEX IF NOT EXISTS steps_model ON steps(provider_id, model_id, variant);\nCREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);\n-- Every range filter and every ordering compares the step's own clock, which\n-- falls back to the recording time for a step that was already in flight when\n-- the plugin loaded. The index has to cover that expression, or every ranged\n-- view is a full table scan.\nCREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));\nCREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));\n\n-- The compaction timeline: when a compaction ended, by host event ID. The\n-- cost and tokens live in the usage table; the payload that used to be copied\n-- here was never read. Only compactions exist in this table by construction.\nCREATE TABLE IF NOT EXISTS compactions (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n message_id TEXT,\n at INTEGER\n);\nCREATE INDEX IF NOT EXISTS compactions_session ON compactions(session_id, at);\nCREATE INDEX IF NOT EXISTS compactions_at ON compactions(at);\nCREATE UNIQUE INDEX IF NOT EXISTS compactions_message ON compactions(message_id) WHERE message_id IS NOT NULL;\n\n-- Usage the host reports with no assistant step of its own: the compaction\n-- summarisation and the session-title generation. The host publishes it as\n-- session.usage.recorded with a source other than generate, and includes it in\n-- the session's own cost/token totals. Primary key is the host event ID, so a\n-- replayed event never counts twice.\nCREATE TABLE IF NOT EXISTS usage (\n id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n source TEXT NOT NULL,\n at INTEGER,\n cost REAL NOT NULL DEFAULT 0,\n input_tokens INTEGER NOT NULL DEFAULT 0,\n output_tokens INTEGER NOT NULL DEFAULT 0,\n reasoning_tokens INTEGER NOT NULL DEFAULT 0,\n cache_read INTEGER NOT NULL DEFAULT 0,\n cache_write INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);\nCREATE INDEX IF NOT EXISTS usage_at ON usage(at);\n`\n\n/** Tables carried by `exportNdjson` / `importNdjson`, in import-safe order. */\nexport const TABLES = [\"sessions\", \"prompts\", \"compactions\", \"steps\", \"usage\"] as const\n\nexport type TableName = (typeof TABLES)[number]\n\n/** Column shape an import has to respect: the type and the NOT NULL rules. */\nexport type ImportColumn = {\n name: string\n /** Declared affinity: `INTEGER`, `REAL`, `TEXT`, `BLOB` or empty. */\n type: string\n notNull: boolean\n primaryKey: boolean\n /** A column with a default may be left out of the import entirely. */\n hasDefault: boolean\n}\n\n/** True when the database carries a table, without throwing on an older file. */\nexport function hasTable(db: Database, name: string): boolean {\n try {\n return db.query(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\").get(name) !== null\n } catch {\n return false\n }\n}\n\n/** Column names of a table, or an empty set when the table does not exist. */\nexport function columnsOf(db: Database, table: string): Set<string> {\n if (!hasTable(db, table)) return new Set()\n return new Set((db.query(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((column) => column.name))\n}\n\n/** Full column metadata an import has to respect. */\nexport function tableColumns(db: Database, table: string): ImportColumn[] {\n if (!hasTable(db, table)) return []\n const info = db.query(`PRAGMA table_info(${table})`).all() as {\n name: string\n type: string\n notnull: number\n pk: number\n dflt_value: string | null\n }[]\n return info.map((column) => ({\n name: column.name,\n type: column.type,\n notNull: column.notnull === 1,\n primaryKey: column.pk > 0,\n hasDefault: column.dflt_value !== null,\n }))\n}\n",
6
+ "import { Database } from \"bun:sqlite\"\nimport { chmodSync, mkdirSync } from \"node:fs\"\nimport { dirname } from \"node:path\"\nimport { ensureRegularFile } from \"./paths\"\nimport { migrate } from \"./migrate\"\nimport { SCHEMA, SCHEMA_VERSION } from \"./schema\"\n\n/**\n * Database lifecycle. The server recorder opens the file for writing and\n * migrates it; readers never write, and maintenance gets a short-lived writer\n * that gives up quickly instead of holding the recorder up.\n */\n\n/**\n * The file holds session titles, project directories and usage history, so it\n * is created for the user alone. Windows takes its access from the parent\n * directory's ACL, which is not something a plugin should rewrite.\n */\nconst POSIX = process.platform !== \"win32\"\n\nfunction hardenDirectory(path: string): void {\n if (!POSIX) return\n try {\n chmodSync(path, 0o700)\n } catch {\n // A shared or read-only directory: the database is still usable.\n }\n}\n\nfunction hardenFiles(path: string): void {\n if (!POSIX || path === \":memory:\") return\n for (const file of [path, `${path}-wal`, `${path}-shm`]) {\n try {\n chmodSync(file, 0o600)\n } catch {\n // The WAL and the shared-memory file are created on the first write and\n // removed on the last close, so one of them is often simply absent.\n }\n }\n}\n\n/** Directory for a database path, created private on POSIX. */\nfunction prepareDirectory(path: string): void {\n if (path === \":memory:\") return\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n hardenDirectory(dirname(path))\n}\n\n/** Open (creating when needed) the stats database and apply the schema. */\nexport function openStatsDb(path: string): Database {\n if (path !== \":memory:\") ensureRegularFile(path)\n prepareDirectory(path)\n const db = new Database(path, { create: true })\n try {\n db.exec(\"PRAGMA journal_mode = WAL\")\n db.exec(\"PRAGMA busy_timeout = 5000\")\n db.exec(\"PRAGMA synchronous = NORMAL\")\n db.exec(SCHEMA)\n migrate(db)\n db.query(\"INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\").run(\n String(SCHEMA_VERSION),\n )\n // The schema write is what creates the WAL and its shared-memory file.\n hardenFiles(path)\n return db\n } catch (error) {\n db.close()\n throw error\n }\n}\n\n/**\n * Reader connection for the TUI: no schema, no migration, no write. It throws\n * when the database is absent or was never written by the recorder, so the\n * caller can say so instead of showing an empty panel.\n */\nexport function openStatsDbReadOnly(path: string): Database {\n ensureRegularFile(path)\n const db = new Database(path, { readonly: true })\n try {\n db.query(\"SELECT 1 FROM steps LIMIT 1\").get()\n } catch (error) {\n db.close()\n throw error\n }\n return db\n}\n\n/**\n * Short-lived write connection for maintenance. The busy timeout is short on\n * purpose: a prune, wipe or vacuum that cannot take the lock must fail in front\n * of the user, not hold the recorder's response path for seconds.\n */\nexport function openStatsDbWrite(path: string): Database {\n if (path !== \":memory:\") ensureRegularFile(path)\n prepareDirectory(path)\n const db = new Database(path, { create: true })\n db.exec(\"PRAGMA busy_timeout = 250\")\n db.exec(\"PRAGMA synchronous = NORMAL\")\n hardenFiles(path)\n return db\n}\n",
7
+ "import { homedir } from \"node:os\"\nimport { join } from \"node:path\"\nimport { statSync } from \"node:fs\"\n\n/**\n * SQLite database used when no path is configured: the per-user state\n * directory of the current OS, never a shared temp directory.\n *\n * The subdirectory is the plugin's package name, never a generic one: the\n * `opencode` tree is shared with OpenCode itself and with every other plugin,\n * so a `stats/` of our own would be a collision waiting to happen.\n *\n * - Windows: `%LOCALAPPDATA%\\opencode\\opencode-usage-insights\\usage.db`\n * - macOS: `~/Library/Application Support/opencode/opencode-usage-insights/usage.db`\n * - Linux/other: `$XDG_STATE_HOME/opencode/opencode-usage-insights/usage.db`,\n * falling back to `~/.local/state/opencode/opencode-usage-insights/usage.db`\n *\n * Pure by design so every OS can be asserted from any machine.\n */\nexport function defaultDbPath(env: Record<string, string | undefined> = process.env, platform: string = process.platform): string {\n const name = join(\"opencode\", \"opencode-usage-insights\", \"usage.db\")\n if (platform === \"win32\") {\n return join(env.LOCALAPPDATA ?? join(homedir(), \"AppData\", \"Local\"), name)\n }\n if (platform === \"darwin\") {\n return join(homedir(), \"Library\", \"Application Support\", name)\n }\n return join(env.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\"), name)\n}\n\n/**\n * Expand a leading `~` (or `~/`), so a configured path reads the way every\n * shell does. Windows accepts the backslash form too.\n */\nexport function expandHome(path: string, home: string = homedir()): string {\n if (path === \"~\") return home\n if (path.startsWith(\"~/\") || path.startsWith(\"~\\\\\")) return join(home, path.slice(2))\n return path\n}\n\n/**\n * Resolve the effective database path: an explicit override first (used by\n * tests and the CLI), then the `OPENCODE_USAGE_INSIGHTS_DB` server policy, then\n * the per-OS state directory. A leading `~` is expanded in all three. The\n * server no longer reads a `db` option from `opencode.json(c)`.\n */\nexport function resolveDbPath(\n configured?: string | undefined,\n env: Record<string, string | undefined> = process.env,\n platform: string = process.platform,\n): string {\n const home = env.HOME ?? env.USERPROFILE ?? homedir()\n if (configured) return expandHome(configured, home)\n if (env.OPENCODE_USAGE_INSIGHTS_DB) return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home)\n return defaultDbPath(env, platform)\n}\n\n/**\n * A configured path must not be a directory, a device or a FIFO: SQLite would\n * fail obscurely, or write where nobody expects it. Symlinks to a regular file\n * are followed (`statSync`, not `lstat`) because moving the state directory to\n * another disk is a legitimate setup. A missing file is fine — the plugin\n * creates it.\n */\nexport function ensureRegularFile(path: string): void {\n let stats\n try {\n stats = statSync(path)\n } catch {\n return\n }\n if (!stats.isFile()) throw new Error(`not a regular file: ${path}`)\n}\n",
8
+ "/**\n * Domain constants shared by the recorder, the migrations and the import\n * layer. They live below all of them so a schema migration never has to import\n * a query module just to name the one event kind it understands.\n */\n\n/** Host event kind written when a compaction completes. */\nexport const COMPACTION_KIND = \"compaction\"\n",
9
+ "import { COMPACTION_KIND } from \"./constants\"\n\n/**\n * The payload older versions copied into `events.data`. Both the startup\n * migration and the NDJSON importer use this parser, so the two paths cannot\n * disagree about what a legacy compaction cost.\n */\n\nconst KEY_SEPARATOR = \"\\u0000\"\n\n/**\n * A timestamp from an imported row: a finite number or a numeric string.\n * `null`, booleans, empty strings and other junk are not timestamps. The\n * migration has always required a real time before recovering usage; the\n * import must not turn a missing one into the epoch.\n */\nexport function importTimestamp(value: unknown): number | undefined {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined\n if (typeof value !== \"string\") return undefined\n const trimmed = value.trim()\n if (trimmed === \"\") return undefined\n const parsed = Number(trimmed)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/** Key a non-step usage row by session and time, for import deduplication. */\nexport function usageKey(sessionID: unknown, at: unknown): string | undefined {\n if (typeof sessionID !== \"string\" || sessionID === \"\") return undefined\n const time = importTimestamp(at)\n return time === undefined ? undefined : `${sessionID}${KEY_SEPARATOR}${time}`\n}\n\nexport type LegacyCompactionUsage = {\n sessionID: string\n at: number\n cost: number\n input: number\n output: number\n reasoning: number\n cacheRead: number\n cacheWrite: number\n}\n\nfunction numberOrZero(value: unknown): number {\n const parsed = importTimestamp(value)\n return parsed === undefined ? 0 : Math.max(0, parsed)\n}\n\n/**\n * Older exports carried the compaction cost and tokens in `events.data`; the\n * schema no longer has that column. Recover the same fields the old migration\n * read, so a backup made by an older version still imports its totals.\n */\nexport function legacyCompactionUsage(row: Record<string, unknown>): LegacyCompactionUsage | undefined {\n if (row.kind !== COMPACTION_KIND) return undefined\n if (row.message_id !== undefined && row.message_id !== null && row.message_id !== \"\") return undefined\n if (typeof row.session_id !== \"string\" || row.session_id === \"\") return undefined\n const at = importTimestamp(row.at)\n if (at === undefined) return undefined\n let payload = row.data\n if (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload)\n } catch {\n return undefined\n }\n }\n if (typeof payload !== \"object\" || payload === null) return undefined\n const record = payload as Record<string, unknown>\n const tokens =\n typeof record.tokens === \"object\" && record.tokens !== null ? (record.tokens as Record<string, unknown>) : {}\n const cache =\n typeof tokens.cache === \"object\" && tokens.cache !== null ? (tokens.cache as Record<string, unknown>) : {}\n return {\n sessionID: row.session_id,\n at,\n cost: numberOrZero(record.cost),\n input: Math.floor(numberOrZero(tokens.input)),\n output: Math.floor(numberOrZero(tokens.output)),\n reasoning: Math.floor(numberOrZero(tokens.reasoning)),\n cacheRead: Math.floor(numberOrZero(cache.read)),\n cacheWrite: Math.floor(numberOrZero(cache.write)),\n }\n}\n",
10
+ "/**\n * Text hygiene for everything that reaches a terminal.\n *\n * Some of what the plugin displays is not written by the user: a model writes\n * a session title, an NDJSON export can come from anywhere. A control\n * character in any of those is interpreted by the terminal that renders it\n * (title changes, cursor moves, colours), so every such string is stripped of\n * control characters before it is stored or drawn.\n *\n * The rule is deliberately blunt: drop C0 controls, DEL and the C1 block, keep\n * everything else (the text is otherwise arbitrary Unicode), and cap the\n * length so a hostile value cannot bloat the database or the frame. Layout is\n * never touched: whitespace is preserved, because callers build indentation\n * into the strings they truncate.\n */\n\n/** Longest value kept by default: a title, an id or a path, not a document. */\nexport const TEXT_LIMIT = 512\n\n/** Longest title or path kept: a label on a line, not a document. */\nexport const LABEL_LIMIT = 4 * TEXT_LIMIT\n\n/**\n * Strip control characters and cap the length. Newlines and tabs go too: a\n * line is one line, and the renderers lay out their own spacing.\n */\nexport function sanitizeText(value: string, limit = TEXT_LIMIT): string {\n if (limit <= 0) return \"\"\n let cleaned = \"\"\n for (const character of value) {\n const code = character.codePointAt(0) ?? 0\n if (code <= 0x1f || code === 0x7f || (code >= 0x80 && code <= 0x9f)) continue\n cleaned += character\n if (cleaned.length >= limit) break\n }\n return cleaned\n}\n\n/** `sanitizeText` without the layout, for a stored label: trimmed as well. */\nexport function sanitizeLabel(value: string, limit = TEXT_LIMIT): string {\n return sanitizeText(value, limit).trim()\n}\n\n/**\n * A single identifier token: the shape a provider id or a model id has. Used\n * to validate the values that become grouping keys in the database, so a\n * configured provider cannot inject anything into an identity a view groups\n * by. Case is left alone: the provider is shown as it is configured, and\n * folding it would report a provider the user never chose.\n */\nconst TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/\n\nexport function isToken(value: string, limit = 64): boolean {\n return value.length > 0 && value.length <= limit && TOKEN.test(value)\n}\n",
11
+ "import type { Database } from \"bun:sqlite\"\nimport { isToken, LABEL_LIMIT, sanitizeLabel } from \"../text\"\n\n/**\n * Write side of the stats engine. Every function is idempotent and sanitizes\n * whatever came from the host event stream or an imported dump.\n */\n\nexport type StepRecord = {\n messageID: string\n sessionID: string\n /** The provider the model ran through, as OpenCode configured it (`opencode-go`). */\n providerID?: string | undefined\n modelID?: string | undefined\n variant?: string | undefined\n input?: number | undefined\n output?: number | undefined\n reasoning?: number | undefined\n cacheRead?: number | undefined\n cacheWrite?: number | undefined\n cost?: number | undefined\n /**\n * List-price estimate for a step the host reported as costing nothing.\n * `0` means a known free model; `NULL` means charged money or an unknown\n * price.\n */\n listCost?: number | undefined\n createdAt?: number | undefined\n /** When the provider streamed the step's first output token. */\n firstTokenAt?: number | undefined\n streamedAt?: number | undefined\n completedAt?: number | undefined\n finish?: string | undefined\n /** Clock of the recording itself, defaults to `Date.now()`. */\n recordedAt?: number | undefined\n}\n\nexport type PromptRecord = {\n sessionID: string\n messageID: string\n createdAt?: number | undefined\n}\n\n/** A completed compaction. The kind is fixed by the writer, not the caller. */\nexport type CompactionRecord = {\n sessionID: string\n messageID?: string | undefined\n at?: number | undefined\n}\n\n/**\n * Usage with no assistant step behind it (a compaction or a title generation).\n * `id` is the host event ID: it is the primary key, so a replay is ignored\n * instead of counted again.\n */\nexport type UsageRecord = {\n id: string\n sessionID: string\n source: string\n at?: number | undefined\n cost?: number | undefined\n input?: number | undefined\n output?: number | undefined\n reasoning?: number | undefined\n cacheRead?: number | undefined\n cacheWrite?: number | undefined\n}\n\nexport type SessionRecord = {\n sessionID: string\n parentID?: string | undefined\n directory?: string | undefined\n title?: string | undefined\n startedAt?: number | undefined\n}\n\n/**\n * Numeric fields arrive from the host event stream, which the plugin treats as\n * untrusted: a single `NaN` bound to a NOT NULL column makes SQLite reject the\n * whole statement, and the recorder's defensive catch would then silently lose\n * the step. Every number is therefore forced into a finite, non-negative value\n * before it reaches the database.\n */\nfunction finite(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0\n}\n\nfunction tokenCount(value: unknown): number {\n return Math.max(0, Math.floor(finite(value)))\n}\n\nfunction timestamp(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null\n}\n\nconst STEP_UPSERT = `\n INSERT INTO steps (\n message_id, session_id, provider_id, model_id, variant,\n input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,\n created_at, first_token_at, streamed_at, completed_at, finish, recorded_at\n ) VALUES (\n $messageID, $sessionID, $providerID, $modelID, $variant,\n $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,\n $createdAt, $firstTokenAt, $streamedAt, $completedAt, $finish, $recordedAt\n )\n ON CONFLICT(message_id) DO UPDATE SET\n session_id = excluded.session_id,\n provider_id = COALESCE(excluded.provider_id, steps.provider_id),\n model_id = COALESCE(excluded.model_id, steps.model_id),\n variant = COALESCE(excluded.variant, steps.variant),\n input_tokens = excluded.input_tokens,\n output_tokens = excluded.output_tokens,\n reasoning_tokens = excluded.reasoning_tokens,\n cache_read = excluded.cache_read,\n cache_write = excluded.cache_write,\n cost = excluded.cost,\n -- A step that starts being charged loses its estimate; an estimate is\n -- kept when a replayed event arrives without a price table.\n list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,\n created_at = COALESCE(excluded.created_at, steps.created_at),\n first_token_at = COALESCE(excluded.first_token_at, steps.first_token_at),\n streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),\n completed_at = COALESCE(excluded.completed_at, steps.completed_at),\n finish = COALESCE(excluded.finish, steps.finish),\n recorded_at = excluded.recorded_at\n`\n\nfunction stepCost(record: StepRecord): { cost: number; listCost: number | null } {\n const cost = Math.max(0, finite(record.cost))\n const listCost =\n cost <= 0 && typeof record.listCost === \"number\" && Number.isFinite(record.listCost) && record.listCost >= 0\n ? record.listCost\n : null\n return { cost, listCost }\n}\n\nfunction stepParams(record: StepRecord, cost: number, listCost: number | null) {\n return {\n $messageID: record.messageID,\n $sessionID: record.sessionID,\n $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,\n $modelID: record.modelID ?? null,\n $variant: record.variant ?? null,\n $input: tokenCount(record.input),\n $output: tokenCount(record.output),\n $reasoning: tokenCount(record.reasoning),\n $cacheRead: tokenCount(record.cacheRead),\n $cacheWrite: tokenCount(record.cacheWrite),\n $cost: cost,\n $listCost: listCost,\n $createdAt: timestamp(record.createdAt),\n $firstTokenAt: timestamp(record.firstTokenAt),\n $streamedAt: timestamp(record.streamedAt),\n $completedAt: timestamp(record.completedAt),\n $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),\n $recordedAt: timestamp(record.recordedAt) ?? Date.now(),\n }\n}\n\n/**\n * Insert or refresh an assistant step. Idempotent by message ID so replayed\n * events, restarts and NDJSON imports never duplicate usage. A non-null field\n * (the provider, the model, the finish reason) survives a re-record with `NULL`\n * through COALESCE. `list_cost` follows the opposite rule: a step that becomes\n * charged loses its estimate, and an estimate survives a replay that carries\n * no price table.\n *\n * The provider is the identity every view groups by, so it is validated as a\n * token before it is stored: a value that is not a provider id is recorded as\n * absent instead of becoming a grouping key.\n */\nexport function recordStep(db: Database, record: StepRecord): void {\n const { cost, listCost } = stepCost(record)\n db.query(STEP_UPSERT).run(stepParams(record, cost, listCost))\n}\n\n/**\n * Insert usage that has no assistant step of its own. The host event ID is the\n * primary key: a replayed event is ignored, so the totals never double count a\n * compaction or a title generation delivered more than once.\n */\nexport function recordUsage(db: Database, record: UsageRecord): void {\n if (typeof record.id !== \"string\" || record.id === \"\") return\n if (typeof record.sessionID !== \"string\" || record.sessionID === \"\") return\n db.query(\n `INSERT INTO usage (\n id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write\n ) VALUES (\n $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite\n ) ON CONFLICT(id) DO NOTHING`,\n ).run({\n $id: record.id,\n $sessionID: record.sessionID,\n $source: sanitizeLabel(record.source, 64),\n $at: timestamp(record.at) ?? Date.now(),\n $cost: Math.max(0, finite(record.cost)),\n $input: tokenCount(record.input),\n $output: tokenCount(record.output),\n $reasoning: tokenCount(record.reasoning),\n $cacheRead: tokenCount(record.cacheRead),\n $cacheWrite: tokenCount(record.cacheWrite),\n })\n}\n\nexport function recordPrompt(db: Database, record: PromptRecord): void {\n db.query(\n `INSERT INTO prompts (session_id, message_id, created_at)\n VALUES ($sessionID, $messageID, $createdAt)\n ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`,\n ).run({\n $sessionID: record.sessionID,\n $messageID: record.messageID,\n $createdAt: timestamp(record.createdAt),\n })\n}\n\n/**\n * Insert the compaction timeline row. The host event ID is the idempotency\n * key; the table holds compactions only, so there is no kind to choose.\n */\nexport function recordCompaction(db: Database, record: CompactionRecord): void {\n db.query(\n `INSERT OR IGNORE INTO compactions (session_id, message_id, at)\n VALUES ($sessionID, $messageID, $at)`,\n ).run({\n $sessionID: record.sessionID,\n $messageID: record.messageID ?? null,\n $at: timestamp(record.at) ?? Date.now(),\n })\n}\n\nexport function upsertSession(db: Database, record: SessionRecord): void {\n db.query(\n `INSERT INTO sessions (session_id, parent_id, directory, title, started_at)\n VALUES ($sessionID, $parentID, $directory, $title, $startedAt)\n ON CONFLICT(session_id) DO UPDATE SET\n parent_id = COALESCE(excluded.parent_id, sessions.parent_id),\n directory = COALESCE(excluded.directory, sessions.directory),\n title = COALESCE(excluded.title, sessions.title),\n started_at = COALESCE(sessions.started_at, excluded.started_at)`,\n ).run({\n $sessionID: record.sessionID,\n $parentID: record.parentID ?? null,\n // Titles are written by a model and directories come from the host: both\n // are displayed, so neither may carry control characters into a terminal.\n $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),\n $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),\n $startedAt: timestamp(record.startedAt),\n })\n}\n",
12
+ "import type { Database } from \"bun:sqlite\"\nimport { COMPACTION_KIND } from \"./constants\"\nimport { legacyCompactionUsage } from \"./legacy\"\nimport { recordUsage } from \"./records\"\nimport { columnsOf, hasTable } from \"./schema\"\n\n/**\n * Migration policy. A long-lived file has to lose what no view reads and gain\n * what a newer recorder writes. Every step is idempotent, so an interrupted\n * run can be repeated; the whole sequence is one transaction so a failure\n * cannot leave a half-migrated schema behind.\n */\n\n/**\n * Columns the recorder used to write and no view ever read. They are dropped\n * from an existing database so a long-lived file shrinks instead of carrying\n * dead weight forever.\n *\n * `router` is here because the gateway that named the routing endpoint in a\n * response header (`x-opencode-endpoint-id`) stopped naming one: the identity a\n * step is grouped by is the provider the model ran through, and the endpoint a\n * gateway happened to route to is no longer observable at all.\n *\n * `steps.parent_id` was never filled by the recorder, and the session's parent\n * relationship is the one the views read. `sessions.updated_at` was written on\n * every rename and move but never read.\n */\nconst REMOVED_COLUMNS = {\n steps: [\"provider_state\", \"upstream\", \"upstream_source\", \"upstream_model\", \"tps\", \"router\", \"parent_id\"],\n sessions: [\"updated_at\"],\n} as const\n\nfunction dropUnused(db: Database): void {\n const objects = db.query(\"SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')\").all() as {\n name: string\n type: string\n }[]\n const indexes = new Set(objects.filter((row) => row.type === \"index\").map((row) => row.name))\n\n if (hasTable(db, \"http_responses\")) db.exec(\"DROP TABLE http_responses\")\n // These indexes read a column that is about to go: SQLite refuses to drop an\n // indexed column, so the index goes first.\n if (indexes.has(\"steps_upstream\")) db.exec(\"DROP INDEX steps_upstream\")\n if (indexes.has(\"steps_router\")) db.exec(\"DROP INDEX steps_router\")\n\n for (const [table, names] of Object.entries(REMOVED_COLUMNS)) {\n const columns = columnsOf(db, table)\n for (const name of names) {\n if (columns.has(name)) db.exec(`ALTER TABLE ${table} DROP COLUMN ${name}`)\n }\n }\n}\n\n/**\n * Add the columns a newer recorder writes. `CREATE TABLE IF NOT EXISTS` does\n * not touch a table that already exists, so a column added to the schema after\n * a database was created has to be added here too. The check is idempotent and\n * also heals a database a half-applied run left behind.\n */\nfunction addMissing(db: Database): void {\n const columns = columnsOf(db, \"steps\")\n if (columns.size > 0 && !columns.has(\"list_cost\")) {\n db.exec(\"ALTER TABLE steps ADD COLUMN list_cost REAL\")\n }\n if (columns.size > 0 && !columns.has(\"first_token_at\")) {\n db.exec(\"ALTER TABLE steps ADD COLUMN first_token_at INTEGER\")\n }\n}\n\n/**\n * The pre-v14 `events` table had a `kind` column and older recorders inserted\n * a compaction on every delivery. Keep one row per exact duplicate before the\n * copy, so the compaction count and the recovered usage stay honest.\n *\n * Once the payload has been dropped there is nothing left to tell two rows\n * apart but the session and the time. Rows without a time are deliberately left\n * alone: grouping them by (session, NULL) would collapse unrelated malformed\n * records instead of deduplicating a replay.\n */\nfunction dedupeLegacyCompactions(db: Database): void {\n if (!hasTable(db, \"events\")) return\n const columns = columnsOf(db, \"events\")\n if (![\"session_id\", \"kind\", \"message_id\", \"at\"].every((name) => columns.has(name))) return\n if (columns.has(\"data\")) {\n db.query(`DELETE FROM events\n WHERE kind = ? AND message_id IS NULL\n AND rowid NOT IN (\n SELECT MIN(rowid) FROM events\n WHERE kind = ? AND message_id IS NULL\n GROUP BY session_id, at, data\n )`).run(COMPACTION_KIND, COMPACTION_KIND)\n } else {\n db.query(`DELETE FROM events\n WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL\n AND rowid NOT IN (\n SELECT MIN(rowid) FROM events\n WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL\n GROUP BY session_id, at\n )`).run(COMPACTION_KIND, COMPACTION_KIND)\n }\n db.exec(`DELETE FROM events\n WHERE message_id IS NOT NULL\n AND rowid NOT IN (\n SELECT MIN(rowid) FROM events\n WHERE message_id IS NOT NULL\n GROUP BY message_id\n )`)\n}\n\n/**\n * Older recorders kept only the compaction event, never `session.usage.recorded`.\n * The event payload already carries the cost and tokens, so recovering it makes\n * the fix retroactive for compactions. A row gets a stable synthetic ID;\n * `recordUsage` ignores a replay. Only historical rows (`message_id IS NULL`)\n * are considered: from the recorder version that wrote `usage`, re-backfilling\n * would count it twice.\n *\n * The parser is shared with the NDJSON importer so both paths read the same\n * payload the same way.\n */\nfunction backfillCompactionUsage(db: Database): void {\n if (!hasTable(db, \"events\") || !hasTable(db, \"usage\")) return\n const columns = columnsOf(db, \"events\")\n if (![\"session_id\", \"kind\", \"message_id\", \"at\", \"data\"].every((name) => columns.has(name))) return\n const rows = db\n .query(\n `SELECT rowid AS id, session_id, kind, message_id, at, data\n FROM events\n WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL`,\n )\n .all(COMPACTION_KIND) as Record<string, unknown>[]\n for (const row of rows) {\n const legacy = legacyCompactionUsage(row)\n if (legacy === undefined) continue\n recordUsage(db, {\n id: `compaction:${String(row.id)}`,\n sessionID: legacy.sessionID,\n source: COMPACTION_KIND,\n at: legacy.at,\n cost: legacy.cost,\n input: legacy.input,\n output: legacy.output,\n reasoning: legacy.reasoning,\n cacheRead: legacy.cacheRead,\n cacheWrite: legacy.cacheWrite,\n })\n }\n}\n\n/**\n * Move the old event log into the compaction timeline and drop it. The copy\n * does not keep the old rowid: the only identity a view reads is the host\n * event ID on `message_id`, and the unique index ignores a repeated one.\n */\nfunction migrateLegacyCompactions(db: Database): void {\n if (!hasTable(db, \"events\")) return\n const columns = columnsOf(db, \"events\")\n if (![\"session_id\", \"kind\", \"message_id\", \"at\"].every((name) => columns.has(name))) return\n db.query(\n `INSERT OR IGNORE INTO compactions (session_id, message_id, at)\n SELECT session_id, message_id, at FROM events WHERE kind = ?`,\n ).run(COMPACTION_KIND)\n db.exec(\"DROP TABLE events\")\n}\n\n/**\n * Bring an existing file up to date. The transaction keeps a failed run from\n * leaving a file that is neither the old schema nor the new one; every step is\n * idempotent for the retry.\n */\nexport function migrate(db: Database): void {\n db.transaction(() => {\n dropUnused(db)\n addMissing(db)\n dedupeLegacyCompactions(db)\n backfillCompactionUsage(db)\n migrateLegacyCompactions(db)\n })()\n}\n",
8
13
  "import type { Database } from \"bun:sqlite\"\nimport { basename } from \"node:path\"\nimport { clampPanelWidth, clampTurnsLimit, MAX_HISTORY_WIDTH } from \"./limits\"\nimport { buildPanel, type PanelRequest } from \"./panel-build\"\nimport {\n defaultSort,\n sessionSummaryLines,\n sidebarLines,\n sanitizeSettings,\n type LineFormatOptions,\n type PanelSettings,\n} from \"./panel-data\"\nimport { costOf, type PriceTable } from \"./pricing\"\nimport { openStatsDbWrite } from \"./stats/db\"\nimport { backfillListCost, dbInfo, pruneOlderThan, vacuum, wipeAll, type BackfillResult, type DbInfo, type PruneResult, type WipeResult } from \"./stats/maintenance\"\nimport { filterOptions, overview, sessionListCost, turns, type FilterOption, type Filters } from \"./stats/queries\"\nimport type {\n BackfillInput,\n FiltersOutput,\n ListCostInput,\n ListCostOutput,\n PanelInput,\n PanelOutput,\n PruneInput,\n TurnsInput,\n TurnsOutput,\n VacuumInput,\n VacuumOutput,\n WipeInput,\n} from \"./rpc\"\n\n/**\n * The database-facing half of the plugin. It runs on the server (in-process as\n * a fallback, or inside `stats-worker`) and is the only code that reads or\n * writes the SQLite file for the panel, sidebar and maintenance actions. The\n * TUI and the desktop GUI only see the validated RPC surface.\n */\n\nconst DAY = 24 * 60 * 60 * 1000\nconst MAX_DAYS = 3650\n\nexport type ServiceErrorCode = \"busy\" | \"unavailable\" | \"disabled\" | \"invalid\"\n\nexport class ServiceError extends Error {\n readonly code: ServiceErrorCode\n\n constructor(code: ServiceErrorCode, message: string) {\n super(message)\n this.name = \"ServiceError\"\n this.code = code\n }\n}\n\nexport type ServiceOptions = {\n /** Database file path, for maintenance and for the `db` view. */\n path: string\n /** `false` hides list-price estimates and disables the backfill. */\n pricing: boolean\n /** `false` exposes read methods only. */\n maintenance: boolean\n /** `false` returns a redacted path instead of the absolute one. */\n exposePaths: boolean\n /** Formatting options shared by the panel and the turn history. */\n format: LineFormatOptions\n /** Server-side catalog for the historical backfill. */\n priceTable?: (() => PriceTable | undefined) | undefined\n}\n\nexport type Service = ReturnType<typeof createService>\n\nfunction clamp(value: number, minimum: number, maximum: number): number {\n if (!Number.isFinite(value)) return minimum\n return Math.min(maximum, Math.max(minimum, Math.round(value)))\n}\n\n/** The `session` range starts when the session was created, not when a step ran. */\nfunction sessionStart(db: Database, sessionID: string): number | undefined {\n const session = db.query(\"SELECT started_at AS at FROM sessions WHERE session_id = ?\").get(sessionID) as\n | { at: number | null }\n | null\n if (session?.at !== null && session?.at !== undefined) return session.at\n const step = db\n .query(\"SELECT MIN(COALESCE(created_at, recorded_at)) AS at FROM steps WHERE session_id = ?\")\n .get(sessionID) as { at: number | null } | null\n return step?.at ?? undefined\n}\n\nfunction redact(info: DbInfo, exposePaths: boolean): DbInfo {\n if (exposePaths) return info\n return { ...info, path: basename(info.path) }\n}\n\nfunction filtersOf(settings: PanelSettings): Filters {\n return {\n ...(settings.modelID !== \"\" ? { modelID: settings.modelID } : {}),\n ...(settings.providerID !== \"\" ? { provider: settings.providerID } : {}),\n }\n}\n\nfunction writeDb<T>(path: string, run: (db: Database) => T): T {\n let db: Database | undefined\n try {\n db = openStatsDbWrite(path)\n return run(db)\n } catch (error) {\n if (error instanceof ServiceError) throw error\n throw new ServiceError(\"busy\", \"the database is busy; try again in a moment\")\n } finally {\n db?.close()\n }\n}\n\nexport function createService(db: () => Database, options: ServiceOptions) {\n const settingsOf = (input: PanelInput): PanelSettings => sanitizeSettings(input.settings)\n\n function infoOf(): DbInfo {\n return redact(dbInfo(db(), options.path), options.exposePaths)\n }\n\n function panel(input: PanelInput): PanelOutput {\n const settings = settingsOf(input)\n const database = settings.view === \"db\" ? infoOf() : undefined\n const width = clampPanelWidth(input.width)\n const filters = filtersOf(settings)\n const request: PanelRequest = {\n db: db(),\n view: settings.view,\n range: settings.range,\n filters,\n granularity: settings.granularity,\n turnsScope: settings.turnsScope,\n sort: settings.sort === \"\" ? defaultSort(settings.view) : settings.sort,\n sortDesc: settings.sortDesc,\n sessionID: input.sessionID,\n sessionStart: sessionStart(db(), input.sessionID),\n now: Date.now(),\n format: { ...options.format, estimates: options.pricing },\n estimates: options.pricing,\n ...(input.detail !== undefined ? { detail: input.detail } : {}),\n ...(database !== undefined ? { database } : {}),\n busy: input.busy === true,\n width,\n }\n return { lines: buildPanel(request), ...(database !== undefined ? { database } : {}) }\n }\n\n function turnHistory(input: TurnsInput): TurnsOutput {\n const handle = db()\n const width = clamp(input.width, 20, MAX_HISTORY_WIDTH)\n const limit = clampTurnsLimit(input.limit)\n const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing)\n const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {\n ...options.format,\n estimates: options.pricing,\n budget: width,\n })\n return { summary, history }\n }\n\n function listCost(input: ListCostInput): ListCostOutput {\n if (!options.pricing) return { cost: 0 }\n return { cost: sessionListCost(db(), input.sessionID) }\n }\n\n function filters(): FiltersOutput {\n return filterOptions(db())\n }\n\n function requireMaintenance(): void {\n if (!options.maintenance) throw new ServiceError(\"disabled\", \"database maintenance is disabled\")\n }\n\n function requireConfirm(confirm: boolean | undefined): void {\n if (confirm !== true) throw new ServiceError(\"invalid\", \"confirmation is required\")\n }\n\n function prune(input: PruneInput): PruneResult {\n requireMaintenance()\n requireConfirm(input.confirm)\n const days = clamp(input.days, 1, MAX_DAYS)\n return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY))\n }\n\n function wipe(input: WipeInput): WipeResult {\n requireMaintenance()\n requireConfirm(input.confirm)\n return writeDb(options.path, (handle) => wipeAll(handle))\n }\n\n function compact(input: VacuumInput): VacuumOutput {\n requireMaintenance()\n requireConfirm(input.confirm)\n return writeDb(options.path, (handle) => vacuum(handle, options.path))\n }\n\n function backfill(input: BackfillInput, table?: PriceTable | undefined): BackfillResult {\n if (!options.pricing) throw new ServiceError(\"disabled\", \"list-price estimates are turned off\")\n requireMaintenance()\n requireConfirm(input.confirm)\n const prices = table ?? options.priceTable?.()\n if (prices === undefined) throw new ServiceError(\"unavailable\", \"the model catalog is unavailable\")\n return writeDb(options.path, (handle) => backfillListCost(handle, (ref, tokens) => costOf(prices, ref, tokens)))\n }\n\n return {\n panel,\n turnHistory,\n listCost,\n filters,\n dbInfo: infoOf,\n prune,\n wipe,\n compact,\n backfill,\n }\n}\n",
9
14
  "/**\n * Shared request bounds.\n *\n * The RPC schemas, the clients and the service use the same numbers: a client\n * must clamp before it calls the RPC, because schema validation runs before the\n * service can clamp. These constants keep the three layers from drifting.\n */\n\n/** Widest panel the server formats. */\nexport const MAX_PANEL_WIDTH = 200\n\n/** Widest turn history the server formats. */\nexport const MAX_HISTORY_WIDTH = 120\n\n/** Most turns the server returns for a history request. */\nexport const MAX_TURNS = 50\n\n/** A finite width within the panel bounds. */\nexport function clampPanelWidth(value: number): number {\n if (!Number.isFinite(value)) return 20\n return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)))\n}\n\n/**\n * How many monospace cells fit in a panel body. The GUI measures the body and\n * one glyph; both are CSS pixels, so the division is exact before the floor.\n * A zero measurement means the body is not laid out (hidden or not mounted):\n * the caller keeps its previous width instead of asking for a 20-column panel.\n */\nexport function panelColumns(available: number, charWidth: number): number {\n if (!Number.isFinite(available) || !Number.isFinite(charWidth) || available <= 0 || charWidth <= 0) return 0\n return clampPanelWidth(Math.floor(available / charWidth))\n}\n\n/** A finite turn limit within the history bounds. */\nexport function clampTurnsLimit(value: number): number {\n if (!Number.isFinite(value)) return 1\n return Math.min(MAX_TURNS, Math.max(1, Math.round(value)))\n}\n",
10
- "/**\n * Pure turn accounting shared by the TUI line, the server recorder and the\n * stats engine.\n *\n * Everything here operates on structural shapes that mirror the session\n * messages published by OpenCode, so the logic stays testable without a host\n * runtime and without the effect-based schema types.\n */\n\nexport type ModelRefLike = {\n providerID: string\n id: string\n variant?: string | undefined\n}\n\nexport type AssistantMessage = {\n type: \"assistant\"\n id: string\n time?: { created?: number | undefined; streamed?: number | undefined; completed?: number | undefined } | undefined\n model?: ModelRefLike | undefined\n tokens?:\n | {\n input?: number | undefined\n output?: number | undefined\n reasoning?: number | undefined\n cache?: { read?: number | undefined; write?: number | undefined } | undefined\n }\n | undefined\n cost?: number | undefined\n /** List-price estimate for a step the host reported as costing nothing. */\n listCost?: number | undefined\n finish?: string | null | undefined\n rawFinish?: string | null | undefined\n}\n\nexport type PromptMessage = {\n type: \"user\" | \"synthetic\" | \"system\"\n id?: string | undefined\n time?: { created?: number | undefined } | undefined\n}\n\nexport type TranscriptMessage =\n | AssistantMessage\n | PromptMessage\n | { type: string; id?: string | undefined; time?: { created?: number | undefined } | undefined }\n\n/** Accumulated token usage for a group of assistant steps. */\nexport type Totals = {\n input: number\n cached: number\n output: number\n reasoning: number\n cacheWrite: number\n cost: number\n /** Sum of list-price estimates for steps the host reported as $0. */\n listCost: number\n steps: number\n}\n\nexport type CacheDrop = {\n messageID: string\n /** Tokens that were expected to hit the prompt cache but did not. */\n tokens: number\n /** `cache.read` of the step that was used as the reuse reference. */\n prevCached: number\n /** Time between the reference step's completion and this step's request. */\n gapMs: number | undefined\n}\n\nexport type TurnStats = {\n /** Wall clock time of the last step's completion. */\n endAt: number | undefined\n /** Creation time of the first settled step of the turn. */\n startAt: number | undefined\n /** Creation time of the prompt that opened this turn. */\n promptAt: number | undefined\n /** Time between the previous prompt and this turn's prompt. */\n promptGapMs: number | undefined\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n /** Provider ID differs from the previous turn in the same transcript. */\n providerChanged: boolean\n /** Provider is the same but the model or variant differs. */\n modelChanged: boolean\n totals: Totals\n /** Passed through from the caller (session-wide accumulated usage). */\n session: Totals | undefined\n /**\n * Prompt-side usage of the last finished step: the context the turn ended\n * with. Summing `input`/`cached` over the steps of a turn counts the same\n * re-sent prompt once per step, which is not what a context view means.\n */\n latest: Totals\n drops: CacheDrop[]\n cacheDropTokens: number\n cacheExpired: boolean\n /** Assistant steps in the turn. */\n steps: number\n}\n\nexport type TurnSegment = {\n assistants: AssistantMessage[]\n prompt: TranscriptMessage | undefined\n}\n\n/** Message types that open a turn: a run of assistants belongs to the last one. */\nexport const PROMPT_BOUNDARIES: ReadonlySet<string> = new Set([\"user\", \"synthetic\", \"system\"])\n\n/**\n * Split a transcript into turns. A turn is a run of assistant steps opened by\n * a prompt boundary (`user`, `synthetic`, `system`). Idle notices, info\n * messages, compactions and shell entries keep the current turn open so a\n * single execution is never split in two.\n */\nexport function transcriptSegments(messages: readonly TranscriptMessage[]): TurnSegment[] {\n const segments: TurnSegment[] = []\n let current: AssistantMessage[] = []\n let prompt: TranscriptMessage | undefined\n\n for (const message of messages) {\n if (message.type === \"assistant\") {\n current.push(message as AssistantMessage)\n continue\n }\n if (!PROMPT_BOUNDARIES.has(message.type)) continue\n if (current.length > 0) {\n segments.push({ assistants: current, prompt })\n current = []\n }\n prompt = message\n }\n if (current.length > 0) segments.push({ assistants: current, prompt })\n return segments\n}\n\n/**\n * The last `count` segments, found by walking the transcript backwards. The\n * live line only needs the turn that just ended and the one before it, and a\n * long session holds tens of thousands of messages: the tail walk stops as\n * soon as it has them, instead of building a segment for every turn.\n */\nexport function transcriptTail(messages: readonly TranscriptMessage[], count: number): TurnSegment[] {\n const segments: TurnSegment[] = []\n let current: AssistantMessage[] = []\n\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!\n if (message.type === \"assistant\") {\n current.unshift(message as AssistantMessage)\n continue\n }\n if (!PROMPT_BOUNDARIES.has(message.type)) continue\n if (current.length === 0) continue\n // The boundary closes the run collected after it.\n segments.unshift({ assistants: current, prompt: message })\n if (segments.length >= count) return segments\n current = []\n }\n // A leading run with no prompt before it is a segment of its own.\n if (current.length > 0 && segments.length < count) segments.unshift({ assistants: current, prompt: undefined })\n return segments\n}\n\n/**\n * A token count or a timestamp read from a host message: `undefined` for a\n * timestamp that is not a finite number, zero for a count that is not. The\n * recorder applies the same rule before SQLite; doing it here keeps the live\n * line on the same footing when a payload is malformed.\n */\nfunction countOf(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0\n}\n\nfunction amountOf(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : 0\n}\n\nfunction stampOf(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined\n}\n\nexport function tokenCounts(message: AssistantMessage): { input: number; output: number; reasoning: number; read: number; write: number } {\n const tokens = message.tokens\n return {\n input: countOf(tokens?.input),\n output: countOf(tokens?.output),\n reasoning: countOf(tokens?.reasoning),\n read: countOf(tokens?.cache?.read),\n write: countOf(tokens?.cache?.write),\n }\n}\n\nexport function totalize(steps: readonly AssistantMessage[]): Totals {\n const totals: Totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length }\n for (const step of steps) {\n const counts = tokenCounts(step)\n totals.input += counts.input\n totals.cached += counts.read\n totals.output += counts.output\n totals.reasoning += counts.reasoning\n totals.cacheWrite += counts.write\n totals.cost += amountOf(step.cost)\n totals.listCost += amountOf(step.listCost)\n }\n return totals\n}\n\n/**\n * The identity of a model reference: the provider it runs through, the model\n * and its variant. Two steps with the same key ran the same thing the same way,\n * which is what `modelChanged` compares.\n */\nexport function identityKey(model: ModelRefLike | undefined): string | undefined {\n if (!model) return undefined\n return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : \"\"}`\n}\n\nexport function cacheRead(message: AssistantMessage | undefined): number {\n return countOf(message?.tokens?.cache?.read)\n}\n\nexport function stepCreated(message: AssistantMessage | undefined): number | undefined {\n return stampOf(message?.time?.created)\n}\n\nexport function stepEnd(message: AssistantMessage | undefined): number | undefined {\n const time = message?.time\n if (!time) return undefined\n return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created)\n}\n\n/**\n * Which identity the two steps must share for a reuse loss to be measurable.\n * `provider` is the strict one: two providers are two caches, so a switch\n * between them is not a loss but a different cache. `model` drops that test,\n * for the reports that measure what an identity change costs: forfeiting the\n * previous provider's cache is exactly the cost they report.\n */\nexport type CacheDropScope = \"provider\" | \"model\"\n\n/**\n * Cache reuse loss against a reference step, mirroring OpenCode's own\n * `turn-usage` heuristic: only comparable when the model is identical, and\n * OpenAI's API reports small reads that are not worth flagging.\n */\nexport function cacheDrop(reference: AssistantMessage | undefined, current: AssistantMessage, scope: CacheDropScope = \"provider\"): number | undefined {\n if (!reference) return undefined\n const before = reference.model\n const after = current.model\n if (!before || !after) return undefined\n if (scope === \"provider\" && before.providerID !== after.providerID) return undefined\n if (before.id !== after.id || (before.variant ?? \"\") !== (after.variant ?? \"\")) {\n return undefined\n }\n const drop = cacheRead(reference) - cacheRead(current)\n if (isNoiseDrop(after.providerID, drop)) return undefined\n return drop > 0 ? drop : undefined\n}\n\n/** Milliseconds between a reference step's completion and the next request. */\nexport function stepGap(reference: AssistantMessage | undefined, current: AssistantMessage): number | undefined {\n const ended = stepEnd(reference)\n const started = stepCreated(current)\n if (ended === undefined || started === undefined) return undefined\n return Math.max(0, started - ended)\n}\n\n/**\n * Streaming duration of a step: request start to the last streamed chunk. The\n * host's `streamed` stamp marks the end of streaming, so this is the window a\n * generation rate belongs to — not a time to first token, which the session\n * messages do not record.\n */\nexport function stepStreamMs(message: AssistantMessage): number | undefined {\n const created = stampOf(message.time?.created)\n const streamed = stampOf(message.time?.streamed)\n if (created === undefined || streamed === undefined || streamed <= created) return undefined\n return streamed - created\n}\n\n/**\n * Tokens produced per second over a window. For a step the window is the\n * streaming one: request start to the last streamed chunk (`created` →\n * `streamed`) — `completed` marks the end of the step, which for a tool-call\n * step happens after the tool calls were handled. Returns undefined when the\n * window or the produced tokens are unknown. Single definition, shared by the\n * recorder (which stores it per step) and the latency view.\n */\nexport function tokensPerSecond(produced: number, from: number | undefined, to: number | undefined): number | undefined {\n if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from) return undefined\n if (!Number.isFinite(produced) || produced <= 0) return undefined\n return (produced / (to - from)) * 1000\n}\n\n\n/** Output-plus-reasoning tokens per second of a step. */\nexport function stepTps(message: AssistantMessage): number | undefined {\n const counts = tokenCounts(message)\n return tokensPerSecond(counts.output + counts.reasoning, message.time?.created, message.time?.streamed)\n}\n\nconst DROP_EXEMPT_PROVIDERS = new Set([\"openai\"])\n\n/**\n * True when a step has final numbers. A step that is still streaming reports\n * partial tokens (usually zero) and no cache read yet, so reading it would\n * render an empty line and invent a cache-expiry warning against it.\n */\nexport function isSettledStep(message: AssistantMessage): boolean {\n if (message.time?.completed !== undefined) return true\n return message.finish !== undefined && message.finish !== null\n}\n\n/**\n * Compute the stats of the most recent turn in a transcript, including the\n * comparison against the previous turn (a provider or model switch, and cache\n * reuse).\n *\n * Returns undefined while the newest turn is still being generated: the line\n * appears when a turn ends, never with the zeroes of an in-flight response.\n */\nexport function computeTurn(messages: readonly TranscriptMessage[], session?: Totals): TurnStats | undefined {\n const segments = transcriptTail(messages, 2)\n const last = segments[segments.length - 1]\n if (!last) return undefined\n const previous = segments[segments.length - 2]\n const lastStep = last.assistants[last.assistants.length - 1]\n if (!lastStep) return undefined\n if (!isSettledStep(lastStep)) return undefined\n const previousStep = previous?.assistants[previous.assistants.length - 1]\n // Defensive: a step that never settled mid-turn carries no usable numbers,\n // so it is neither a cache reference nor a reuse candidate.\n const settled = last.assistants.filter(isSettledStep)\n\n const drops: CacheDrop[] = []\n let reference: AssistantMessage | undefined = previousStep !== undefined && isSettledStep(previousStep) ? previousStep : undefined\n for (const step of settled) {\n const drop = cacheDrop(reference, step)\n if (drop !== undefined) {\n drops.push({\n messageID: step.id,\n tokens: drop,\n prevCached: cacheRead(reference),\n gapMs: stepGap(reference, step),\n })\n }\n reference = step\n }\n\n const provider = lastStep.model?.providerID\n const previousProvider = previousStep?.model?.providerID\n const key = identityKey(lastStep.model)\n const previousKey = identityKey(previousStep?.model)\n\n return {\n endAt: stepEnd(lastStep),\n startAt: stepCreated(settled[0] ?? lastStep),\n promptAt: stampOf(last.prompt?.time?.created),\n promptGapMs: promptGap(last.prompt, previous?.prompt),\n providerID: provider,\n modelID: lastStep.model?.id,\n variant: lastStep.model?.variant,\n providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,\n modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,\n totals: totalize(settled),\n latest: totalize([lastStep]),\n session,\n drops,\n cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),\n cacheExpired: drops.length > 0,\n steps: settled.length,\n }\n}\n\nfunction promptGap(current: TranscriptMessage | undefined, previous: TranscriptMessage | undefined): number | undefined {\n const now = stampOf(current?.time?.created)\n const before = stampOf(previous?.time?.created)\n if (now === undefined || before === undefined) return undefined\n return Math.max(0, now - before)\n}\n\n/** True when a cache drop is small enough to be provider noise. */\nexport function isNoiseDrop(providerID: string | undefined, drop: number): boolean {\n if (providerID === undefined) return false\n return DROP_EXEMPT_PROVIDERS.has(providerID) && drop >= 1024 && drop <= 2048\n}\n\n// ---------------------------------------------------------------------------\n// Formatting\n// ---------------------------------------------------------------------------\n\nexport type LineTone = \"base\" | \"muted\" | \"warning\"\n\nexport type LineSegment = { text: string; tone: LineTone }\n\nexport type LineLabels = {\n delta: string\n turn: string\n session: string\n step: string\n steps: string\n input: string\n cached: string\n output: string\n reasoning: string\n cost: string\n /** Prefix for a list-price estimate, e.g. `cost ≈ $0.03`. */\n estimate: string\n cacheExpired: string\n providerChanged: string\n modelChanged: string\n}\n\n/**\n * How the turn segment counts prompt usage. `latest` shows the prompt size the\n * turn ended with — the context view, and what OpenCode's own turn-token debug\n * line reports. `sum` adds every step of the turn: the billing view, where a\n * tool-call loop re-sends (and re-reads) the same context once per step.\n */\nexport type TurnTotalsView = \"latest\" | \"sum\"\n\nexport type LineFields = {\n clock: boolean\n delta: boolean\n model: boolean\n variant: boolean\n turn: boolean\n session: boolean\n reasoning: boolean\n cost: boolean\n cacheExpiry: boolean\n}\n\nexport const DEFAULT_LABELS: LineLabels = {\n delta: \"Δ\",\n // The turn segment is unlabelled by default to keep the line short; set it\n // back to \"turn\" (or anything else) through `labels.turn`.\n turn: \"\",\n session: \"sess\",\n step: \"step\",\n steps: \"steps\",\n input: \"in\",\n cached: \"cached\",\n output: \"out\",\n reasoning: \"reason\",\n cost: \"cost\",\n estimate: \"≈\",\n cacheExpired: \"cache expired\",\n providerChanged: \"changed\",\n modelChanged: \"model changed\",\n}\n\nexport const DEFAULT_FIELDS: LineFields = {\n clock: true,\n delta: true,\n model: true,\n variant: true,\n turn: true,\n session: true,\n reasoning: false,\n // The turn's and the session's cost are on by default: what a session costs\n // is the question the tokens only half answer. A zero is left out, so a free\n // model reads as free instead of repeating `$0` on every line.\n cost: true,\n cacheExpiry: true,\n}\n\nexport function formatClock(ms: number): string {\n if (!Number.isFinite(ms)) return \"--:--\"\n const date = new Date(ms)\n const pad = (value: number) => String(value).padStart(2, \"0\")\n return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n}\n\nexport function formatDuration(ms: number): string {\n if (!Number.isFinite(ms)) return \"–\"\n const totalSeconds = Math.max(0, Math.floor(ms / 1000))\n const seconds = totalSeconds % 60\n const minutes = Math.floor(totalSeconds / 60) % 60\n const hours = Math.floor(totalSeconds / 3600) % 24\n const days = Math.floor(totalSeconds / 86400)\n if (days > 0) return `${days}d${hours}h`\n if (hours > 0) return `${hours}h${String(minutes).padStart(2, \"0\")}m`\n if (minutes > 0) return `${minutes}m${String(seconds).padStart(2, \"0\")}s`\n return `${seconds}s`\n}\n\nexport function formatTokens(value: number): string {\n const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0\n if (n < 1_000) return String(n)\n if (n < 999_500) {\n const k = n / 1_000\n return `${trimZeros(k.toFixed(k < 10 ? 2 : 1))}k`\n }\n if (n < 999_500_000) {\n const m = n / 1_000_000\n return `${trimZeros(m.toFixed(m < 10 ? 2 : 1))}M`\n }\n return `${Math.round(n / 1_000_000)}M`\n}\n\nfunction trimZeros(value: string): string {\n return value.includes(\".\") ? value.replace(/0+$/, \"\").replace(/\\.$/, \"\") : value\n}\n\nexport function formatCost(value: number): string {\n if (!Number.isFinite(value) || value <= 0) return \"$0\"\n // Four decimals is the display precision below a dollar; a real, positive\n // amount that rounds to `$0.0000` would read as free, so it is shown as a\n // bound instead. This keeps a tiny list estimate distinguishable from zero.\n if (value < 0.00005) return \"<$0.0001\"\n if (value < 1) return `$${value.toFixed(4)}`\n return `$${value.toFixed(2)}`\n}\n\n/**\n * Charged and estimated money as one string. A mixed total keeps both parts\n * visible so list price is never mistaken for money that was charged:\n * `$0.12 + ≈ $3.40`. Returns undefined when there is no money to show.\n */\nexport function formatMoney(charged: number, estimated: number, marker = \"≈\"): string | undefined {\n const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined\n const estimate =\n Number.isFinite(estimated) && estimated > 0\n ? `${marker.trim() === \"\" ? \"\" : `${marker.trim()} `}${formatCost(estimated)}`\n : undefined\n if (paid !== undefined && estimate !== undefined) return `${paid} + ${estimate}`\n return paid ?? estimate\n}\n\n/**\n * The list-equivalent total for a compact table cell: charged money plus the\n * estimates, marked with `≈` when any part is estimated.\n */\nexport function formatSpend(charged: number, estimated: number, marker = \"≈\"): string {\n const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0\n const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0\n if (estimate > 0) return `${marker.trim()}${formatCost(paid + estimate)}`\n return formatCost(paid)\n}\n\n/**\n * The buckets the line displays, derived from a totals group. `input` is the\n * *uncached* part of the prompt (fresh input plus cache writes, i.e. what the\n * debug line's `new` counts on the prompt side), `prompt` is the whole prompt\n * of the request and `output` is everything the model generated (visible output\n * + reasoning). OpenCode's own debug line reconciles with these:\n * `new = in + out` and `total = prompt + out`, with `prompt = in + cached`.\n * The stored buckets stay raw; only the display folds.\n */\nexport type DisplayTotals = Totals & {\n /** Whole prompt of the request: fresh input + cached reads + cache writes. */\n prompt: number\n}\n\nexport function displayTotals(totals: Totals): DisplayTotals {\n const prompt = totals.input + totals.cached + totals.cacheWrite\n return {\n input: prompt - totals.cached,\n cached: totals.cached,\n cacheWrite: totals.cacheWrite,\n output: totals.output + totals.reasoning,\n reasoning: totals.reasoning,\n cost: totals.cost,\n listCost: totals.listCost,\n steps: totals.steps,\n prompt,\n }\n}\n\n/**\n * The numbers of one totals group. `cost` is passed explicitly because the two\n * callers mean different money: a turn's cost is the sum over its steps\n * whatever view its tokens follow, and money never comes from a \"latest\" step.\n * A charged cost of zero is left out; a list-price estimate is shown with `≈`.\n */\nfunction totalsText(\n prefix: string,\n totals: Totals,\n labels: LineLabels,\n fields: LineFields,\n stepCount = 0,\n cost = totals.cost,\n listCost = totals.listCost,\n estimates = true,\n): string {\n const display = displayTotals(totals)\n // The parenthesised value is the whole prompt, shown only when it differs\n // from the uncached part the label leads with.\n const input =\n display.prompt === display.input\n ? `${labels.input} ${formatTokens(display.input)}`\n : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`\n const parts = [\n input,\n `${labels.cached} ${formatTokens(display.cached)}`,\n `${labels.output} ${formatTokens(display.output)}`,\n ]\n if (fields.reasoning) parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`)\n const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined\n if (money !== undefined) parts.push(`${labels.cost} ${money}`)\n // An empty label (the default for the turn) leaves the numbers unlabelled; a\n // multi-step turn still says how many requests it took.\n const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : \"\"\n const head = [prefix, steps].filter((piece) => piece !== \"\").join(\" \")\n const numbers = parts.join(\", \")\n if (head === \"\") return numbers\n return stepCount > 1 ? `${head} · ${numbers}` : `${head} ${numbers}`\n}\n\n/**\n * The session totals as the line's `sess` segment alone. The Desktop badge\n * shows this while a turn is running: the turn has no final numbers yet, so\n * the badge reports the session's accumulated spend and this is its tooltip.\n */\nexport function formatSessionLine(\n totals: Totals,\n options?: { labels?: Partial<LineLabels>; fields?: Partial<LineFields>; estimates?: boolean },\n): string {\n const labels = { ...DEFAULT_LABELS, ...options?.labels }\n const fields = { ...DEFAULT_FIELDS, ...options?.fields }\n const estimates = options?.estimates !== false\n return totalsText(labels.session, totals, labels, fields, 0, totals.cost, totals.listCost, estimates)\n}\n\n/**\n * Render the telemetry line as toned segments. The caller maps tones onto\n * theme colors; `formatLine` joins the segments as plain text.\n */\nexport function formatLineSegments(\n stats: TurnStats,\n options?: { labels?: Partial<LineLabels>; fields?: Partial<LineFields>; turnTotals?: TurnTotalsView; estimates?: boolean },\n): LineSegment[] {\n const labels = { ...DEFAULT_LABELS, ...options?.labels }\n const fields = { ...DEFAULT_FIELDS, ...options?.fields }\n const turnTotals = options?.turnTotals ?? \"latest\"\n const estimates = options?.estimates !== false\n const segments: LineSegment[] = []\n\n if (fields.clock && stats.endAt !== undefined) {\n segments.push({ text: formatClock(stats.endAt), tone: \"muted\" })\n }\n if (fields.delta && stats.promptGapMs !== undefined) {\n segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: \"muted\" })\n }\n // The turn's identity is the provider the model ran through and the model\n // itself: the same model can come from different providers, so both are\n // shown, and a provider switch is the change the line warns about.\n if (stats.providerID !== undefined) {\n let text = stats.providerID\n if (fields.model && stats.modelID !== undefined) text += `/${stats.modelID}`\n if (fields.variant && stats.variant) text += ` ${stats.variant}`\n segments.push({ text, tone: stats.providerChanged ? \"warning\" : \"base\" })\n if (stats.providerChanged) segments.push({ text: labels.providerChanged, tone: \"warning\" })\n else if (stats.modelChanged) segments.push({ text: labels.modelChanged, tone: \"muted\" })\n }\n if (fields.turn && stats.totals.steps > 0) {\n const totals = turnTotals === \"sum\" ? stats.totals : stats.latest\n // The tokens follow the view — `latest` is the context the turn ended with\n // — but money is paid per step: the turn's cost is the sum over its steps,\n // never the last step's share of it.\n segments.push({\n text: totalsText(\n labels.turn,\n totals,\n labels,\n fields,\n turnTotals === \"sum\" ? stats.totals.steps : stats.steps,\n stats.totals.cost,\n stats.totals.listCost,\n estimates,\n ),\n tone: \"base\",\n })\n }\n if (fields.session && stats.session) {\n segments.push({\n text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),\n tone: \"muted\",\n })\n }\n if (fields.cacheExpiry && stats.cacheExpired) {\n const count = stats.drops.length > 1 ? `×${stats.drops.length}` : \"\"\n segments.push({ text: `⚠ ${labels.cacheExpired} (−${formatTokens(stats.cacheDropTokens)}${count})`, tone: \"warning\" })\n }\n return segments\n}\n\nexport function formatLine(\n stats: TurnStats,\n options?: { labels?: Partial<LineLabels>; fields?: Partial<LineFields>; turnTotals?: TurnTotalsView; estimates?: boolean },\n): string {\n return formatLineSegments(stats, options)\n .map((segment) => segment.text)\n .join(\" · \")\n}\n",
11
- "import type { Database } from \"bun:sqlite\"\nimport { cacheDrop, stepGap, tokensPerSecond, type AssistantMessage } from \"../core\"\n\n/**\n * Read side of the stats engine: every function takes an open database and\n * returns plain rows for the TUI panel, the report script and the NDJSON\n * exports. Aggregations stay in SQL; comparisons and percentiles that would\n * need window functions or custom SQLite builds are computed in JS.\n */\n\n/** Event kind written by the recorder when a compaction completes. */\nexport const COMPACTION_KIND = \"compaction\"\n\n/**\n * Idle gap above which a cache reuse loss is attributed to provider-side\n * expiry rather than to a mid-session event. Heuristic: the empirical TTL\n * evidence view narrows this down with real observations.\n */\nexport const DEFAULT_TTL_HINT_MS = 10 * 60 * 1000\n\nexport type Range = {\n from?: number | undefined\n to?: number | undefined\n}\n\n/**\n * Panel filters. They narrow every aggregation to one model, one provider or\n * one session, and are applied with the same `WHERE` builder the range uses so\n * a filtered view and a drill-down agree.\n */\nexport type Filters = {\n /** Model id, variant excluded. */\n modelID?: string | undefined\n /**\n * One model *and* its variant, as `modelKey` builds it (`m1#max`). A variant\n * is a different model to the provider, so a drill-down into one variant must\n * not pick up its family.\n */\n modelKey?: string | undefined\n /**\n * The provider the model ran through, as OpenCode configured it\n * (`opencode-go`, `deepseek`, `deepinfra`). It is the identity every view\n * groups by: a gateway may re-route the request, but the upstream that\n * actually ran it is not observable.\n */\n provider?: string | undefined\n /**\n * One session, exactly. Used by the `session` range and by the overview's\n * \"this session\" block, which must not pick up the steps of every other\n * session that happened to run after it started.\n */\n sessionID?: string | undefined\n}\n\nexport type Usage = {\n steps: number\n input: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n /** List-price estimate for steps the host reported as costing nothing. */\n listCost: number\n}\n\n/**\n * What the selection costs: charged money plus the list-price estimate of the\n * steps the host reported as free. Display code marks the estimated part.\n */\nexport function spend(usage: Pick<Usage, \"cost\" | \"listCost\">): number {\n return usage.cost + usage.listCost\n}\n\n/** True when at least one step in the aggregate is an estimate. */\nexport function hasEstimate(usage: Pick<Usage, \"listCost\">): boolean {\n return usage.listCost > 0\n}\n\n/**\n * The list-price estimate of one session, from the steps the plugin recorded.\n * The live line uses it for the `sess` segment; a session with no recorded\n * estimate (or a database without the column) answers 0.\n */\nexport function sessionListCost(db: Database, sessionID: string): number {\n const row = db\n .query(\"SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?\")\n .get(sessionID) as { listCost: number | null } | null\n return row?.listCost ?? 0\n}\n\n/**\n * Money the host reported with no assistant step behind it: a compaction\n * summary or a generated title. It is part of the session's own cost, so the\n * totals that claim to describe a session include it.\n */\nexport type OtherUsage = {\n /** Host usage records behind the number. */\n entries: number\n cost: number\n}\n\nexport const EMPTY_OTHER: OtherUsage = { entries: 0, cost: 0 }\n\n/** True when the database has the table the non-step usage lives in. */\nfunction hasUsageTable(db: Database): boolean {\n try {\n return db.query(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'\").get() !== null\n } catch {\n return false\n }\n}\n\n/**\n * `WHERE` for non-step usage. A model or provider filter cannot be honored:\n * the host usage record carries neither, so including it under a filter would\n * attribute money to a model that did not earn it. A session filter can: the\n * row is the session's.\n */\nfunction otherWhere(\n range: Range | undefined,\n filters?: Filters | undefined,\n): { where: string; params: (string | number)[] } | undefined {\n if (filters?.modelID !== undefined && filters.modelID !== \"\") return undefined\n if (filters?.modelKey !== undefined && filters.modelKey !== \"\") return undefined\n if (filters?.provider !== undefined && filters.provider !== \"\") return undefined\n const span = rangeWhere(range, \"at\")\n const clauses = span.where === \"\" ? [] : [span.where.slice(\"WHERE \".length)]\n const params: (string | number)[] = [...span.params]\n if (filters?.sessionID !== undefined && filters.sessionID !== \"\") {\n clauses.push(\"session_id = ?\")\n params.push(filters.sessionID)\n }\n return { where: clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\", params }\n}\n\n/** Non-step usage in the selection. */\nexport function otherUsage(db: Database, range?: Range | undefined, filters?: Filters | undefined): OtherUsage {\n const filter = otherWhere(range, filters)\n if (filter === undefined || !hasUsageTable(db)) return { ...EMPTY_OTHER }\n try {\n const row = db\n .query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`)\n .get(...filter.params) as { entries: number | null; cost: number | null } | null\n return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 }\n } catch {\n return { ...EMPTY_OTHER }\n }\n}\n\n/** Non-step usage per session, for the session rows. */\nexport function otherUsageBySession(db: Database, range?: Range | undefined, filters?: Filters | undefined): Map<string, OtherUsage> {\n const out = new Map<string, OtherUsage>()\n const filter = otherWhere(range, filters)\n if (filter === undefined || !hasUsageTable(db)) return out\n try {\n const rows = db\n .query(\n `SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost\n FROM usage ${filter.where}\n GROUP BY session_id`,\n )\n .all(...filter.params) as Array<{ sessionID: string; entries: number | null; cost: number | null }>\n for (const row of rows) out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 })\n } catch {\n // An older database has no usage table: step totals alone are still valid.\n }\n return out\n}\n\nexport type OtherUsageRow = {\n sessionID: string\n at: number\n cost: number\n}\n\n/**\n * Non-step usage as one row per host record, so calendar buckets can fold it\n * into their periods with the same local-time rule the steps use.\n */\nexport function otherUsageRows(db: Database, range?: Range | undefined, filters?: Filters | undefined): OtherUsageRow[] {\n const filter = otherWhere(range, filters)\n if (filter === undefined || !hasUsageTable(db)) return []\n const where = filter.where === \"\" ? \"WHERE at IS NOT NULL\" : `${filter.where} AND at IS NOT NULL`\n try {\n return db\n .query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`)\n .all(...filter.params) as OtherUsageRow[]\n } catch {\n return []\n }\n}\n\ntype UsageRow = {\n steps: number | null\n input: number | null\n cached: number | null\n cacheWrite: number | null\n output: number | null\n reasoning: number | null\n cost: number | null\n listCost: number | null\n}\n\nexport const STEP_TIME = \"COALESCE(created_at, recorded_at)\"\n\n/**\n * The identity of a model *and* its variant, in SQL: `modelKey` says a variant\n * is a different model to the provider, so a variant never shares a row with\n * its family. The JS twin is `modelKey` below; both have to agree.\n */\nexport const MODEL_KEY_SQL = \"COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')\"\n\n/** `modelKey(modelID, variant)`: the family, with the variant as a suffix. */\nexport function modelKey(modelID: string, variant: string | undefined): string {\n return `${modelID}#${variant ?? \"\"}`\n}\n\n/** Human label of a model key or a model id and variant. */\nexport function modelLabel(modelID: string, variant: string | undefined): string {\n return variant === undefined ? modelID : `${modelID} ${variant}`\n}\nconst USAGE_SELECT = `COUNT(*) AS steps,\n COALESCE(SUM(input_tokens), 0) AS input,\n COALESCE(SUM(cache_read), 0) AS cached,\n COALESCE(SUM(cache_write), 0) AS cacheWrite,\n COALESCE(SUM(output_tokens), 0) AS output,\n COALESCE(SUM(reasoning_tokens), 0) AS reasoning,\n COALESCE(SUM(cost), 0) AS cost,\n COALESCE(SUM(list_cost), 0) AS listCost`\n\nfunction usageFrom(row: UsageRow): Usage {\n return {\n steps: row.steps ?? 0,\n input: row.input ?? 0,\n cached: row.cached ?? 0,\n cacheWrite: row.cacheWrite ?? 0,\n output: row.output ?? 0,\n reasoning: row.reasoning ?? 0,\n cost: row.cost ?? 0,\n listCost: row.listCost ?? 0,\n }\n}\n\nfunction rangeWhere(range: Range | undefined, column = STEP_TIME): { where: string; params: number[] } {\n const clauses: string[] = []\n const params: number[] = []\n if (range?.from !== undefined) {\n clauses.push(`${column} >= ?`)\n params.push(range.from)\n }\n if (range?.to !== undefined) {\n clauses.push(`${column} < ?`)\n params.push(range.to)\n }\n return { where: clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\", params }\n}\n\n/**\n * `WHERE` for a range plus the panel filters. Shared with the analysis layer so\n * a filtered view and a drill-down agree on what is in scope.\n */\nexport function buildWhere(\n range: Range | undefined,\n filters?: Filters | undefined,\n column = STEP_TIME,\n): { where: string; params: (string | number)[] } {\n const rangeClause = rangeWhere(range, column)\n const clauses = rangeClause.where === \"\" ? [] : [rangeClause.where.slice(\"WHERE \".length)]\n const params: (string | number)[] = [...rangeClause.params]\n if (filters?.modelID !== undefined && filters.modelID !== \"\") {\n clauses.push(\"model_id = ?\")\n params.push(filters.modelID)\n }\n if (filters?.modelKey !== undefined && filters.modelKey !== \"\") {\n clauses.push(`${MODEL_KEY_SQL} = ?`)\n params.push(filters.modelKey)\n }\n if (filters?.provider !== undefined && filters.provider !== \"\") {\n clauses.push(\"provider_id = ?\")\n params.push(filters.provider)\n }\n if (filters?.sessionID !== undefined && filters.sessionID !== \"\") {\n clauses.push(\"session_id = ?\")\n params.push(filters.sessionID)\n }\n return { where: clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\", params }\n}\n\n/**\n * Share of the whole prompt that came from the cache. The denominator is what\n * the provider saw: cache reads, fresh input and cache writes.\n */\nexport function cacheHitRatio(usage: Pick<Usage, \"input\" | \"cached\" | \"cacheWrite\">): number | undefined {\n const total = usage.cached + usage.input + usage.cacheWrite\n return total > 0 ? usage.cached / total : undefined\n}\n\nexport type Overview = Usage & {\n sessions: number\n prompts: number\n /** Compaction/title money included in `cost`, when the range has any. */\n otherCost?: number | undefined\n firstAt: number | undefined\n lastAt: number | undefined\n cacheHitRatio: number | undefined\n /**\n * Tokens generated per second of streaming, over the whole selection: the\n * produced tokens divided by the summed streaming windows. A weighted average,\n * not the mean of the per-step rates the latency view reports as p50.\n */\n tps: number | undefined\n}\n\nexport function overview(db: Database, range?: Range, filters?: Filters): Overview {\n const steps = buildWhere(range, filters)\n const row = db\n .query(\n `SELECT ${USAGE_SELECT},\n COUNT(DISTINCT session_id) AS sessions,\n MIN(${STEP_TIME}) AS firstAt,\n MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,\n COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,\n COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window\n FROM steps ${steps.where}`,\n )\n .get(...steps.params) as\n | (UsageRow & { sessions: number | null; firstAt: number | null; lastAt: number | null; produced: number | null; window: number | null })\n | null\n\n const prompts = rangeWhere(range, \"created_at\")\n const promptClauses = prompts.where === \"\" ? [] : [prompts.where.slice(\"WHERE \".length)]\n const promptParams: (string | number)[] = [...prompts.params]\n // The session block asks for one session: a prompt has no model, so the\n // session filter is the one that can be honored here. Ignoring it counted\n // every prompt in the range, including those of other sessions.\n if (filters?.sessionID !== undefined && filters.sessionID !== \"\") {\n promptClauses.push(\"session_id = ?\")\n promptParams.push(filters.sessionID)\n }\n const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(\" AND \")}` : \"\"\n const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams) as {\n prompts: number\n } | null\n\n const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 })\n const other = otherUsage(db, range, filters)\n return {\n ...usage,\n // The host's session cost includes compactions and titles; a total that\n // claims to describe the selection has to include them too. Tokens stay\n // step-based so the cache views keep comparing like with like.\n cost: usage.cost + other.cost,\n sessions: row?.sessions ?? 0,\n prompts: promptRow?.prompts ?? 0,\n otherCost: other.cost,\n firstAt: row?.firstAt ?? undefined,\n lastAt: row?.lastAt ?? undefined,\n cacheHitRatio: cacheHitRatio(usage),\n tps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),\n }\n}\n\nexport type ProviderUsage = Usage & {\n providerID: string\n firstAt: number | undefined\n lastAt: number | undefined\n}\n\nexport type ModelUsage = {\n modelID: string\n variant: string | undefined\n providers: ProviderUsage[]\n totals: Usage\n}\n\ntype ModelRow = UsageRow & {\n provider_id: string | null\n model_id: string | null\n variant: string | null\n first_at: number | null\n last_at: number | null\n}\n\n/**\n * Usage per model, each with the providers that served it. This is the view\n * that answers \"through which provider is this model actually coming, over the\n * selected period\".\n */\nexport function models(db: Database, range?: Range, filters?: Filters): ModelUsage[] {\n const filter = buildWhere(range, filters)\n const rows = db\n .query(\n `SELECT provider_id, model_id, variant,\n ${USAGE_SELECT},\n MIN(${STEP_TIME}) AS first_at,\n MAX(COALESCE(completed_at, recorded_at)) AS last_at\n FROM steps ${filter.where}\n GROUP BY provider_id, model_id, variant\n ORDER BY steps DESC, cached DESC`,\n )\n .all(...filter.params) as ModelRow[]\n\n const models = new Map<string, ModelUsage>()\n for (const row of rows) {\n const modelID = row.model_id ?? \"(unknown)\"\n const variant = row.variant ?? undefined\n const key = `${modelID}#${variant ?? \"\"}`\n let model = models.get(key)\n if (!model) {\n model = { modelID, variant, providers: [], totals: emptyUsage() }\n models.set(key, model)\n }\n const usage = usageFrom(row)\n model.providers.push({\n ...usage,\n providerID: row.provider_id ?? \"(unknown)\",\n firstAt: row.first_at ?? undefined,\n lastAt: row.last_at ?? undefined,\n })\n addUsage(model.totals, usage)\n }\n return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals))\n}\n\nfunction emptyUsage(): Usage {\n return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 }\n}\n\nfunction addUsage(target: Usage, source: Usage): void {\n target.steps += source.steps\n target.input += source.input\n target.cached += source.cached\n target.cacheWrite += source.cacheWrite\n target.output += source.output\n target.reasoning += source.reasoning\n target.cost += source.cost\n target.listCost += source.listCost\n}\n\n/**\n * Every bucket a provider bills for: the whole prompt (fresh input, cache\n * reads and writes) plus visible output and reasoning. Leaving `cacheWrite`\n * or `reasoning` out ranked a model with heavy cache writes or thinking below\n * one with more visible output, which is not what \"most tokens\" means.\n */\nfunction billedTokens(usage: Pick<Usage, \"input\" | \"cached\" | \"cacheWrite\" | \"output\" | \"reasoning\">): number {\n return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning\n}\n\nexport type TimelineBucket = { at: number } & Usage\n\n/** Usage aggregated into fixed time buckets (for example one hour or day). */\nexport function timeline(db: Database, range: Range | undefined, bucketMs: number): TimelineBucket[] {\n const filter = rangeWhere(range)\n const rows = db\n .query(\n `SELECT CAST(${STEP_TIME} / ? AS INTEGER) * ? AS bucket, ${USAGE_SELECT}\n FROM steps ${filter.where}\n GROUP BY bucket\n ORDER BY bucket`,\n )\n .all(bucketMs, bucketMs, ...filter.params) as (UsageRow & { bucket: number })[]\n return rows.map((row) => ({ at: row.bucket, ...usageFrom(row) }))\n}\n\nexport type DropReason = \"compaction\" | \"expired\" | \"unknown\"\n\nexport type CacheDropRow = {\n sessionID: string\n messageID: string\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n at: number\n tokens: number\n gapMs: number | undefined\n prevCached: number\n reason: DropReason\n}\n\nexport type TtlEvidenceRow = {\n providerID: string\n modelID: string\n samples: number\n /** Largest idle gap that still hit the cache. */\n maxHitGapMs: number | undefined\n /** Smallest idle gap after which reuse was lost. */\n minDropGapMs: number | undefined\n}\n\nexport type LatencyStats = {\n count: number\n p50: number | undefined\n p90: number | undefined\n p99: number | undefined\n}\n\nexport type LatencyReport = {\n /** Milliseconds from request to completed response. */\n wall: LatencyStats\n /** Milliseconds from request to the last streamed chunk (the streaming window). */\n stream: LatencyStats\n /** Output-plus-reasoning tokens per second over that window. */\n tps: LatencyStats\n}\n\n/** Nearest-rank percentile over an unsorted sample. */\nexport function percentile(values: readonly number[], p: number): number | undefined {\n if (values.length === 0) return undefined\n const sorted = [...values].sort((a, b) => a - b)\n const rank = Math.ceil((p / 100) * sorted.length)\n const index = Math.min(sorted.length - 1, Math.max(0, rank - 1))\n return sorted[index]\n}\n\nexport function latencyStats(values: number[]): LatencyStats {\n return {\n count: values.length,\n p50: percentile(values, 50),\n p90: percentile(values, 90),\n p99: percentile(values, 99),\n }\n}\n\nconst statsFor = latencyStats\n\nexport type SessionUsage = Usage & {\n sessionID: string\n parentID: string | undefined\n title: string | undefined\n directory: string | undefined\n providers: string[]\n models: string[]\n prompts: number\n /** Compaction/title money included in `cost`, when the session has any. */\n otherCost?: number | undefined\n firstAt: number | undefined\n lastAt: number | undefined\n cacheHitRatio: number | undefined\n}\n\nexport function sessions(\n db: Database,\n options?: { range?: Range; filters?: Filters; limit?: number; sessionIDs?: readonly string[] },\n): SessionUsage[] {\n if (options?.sessionIDs !== undefined && options.sessionIDs.length === 0) return []\n const range = options?.range\n const filter = buildWhere(range, options?.filters, \"COALESCE(st.created_at, st.recorded_at)\")\n const limit = options?.limit ?? 20\n const clauses = filter.where === \"\" ? [] : [filter.where.slice(\"WHERE \".length)]\n const params: (number | string)[] = [...filter.params]\n // The session row is for a range, so its prompt count has to be for that\n // range too: a 7-day row must not show the prompts of the session's whole\n // history. The placeholders sit in the SELECT list, before the WHERE ones.\n const promptRange: string[] = []\n const promptParams: number[] = []\n if (range?.from !== undefined) {\n promptRange.push(\"p.created_at >= ?\")\n promptParams.push(range.from)\n }\n if (range?.to !== undefined) {\n promptRange.push(\"p.created_at < ?\")\n promptParams.push(range.to)\n }\n const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(\" AND \")}` : \"\"\n if (options?.sessionIDs !== undefined) {\n // A specific set of sessions (the subagents of one session): the group by\n // then reads one index range per session instead of every step recorded.\n const ids = options.sessionIDs.slice(0, 500)\n clauses.push(`st.session_id IN (${ids.map(() => \"?\").join(\", \")})`)\n params.push(...ids)\n }\n const rows = db\n .query(\n `SELECT st.session_id, s.title, s.directory, s.parent_id,\n GROUP_CONCAT(DISTINCT st.provider_id) AS providers,\n GROUP_CONCAT(DISTINCT st.model_id) AS models,\n (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,\n COUNT(*) AS steps,\n COALESCE(SUM(st.input_tokens), 0) AS input,\n COALESCE(SUM(st.cache_read), 0) AS cached,\n COALESCE(SUM(st.cache_write), 0) AS cacheWrite,\n COALESCE(SUM(st.output_tokens), 0) AS output,\n COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,\n COALESCE(SUM(st.cost), 0) AS cost,\n COALESCE(SUM(st.list_cost), 0) AS listCost,\n MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,\n MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at\n FROM steps st\n LEFT JOIN sessions s ON s.session_id = st.session_id\n ${clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\"}\n GROUP BY st.session_id\n ORDER BY last_at DESC\n LIMIT ?`,\n )\n .all(\n ...promptParams,\n ...params,\n limit,\n ) as (UsageRow & {\n session_id: string\n title: string | null\n directory: string | null\n parent_id: string | null\n providers: string | null\n models: string | null\n prompts: number | null\n first_at: number | null\n last_at: number | null\n })[]\n\n // The host's session cost includes compactions and titles; the session row\n // has to include them too, or it disagrees with the line's `sess` segment.\n const other = otherUsageBySession(db, range, options?.filters)\n return rows.map((row) => {\n const usage = usageFrom(row)\n const extra = other.get(row.session_id)?.cost ?? 0\n return {\n ...usage,\n cost: usage.cost + extra,\n sessionID: row.session_id,\n parentID: row.parent_id ?? undefined,\n title: row.title ?? undefined,\n directory: row.directory ?? undefined,\n providers: row.providers ? row.providers.split(\",\").filter(Boolean) : [],\n models: row.models ? row.models.split(\",\").filter(Boolean) : [],\n prompts: row.prompts ?? 0,\n otherCost: extra,\n firstAt: row.first_at ?? undefined,\n lastAt: row.last_at ?? undefined,\n cacheHitRatio: cacheHitRatio(usage),\n }\n })\n}\n\n/** Sessions whose parent is `parentID`: the subagents of one session. */\nexport function childSessionIDs(db: Database, parentID: string): string[] {\n return (db.query(\"SELECT session_id FROM sessions WHERE parent_id = ? ORDER BY session_id\").all(parentID) as { session_id: string }[]).map(\n (row) => row.session_id,\n )\n}\n\n/** Session usage rows for a specific set of sessions (subagent rollups). */\nexport function sessionUsageOf(db: Database, sessionIDs: readonly string[]): SessionUsage[] {\n return sessions(db, { sessionIDs, limit: sessionIDs.length })\n}\n\nexport type TurnDrop = {\n messageID: string\n tokens: number\n gapMs: number | undefined\n}\n\n/**\n * One finished turn of a session, built from the recorded steps and prompts. It\n * carries the same buckets the telemetry line uses, so the panel can render the\n * per-prompt history with the line's own formatter.\n */\nexport type TurnUsage = {\n sessionID: string\n /** Creation time of the prompt that opened the turn, when it was recorded. */\n promptAt: number | undefined\n endAt: number | undefined\n /**\n * Wall time of the turn's execution: the first step's request to the last\n * step's completion. Tool-call gaps inside the turn are included; time spent\n * queued before the first request is not.\n */\n durationMs: number | undefined\n /** Time between the previous finished turn's prompt and this turn's prompt. */\n promptGapMs: number | undefined\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n providerChanged: boolean\n modelChanged: boolean\n steps: number\n /** Raw buckets of the last step: the prompt the turn ended with. */\n latest: Usage\n /** Raw buckets summed over every step of the turn. */\n totals: Usage\n drops: TurnDrop[]\n /** Finish reason of the turn's last step. */\n finish: string | undefined\n /**\n * Tokens generated per second of streaming over the turn's steps: produced\n * tokens divided by their summed streaming windows. For a one-step turn it is\n * that step's rate.\n */\n tps: number | undefined\n}\n\ntype TurnStepRow = {\n message_id: string\n session_id: string\n provider_id: string | null\n model_id: string | null\n variant: string | null\n input_tokens: number | null\n cache_read: number | null\n cache_write: number | null\n output_tokens: number | null\n reasoning_tokens: number | null\n cost: number | null\n list_cost: number | null\n created_at: number | null\n streamed_at: number | null\n recorded_at: number\n completed_at: number | null\n finish: string | null\n}\n\n/** A turn is finished when its last step ended without asking for more tools. */\nfunction turnFinished(finish: string | null): boolean {\n return finish !== null && finish !== \"\" && finish !== \"tool-calls\"\n}\n\nfunction stepUsage(row: TurnStepRow): Usage {\n return {\n steps: 1,\n input: row.input_tokens ?? 0,\n cached: row.cache_read ?? 0,\n cacheWrite: row.cache_write ?? 0,\n output: row.output_tokens ?? 0,\n reasoning: row.reasoning_tokens ?? 0,\n cost: row.cost ?? 0,\n listCost: row.list_cost ?? 0,\n }\n}\n\n/** Structural view of a recorded step, so the shared cache-drop rule applies. */\nfunction stepMessage(row: TurnStepRow): AssistantMessage {\n return {\n type: \"assistant\",\n id: row.message_id,\n time: { created: row.created_at ?? row.recorded_at, completed: row.completed_at ?? undefined },\n model:\n row.provider_id !== null && row.model_id !== null\n ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined }\n : undefined,\n tokens: {\n input: row.input_tokens ?? 0,\n output: row.output_tokens ?? 0,\n reasoning: row.reasoning_tokens ?? 0,\n cache: { read: row.cache_read ?? 0, write: row.cache_write ?? 0 },\n },\n finish: row.finish ?? undefined,\n }\n}\n\n/**\n * Finished turns, newest first. Steps belong to the newest prompt recorded at or\n * before them; a turn whose last step asked for tools is dropped, because it is\n * still running — the same rule the telemetry line follows.\n *\n * For one session the read is bounded by a window of the newest prompts. The\n * window grows until it holds `limit` finished turns: a prompt can be empty\n * (the host records a synthetic system-reminder next to the user prompt) and\n * the newest turn can still be running, so a fixed one-prompt margin is not\n * enough. `complete` means the window covers every prompt of the session.\n */\nexport function turns(\n db: Database,\n options?: { sessionID?: string | undefined; range?: Range | undefined; filters?: Filters | undefined; limit?: number | undefined },\n): TurnUsage[] {\n const requested = options?.limit ?? 50\n const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50\n const filter = buildWhere(options?.range, options?.filters)\n const baseClauses = filter.where === \"\" ? [] : [filter.where.slice(\"WHERE \".length)]\n const baseParams: (number | string)[] = [...filter.params]\n if (options?.sessionID !== undefined) {\n baseClauses.push(\"session_id = ?\")\n baseParams.push(options.sessionID)\n }\n\n /** Read the turns inside the given prompt window, newest first. */\n function read(promptCount: number): { rows: TurnUsage[]; complete: boolean } {\n const clauses = [...baseClauses]\n const params = [...baseParams]\n const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount)\n if (floor !== undefined) {\n clauses.push(`${STEP_TIME} >= ?`)\n params.push(floor)\n }\n const steps = db\n .query(\n `SELECT message_id, session_id, provider_id, model_id, variant,\n input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,\n created_at, streamed_at, recorded_at, completed_at, finish\n FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\"}\n ORDER BY session_id, ${STEP_TIME}, message_id`,\n )\n .all(...params) as TurnStepRow[]\n\n const promptClause = options?.sessionID === undefined ? \"\" : `WHERE session_id = ?${floor === undefined ? \"\" : \" AND created_at >= ?\"}`\n const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor]\n const promptRows = db\n .query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`)\n .all(...promptParams) as { session_id: string; created_at: number | null }[]\n\n const promptsBySession = new Map<string, number[]>()\n for (const row of promptRows) {\n if (row.created_at === null) continue\n const list = promptsBySession.get(row.session_id) ?? []\n list.push(row.created_at)\n promptsBySession.set(row.session_id, list)\n }\n\n const result: TurnUsage[] = []\n let sessionID: string | undefined\n let bucket: TurnStepRow[] = []\n let promptIndex = -2\n let promptAt: number | undefined\n\n function close(): void {\n const last = bucket[bucket.length - 1]\n if (last === undefined || !turnFinished(last.finish)) {\n bucket = []\n return\n }\n const totals = emptyUsage()\n for (const row of bucket) addUsage(totals, stepUsage(row))\n const drops: TurnDrop[] = []\n let reference: AssistantMessage | undefined\n for (const row of bucket) {\n const message = stepMessage(row)\n const drop = cacheDrop(reference, message)\n if (drop !== undefined) {\n drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) })\n }\n reference = message\n }\n const providerID = last.provider_id ?? undefined\n const modelID = last.model_id ?? undefined\n const variant = last.variant ?? undefined\n let produced = 0\n let window = 0\n for (const row of bucket) {\n if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at) continue\n produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0)\n window += row.streamed_at - row.created_at\n }\n const previous = result.length > 0 && result[result.length - 1]!.sessionID === last.session_id ? result[result.length - 1] : undefined\n const endAt = last.completed_at ?? last.created_at ?? last.recorded_at\n // A turn starts when the first request goes out; a step recorded without\n // its own start stamp falls back to the prompt that opened the turn.\n const firstAt = bucket[0]?.created_at ?? promptAt\n result.push({\n sessionID: last.session_id,\n promptAt,\n endAt,\n durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,\n // The gap is against the previous *turn*, not the previous prompt row:\n // a synthetic system-reminder prompt can sit between two user turns.\n promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,\n providerID,\n modelID,\n variant,\n providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,\n modelChanged:\n previous !== undefined &&\n previous.providerID === providerID &&\n `${previous.modelID ?? \"\"}#${previous.variant ?? \"\"}` !== `${modelID ?? \"\"}#${variant ?? \"\"}`,\n steps: bucket.length,\n latest: stepUsage(last),\n totals,\n drops,\n finish: last.finish ?? undefined,\n tps: tokensPerSecond(produced, 0, window),\n })\n bucket = []\n }\n\n for (const row of steps) {\n if (row.session_id !== sessionID) {\n close()\n sessionID = row.session_id\n promptIndex = -2\n promptAt = undefined\n }\n const time = row.created_at ?? row.recorded_at\n const prompts = promptsBySession.get(row.session_id) ?? []\n let index = -1\n for (let candidate = prompts.length - 1; candidate >= 0; candidate -= 1) {\n if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {\n index = candidate\n break\n }\n }\n if (index !== promptIndex) {\n close()\n promptIndex = index\n promptAt = index >= 0 ? prompts[index] : undefined\n }\n bucket.push(row)\n }\n close()\n\n // Once the window reaches a prompt at or before the range's start, no older\n // prompt can be the newest one before a step inside the range: the window\n // already covers every turn the range can contain.\n const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from\n return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart }\n }\n\n let promptCount = Math.max(1, limit + 1)\n for (;;) {\n const { rows, complete } = read(promptCount)\n if (rows.length >= limit || complete) return rows.slice(0, limit)\n const next = promptCount * 2 + 1\n if (!Number.isFinite(next) || next <= promptCount) return rows.slice(0, limit)\n promptCount = next\n }\n}\n\n/**\n * Creation time of the `count`-th newest prompt of a session, or undefined\n * when it has fewer. Used to bound the steps a `turns` read has to load.\n */\nfunction promptFloor(db: Database, sessionID: string, count: number): number | undefined {\n const rows = db\n .query(\"SELECT created_at FROM prompts WHERE session_id = ? AND created_at IS NOT NULL ORDER BY created_at DESC LIMIT ?\")\n .all(sessionID, count) as { created_at: number }[]\n return rows.length === count ? rows[count - 1]!.created_at : undefined\n}\n\n// ---------------------------------------------------------------------------\n// Filter pickers\n// ---------------------------------------------------------------------------\n\nexport type FilterOption = { value: string; steps: number }\n\n/** Distinct models and providers, most used first. */\nexport function filterOptions(db: Database): { models: FilterOption[]; providers: FilterOption[] } {\n const pick = (column: string): FilterOption[] =>\n (\n db\n .query(`SELECT ${column} AS value, COUNT(*) AS steps FROM steps WHERE ${column} IS NOT NULL GROUP BY ${column} ORDER BY steps DESC`)\n .all() as { value: string; steps: number }[]\n ).map((row) => ({ value: row.value, steps: row.steps }))\n return { models: pick(\"model_id\"), providers: pick(\"provider_id\") }\n}\n",
12
- "/**\n * The analysis layer: the reports the panel and the CLI show.\n *\n * Two shapes, chosen by measurement rather than taste:\n *\n * 1. **Aggregates in SQLite** — totals, counts, distinct values. `coverageOf`\n * and the filter pickers never move a row into JavaScript.\n * 2. **Narrow rows plus arithmetic in JS** — percentiles, pair rules, calendar\n * buckets. SQLite's window functions cost about 17 µs per row per report\n * here (a sort plus a materialisation), while reading the four to twelve\n * columns a report actually needs costs 1–4 µs per row. The percentiles and\n * the pair comparisons are therefore computed over lean projections: on the\n * audit's 120k-step database a whole view costs a few hundred milliseconds,\n * and on a normal one it is instant.\n *\n * The rules are not restated here. Cache reuse, idle gaps and the noise\n * threshold come from `core.ts` — the same functions the live line uses — so\n * the panel and the line can never disagree about what a cache loss is.\n * `test/reports.test.ts` holds every report to those rules.\n */\n\nimport type { Database } from \"bun:sqlite\"\nimport { cacheDrop, stepGap, tokensPerSecond, type AssistantMessage } from \"../core\"\nimport {\n buildWhere,\n DEFAULT_TTL_HINT_MS,\n latencyStats,\n modelKey,\n modelLabel,\n percentile,\n type Filters,\n type LatencyStats,\n type OtherUsageRow,\n type Range,\n type Usage,\n} from \"./queries\"\n\n/** The step's own clock, the expression the `steps_at` index covers. */\nexport const STEP_AT = \"COALESCE(created_at, recorded_at)\"\n\ntype Options = { range?: Range | undefined; filters?: Filters | undefined }\n\n// ---------------------------------------------------------------------------\n// Lean projections\n// ---------------------------------------------------------------------------\n\n/**\n * Turn `null` into `undefined` in place, so a row costs one object and not two.\n * Every query aliases its columns to the field names they are read through;\n * only the optional ones have to be normalized.\n */\nfunction normalize<Row>(rows: Row[], optional: readonly string[]): Row[] {\n for (const row of rows as unknown as Array<Record<string, unknown>>) {\n for (const key of optional) if (row[key] === null) row[key] = undefined\n }\n return rows\n}\n\nfunction groupBy<Value, Key>(items: readonly Value[], key: (item: Value) => Key): Map<Key, Value[]> {\n const groups = new Map<Key, Value[]>()\n for (const item of items) {\n const group = key(item)\n const list = groups.get(group)\n if (list !== undefined) list.push(item)\n else groups.set(group, [item])\n }\n return groups\n}\n\n/** One recorded step, as the reports read it. */\nexport type StepRow = {\n messageID: string\n sessionID: string\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n input: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n listCost: number\n createdAt: number | undefined\n streamedAt: number | undefined\n completedAt: number | undefined\n /** `COALESCE(created_at, recorded_at)`: the ordering time of the step. */\n at: number\n /** Set on the single step loaded before the range, as a reference. */\n boundary?: boolean | undefined\n}\n\nconst STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,\n model_id AS modelID, variant,\n COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,\n COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,\n COALESCE(list_cost, 0) AS listCost,\n created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`\n\nconst STEP_OPTIONAL = [\"providerID\", \"modelID\", \"variant\", \"createdAt\", \"streamedAt\", \"completedAt\"] as const\n\n/**\n * A step as the pair reports read it. Their projection leaves the generated\n * tokens out (nothing they compute sums them), and the type says so: an\n * aggregate that reads `output` cannot be handed a pair row by mistake.\n */\nexport type PairRow = Omit<StepRow, \"output\" | \"reasoning\">\n\n/** The pair reports read no generated tokens: `output` and `reasoning` stay out. */\nconst PAIR_COLUMNS = STEP_COLUMNS.replace(\"COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, \", \"\")\n\n/** The steps of the range, narrow. Ordering is only paid for where it is read. */\nexport function stepRows(db: Database, options?: Options): StepRow[] {\n const filter = buildWhere(options?.range, options?.filters)\n const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params) as Array<Record<string, unknown>>\n return normalize(rows, STEP_OPTIONAL) as StepRow[]\n}\n\n/**\n * The steps of the range plus, for every session with a step inside it, the one\n * step before the range: the pair reports compare a step with the one that\n * preceded it, so the first step of a range has to see it.\n *\n * The boundary is one seek per session on the `(session_id, time)` index — a\n * few milliseconds for a far wider history — never the whole history of the\n * sessions in range.\n */\nexport function cachePairs(db: Database, options?: Options): PairRow[] {\n const filter = buildWhere(options?.range, options?.filters)\n const rows = normalize(\n db\n .query(`SELECT ${PAIR_COLUMNS} FROM steps ${filter.where} ORDER BY session_id, ${STEP_AT}, message_id`)\n .all(...filter.params) as Array<Record<string, unknown>>,\n STEP_OPTIONAL,\n ) as PairRow[]\n const from = options?.range?.from\n if (from === undefined || rows.length === 0) return rows\n const seek = db.query(\n `SELECT ${PAIR_COLUMNS} FROM steps\n WHERE session_id = ? AND COALESCE(created_at, recorded_at) < ?\n ORDER BY COALESCE(created_at, recorded_at) DESC, message_id DESC LIMIT 1`,\n )\n for (const sessionID of new Set(rows.map((row) => row.sessionID))) {\n const boundary = seek.get(sessionID, from) as Record<string, unknown> | null\n if (boundary === null) continue\n const step = normalize([boundary], STEP_OPTIONAL)[0] as PairRow\n step.boundary = true\n rows.push(step)\n }\n rows.sort((left, right) => {\n if (left.sessionID !== right.sessionID) return left.sessionID < right.sessionID ? -1 : 1\n if (left.at !== right.at) return left.at - right.at\n return left.messageID < right.messageID ? -1 : left.messageID > right.messageID ? 1 : 0\n })\n return rows\n}\n\n/** The same step in the message shape the shared pair rules are written for. */\nfunction message(step: PairRow): AssistantMessage {\n return {\n type: \"assistant\",\n id: step.messageID,\n ...(step.modelID === undefined\n ? {}\n : { model: { providerID: step.providerID ?? \"\", id: step.modelID, ...(step.variant === undefined ? {} : { variant: step.variant }) } }),\n tokens: { cache: { read: step.cached } },\n time: {\n ...(step.createdAt === undefined ? {} : { created: step.createdAt }),\n ...(step.streamedAt === undefined ? {} : { streamed: step.streamedAt }),\n ...(step.completedAt === undefined ? {} : { completed: step.completedAt }),\n },\n }\n}\n\n/** Consecutive steps of the same session, in order. */\nfunction pairsOf(rows: readonly PairRow[]): Array<{ previous: PairRow; current: PairRow }> {\n const pairs: Array<{ previous: PairRow; current: PairRow }> = []\n for (let index = 1; index < rows.length; index += 1) {\n const previous = rows[index - 1]!\n const current = rows[index]!\n if (previous.sessionID !== current.sessionID) continue\n pairs.push({ previous, current })\n }\n return pairs\n}\n\ntype Counted = { input: number; cached: number; cacheWrite: number; output: number; reasoning: number; cost: number; listCost: number }\n\n/** The buckets the panel and the line agree on. */\nfunction usageOf(steps: readonly Counted[]): Usage {\n const usage: Usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 }\n for (const step of steps) {\n usage.steps += 1\n usage.input += step.input\n usage.cached += step.cached\n usage.cacheWrite += step.cacheWrite\n usage.output += step.output\n usage.reasoning += step.reasoning\n usage.cost += step.cost\n usage.listCost += step.listCost\n }\n return usage\n}\n\n// ---------------------------------------------------------------------------\n// Coverage\n// ---------------------------------------------------------------------------\n\nexport type CoverageReport = {\n steps: number\n models: number\n /** Providers the steps ran through. A step whose provider is unknown is counted nowhere. */\n providers: number\n missingModel: number\n unsettled: number\n missingTps: number\n firstAt: number | undefined\n lastAt: number | undefined\n}\n\n/**\n * What the panel cannot answer honestly: how many steps lack a model, and how\n * many never settled. A zero in the switch counts means \"never switched\" only\n * when this coverage is complete.\n */\nexport function coverageOf(db: Database, options?: Options): CoverageReport {\n const filter = buildWhere(options?.range, options?.filters)\n const row = db\n .query(\n `SELECT COUNT(*) AS steps,\n COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,\n COUNT(DISTINCT provider_id) AS providers,\n COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,\n COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,\n COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at THEN 0 ELSE 1 END), 0) AS missingTps,\n MIN(${STEP_AT}) AS firstAt,\n MAX(${STEP_AT}) AS lastAt\n FROM steps ${filter.where}`,\n )\n .get(...filter.params) as {\n steps: number\n models: number\n providers: number\n missingModel: number\n unsettled: number\n missingTps: number\n firstAt: number | null\n lastAt: number | null\n }\n return {\n steps: row.steps,\n models: row.models,\n providers: row.providers,\n missingModel: row.missingModel,\n unsettled: row.unsettled,\n missingTps: row.missingTps,\n firstAt: row.firstAt ?? undefined,\n lastAt: row.lastAt ?? undefined,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Latency\n// ---------------------------------------------------------------------------\n\n/** The steps a latency report is built from. It reads no generated tokens. */\ntype GroupedRow = StepRow\n\nfunction groupedRows(db: Database, options?: Options): GroupedRow[] {\n const filter = buildWhere(options?.range, options?.filters)\n const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params) as Array<Record<string, unknown>>\n return normalize(rows, STEP_OPTIONAL) as StepRow[]\n}\n\n/** The three measures a latency report is made of. */\nfunction timingOf(step: StepRow): { wall: number | undefined; stream: number | undefined; tps: number | undefined } {\n // A clock adjustment can stamp a step as completed before it was created.\n // A negative wall time is not a latency; it would also drag the percentiles\n // down, so the window is clamped at zero.\n const wall =\n step.createdAt !== undefined && step.completedAt !== undefined\n ? Math.max(0, step.completedAt - step.createdAt)\n : undefined\n const stream =\n step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined\n return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) }\n}\n\nexport type LatencyReport = {\n wall: LatencyStats\n stream: LatencyStats\n tps: LatencyStats\n}\n\n/** The timings of the range: one read, shared by the overall report and the groups. */\nexport function timingRows(db: Database, options?: Options): GroupedRow[] {\n return groupedRows(db, options)\n}\n\n/** Overall wall time, streaming window and throughput percentiles. */\nexport function latencyOf(rows: readonly StepRow[]): LatencyReport {\n const wall: number[] = []\n const stream: number[] = []\n const tps: number[] = []\n for (const step of rows) {\n const timing = timingOf(step)\n if (timing.wall !== undefined) wall.push(timing.wall)\n if (timing.stream !== undefined) stream.push(timing.stream)\n if (timing.tps !== undefined) tps.push(timing.tps)\n }\n return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) }\n}\n\nexport type LatencyGroupRow = {\n key: string\n label: string\n count: number\n usage: Usage\n wall: LatencyStats\n stream: LatencyStats\n tps: LatencyStats\n}\n\nexport type Dimension = \"model\" | \"provider\"\n\n/** Wall, streaming window and throughput percentiles per group. */\nexport function latencyGroupsOf(rows: readonly StepRow[], by: Dimension): LatencyGroupRow[] {\n const key = (step: StepRow) => (by === \"model\" ? modelKey(step.modelID ?? \"(unknown)\", step.variant) : step.providerID ?? \"(unknown)\")\n const groups: LatencyGroupRow[] = []\n for (const [group, steps] of groupBy(rows, key)) {\n const wall: number[] = []\n const stream: number[] = []\n const tps: number[] = []\n for (const step of steps) {\n const timing = timingOf(step)\n if (timing.wall !== undefined) wall.push(timing.wall)\n if (timing.stream !== undefined) stream.push(timing.stream)\n if (timing.tps !== undefined) tps.push(timing.tps)\n }\n const [modelID, variant] = group.split(\"#\")\n groups.push({\n key: group,\n label: by === \"model\" ? (variant === undefined || variant === \"\" ? modelID! : `${modelID} ${variant}`) : group,\n count: steps.length,\n usage: usageOf(steps),\n wall: latencyStats(wall),\n stream: latencyStats(stream),\n tps: latencyStats(tps),\n })\n }\n return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key))\n}\n\n// ---------------------------------------------------------------------------\n// Cache reuse\n// ---------------------------------------------------------------------------\n\nexport type CacheStats = {\n steps: number\n input: number\n cached: number\n cacheWrite: number\n /** The whole prompt the provider saw: `cached + input + cache_write`. */\n prompt: number\n /** Token-weighted reuse over the whole selection. */\n hit: number | undefined\n /** Median of the per-step reuse ratios: a few huge steps cannot hide a split pattern. */\n hitP50: number | undefined\n}\n\nconst EMPTY_CACHE: CacheStats = { steps: 0, input: 0, cached: 0, cacheWrite: 0, prompt: 0, hit: undefined, hitP50: undefined }\n\n/** Reuse of the prompt cache over a set of steps. */\nfunction cacheStatsOfSteps(steps: readonly { input: number; cached: number; cacheWrite: number }[]): CacheStats {\n let input = 0\n let cached = 0\n let cacheWrite = 0\n const ratios: number[] = []\n for (const step of steps) {\n input += step.input\n cached += step.cached\n cacheWrite += step.cacheWrite\n const prompt = step.input + step.cached + step.cacheWrite\n if (prompt > 0) ratios.push(step.cached / prompt)\n }\n const prompt = input + cached + cacheWrite\n return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) }\n}\n\n/** Reuse of the prompt cache over the range, as one row. */\nexport function cacheStatsOf(db: Database, options?: Options): CacheStats {\n const rows = stepRows(db, options)\n return rows.length === 0 ? EMPTY_CACHE : cacheStatsOfSteps(rows)\n}\n\nexport type CacheModelRow = {\n modelID: string\n variant: string | undefined\n cache: CacheStats\n}\n\n/**\n * Reuse of the prompt cache per model, most cached first, over the steps of the\n * range. A boundary step is not part of the range, so it is left out.\n */\nexport function cacheStatsByModel(rows: readonly PairRow[]): CacheModelRow[] {\n const out: CacheModelRow[] = []\n const inRange = rows.filter((row) => row.boundary !== true)\n for (const [, group] of groupBy(inRange, (row) => modelKey(row.modelID ?? \"(unknown)\", row.variant))) {\n out.push({ modelID: group[0]!.modelID ?? \"(unknown)\", variant: group[0]!.variant, cache: cacheStatsOfSteps(group) })\n }\n return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID))\n}\n\n// ---------------------------------------------------------------------------\n// Pairs: switches, cache survival, TTL, losses\n// ---------------------------------------------------------------------------\n\nexport type SwitchRow = {\n modelID: string\n variant: string | undefined\n steps: number\n pairs: number\n /** Steps whose model, variant or provider differed from the step before. */\n changes: number\n /** Of those, the ones whose model (or variant) differed. */\n modelChanges: number\n /** Of those, the ones whose provider differed. */\n providerChanges: number\n /** Cache the changes cost: only a provider switch can forfeit a reusable cache. */\n cacheLost: number\n cacheLostEvents: number\n}\n\nexport type SwitchReport = {\n rows: SwitchRow[]\n totals: { pairs: number; changes: number; cacheLost: number; cacheLostEvents: number }\n}\n\n/**\n * Switches between consecutive steps of a session, by the two dimensions that\n * decide which cache holds the work: the model (with its variant) and the\n * provider.\n *\n * A switch is not by itself a fault — it is usually the user choosing another\n * model — so the report only names a cost where one is measurable: a provider\n * switch that leaves the model intact forfeits the cache the previous provider\n * held. A model switch has no measurable cost by definition, because two models\n * never share a cache to lose.\n */\nexport function switchesOf(rows: readonly PairRow[]): SwitchReport {\n const perModel = new Map<string, SwitchRow>()\n const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 }\n\n for (const { previous, current } of pairsOf(rows)) {\n if (previous.modelID === undefined || current.modelID === undefined) continue\n const key = modelKey(current.modelID, current.variant)\n const row = perModel.get(key) ?? {\n modelID: current.modelID,\n variant: current.variant,\n steps: 0,\n pairs: 0,\n changes: 0,\n modelChanges: 0,\n providerChanges: 0,\n cacheLost: 0,\n cacheLostEvents: 0,\n }\n row.steps += 1\n row.pairs += 1\n totals.pairs += 1\n\n const modelChanged = key !== modelKey(previous.modelID, previous.variant)\n const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID\n if (modelChanged) row.modelChanges += 1\n if (providerChanged) row.providerChanges += 1\n if (modelChanged || providerChanged) {\n row.changes += 1\n totals.changes += 1\n // The scope is the model alone: a provider switch forfeits the cache the\n // previous provider held, and that is the cost this report names.\n const lost = cacheDrop(message(previous), message(current), \"model\")\n if (lost !== undefined) {\n row.cacheLost += lost\n row.cacheLostEvents += 1\n totals.cacheLost += lost\n totals.cacheLostEvents += 1\n }\n }\n perModel.set(key, row)\n }\n\n return {\n rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),\n totals,\n }\n}\n\nexport type GapBucket = {\n label: string\n samples: number\n /** Pairs that still reused the prompt cache. */\n retained: number\n drops: number\n lostTokens: number\n retainedRatio: number | undefined\n}\n\nexport type ProviderReuseRow = {\n /** The provider, or `(unknown)` when a step ran without one. */\n provider: string\n samples: number\n retained: number\n drops: number\n lostTokens: number\n retainedRatio: number | undefined\n}\n\nexport type GapReport = {\n buckets: GapBucket[]\n providers: ProviderReuseRow[]\n samples: number\n}\n\n/**\n * Idle-gap buckets. The cache cliff sits in the 15–60m window, so that hour is\n * split in four: the coarse buckets would fold a TTL boundary into one row.\n */\nexport const GAP_BUCKETS: ReadonlyArray<readonly [string, number, number | undefined]> = [\n [\"<1m\", 0, 60_000],\n [\"1–5m\", 60_000, 5 * 60_000],\n [\"5–15m\", 5 * 60_000, 15 * 60_000],\n [\"15–20m\", 15 * 60_000, 20 * 60_000],\n [\"20–30m\", 20 * 60_000, 30 * 60_000],\n [\"30–45m\", 30 * 60_000, 45 * 60_000],\n [\"45–60m\", 45 * 60_000, 60 * 60_000],\n [\"1–6h\", 60 * 60_000, 6 * 60 * 60_000],\n [\">6h\", 6 * 60 * 60_000, undefined],\n]\n\nfunction bucketFor(gapMs: number): number {\n const index = GAP_BUCKETS.findIndex(([, from, to]) => gapMs >= from && (to === undefined || gapMs < to))\n return index === -1 ? GAP_BUCKETS.length - 1 : index\n}\n\n/**\n * How long an idle gap the prompt cache survives, per gap bucket and per\n * provider. Only pairs of the same model are comparable, which is exactly the\n * set the cache rule already uses.\n */\nexport function gapReportOf(rows: readonly PairRow[]): GapReport {\n const buckets: GapBucket[] = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }))\n const providers = new Map<string, ProviderReuseRow>()\n let samples = 0\n\n for (const { previous, current } of pairsOf(rows)) {\n if (previous.modelID === undefined || current.modelID === undefined) continue\n if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant)) continue\n // A pair that switched provider is not a survival sample: the switch\n // tally owns that case, and a switch is not an idle gap.\n if ((previous.providerID ?? \"\") !== (current.providerID ?? \"\")) continue\n const gap = stepGap(message(previous), message(current))\n if (gap === undefined) continue\n const lost = cacheDrop(message(previous), message(current))\n const bucket = buckets[bucketFor(gap)]!\n bucket.samples += 1\n samples += 1\n if (lost === undefined) bucket.retained += 1\n else {\n bucket.drops += 1\n bucket.lostTokens += lost\n }\n\n const provider = current.providerID ?? previous.providerID ?? \"(unknown)\"\n const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }\n row.samples += 1\n if (lost === undefined) row.retained += 1\n else {\n row.drops += 1\n row.lostTokens += lost\n }\n providers.set(provider, row)\n }\n\n for (const bucket of buckets) bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined\n for (const row of providers.values()) row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined\n return {\n buckets,\n providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),\n samples,\n }\n}\n\nexport type TtlEvidenceRow = {\n providerID: string\n modelID: string\n samples: number\n /** Largest idle gap that still hit the cache. */\n maxHitGapMs: number | undefined\n /** Smallest idle gap after which reuse was lost. */\n minDropGapMs: number | undefined\n}\n\n/**\n * Empirical bounds on the provider cache TTL: the longest idle gap that still\n * reused the cache, and the shortest gap that lost it. Comparing the two per\n * provider turns TTL guesses into observations.\n */\nexport function ttlEvidenceOf(rows: readonly PairRow[]): TtlEvidenceRow[] {\n const evidence = new Map<string, TtlEvidenceRow>()\n\n for (const { previous, current } of pairsOf(rows)) {\n if (previous.modelID === undefined || current.modelID === undefined) continue\n const key = `${current.providerID ?? \"\"}/${current.modelID}`\n const before = `${previous.providerID ?? \"\"}/${previous.modelID}#${previous.variant ?? \"\"}`\n const after = `${current.providerID ?? \"\"}/${current.modelID}#${current.variant ?? \"\"}`\n if (before !== after) continue\n\n const row = evidence.get(key) ?? {\n providerID: current.providerID ?? \"(unknown)\",\n modelID: current.modelID,\n samples: 0,\n maxHitGapMs: undefined,\n minDropGapMs: undefined,\n }\n row.samples += 1\n const gapMs = stepGap(message(previous), message(current))\n if (gapMs !== undefined) {\n const lost = cacheDrop(message(previous), message(current))\n if (lost === undefined) row.maxHitGapMs = row.maxHitGapMs === undefined ? gapMs : Math.max(row.maxHitGapMs, gapMs)\n else row.minDropGapMs = row.minDropGapMs === undefined ? gapMs : Math.min(row.minDropGapMs, gapMs)\n }\n evidence.set(key, row)\n }\n return [...evidence.values()].sort(\n (left, right) => right.samples - left.samples || `${left.providerID}/${left.modelID}`.localeCompare(`${right.providerID}/${right.modelID}`),\n )\n}\n\nexport type DropReason = \"compaction\" | \"expired\" | \"unknown\"\n\nexport type CacheDropRow = {\n sessionID: string\n messageID: string\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n at: number\n tokens: number\n gapMs: number | undefined\n prevCached: number\n reason: DropReason\n}\n\n/**\n * Cache reuse losses with a best-effort reason: a compaction in between, an\n * idle gap long enough to be provider-side expiry, or unknown.\n *\n * Compactions come from the `events` table: one query for the sessions in\n * play, never one per loss.\n */\nexport function cacheDropsOf(db: Database, rows: readonly PairRow[], options?: { ttlHintMs?: number }): CacheDropRow[] {\n const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS\n const losses: Array<{ previous: PairRow; current: PairRow; tokens: number; gapMs: number | undefined }> = []\n for (const { previous, current } of pairsOf(rows)) {\n // The model scope: a provider switch forfeits the cache the previous\n // provider held, which is a loss like any other.\n const tokens = cacheDrop(message(previous), message(current), \"model\")\n if (tokens === undefined) continue\n losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) })\n }\n if (losses.length === 0) return []\n\n const compactions = new Map<string, number[]>()\n const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))]\n const events = db\n .query(\n `SELECT session_id, at FROM events\n WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => \"?\").join(\", \")})\n ORDER BY at`,\n )\n .all(...sessionIDs) as { session_id: string; at: number }[]\n for (const event of events) {\n const list = compactions.get(event.session_id)\n if (list !== undefined) list.push(event.at)\n else compactions.set(event.session_id, [event.at])\n }\n\n return losses\n .map((loss) => {\n const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt\n const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at)\n const reason: DropReason = compacted ? \"compaction\" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? \"expired\" : \"unknown\"\n return {\n sessionID: loss.current.sessionID,\n messageID: loss.current.messageID,\n providerID: loss.current.providerID,\n modelID: loss.current.modelID,\n variant: loss.current.variant,\n at: loss.current.at,\n tokens: loss.tokens,\n gapMs: loss.gapMs,\n prevCached: loss.previous.cached,\n reason,\n }\n })\n .sort((left, right) => left.at - right.at)\n}\n\n// ---------------------------------------------------------------------------\n// Providers\n// ---------------------------------------------------------------------------\n\nexport type ProviderSummary = {\n /** The provider, or undefined for steps recorded without one. */\n provider: string | undefined\n /** Models this provider served. */\n models: string[]\n share: number\n usage: Usage\n cache: CacheStats\n tps: number | undefined\n wall: number | undefined\n firstAt: number | undefined\n lastAt: number | undefined\n}\n\nexport type ProviderRow = ProviderSummary & {\n modelID: string\n variant: string | undefined\n}\n\n/** The numbers of one group of steps. */\nfunction groupValues(steps: readonly StepRow[]): { cache: CacheStats; tps: number | undefined; wall: number | undefined } {\n const wall: number[] = []\n const tps: number[] = []\n for (const step of steps) {\n const timing = timingOf(step)\n if (timing.wall !== undefined) wall.push(timing.wall)\n if (timing.tps !== undefined) tps.push(timing.tps)\n }\n return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 }\n}\n\nfunction providerOf(steps: readonly StepRow[], models: string): Omit<ProviderSummary, \"provider\"> & { provider: string | undefined } {\n const values = groupValues(steps)\n // A long-lived provider can hold a million steps. Spreading that into\n // `Math.min`/`Math.max` exceeds the call-stack argument limit, so the bounds\n // are folded instead.\n let firstAt: number | undefined\n let lastAt: number | undefined\n for (const step of steps) {\n if (firstAt === undefined || step.at < firstAt) firstAt = step.at\n if (lastAt === undefined || step.at > lastAt) lastAt = step.at\n }\n return {\n provider: steps[0]!.providerID,\n models: models.split(\"\\u0000\"),\n share: 0,\n usage: usageOf(steps),\n cache: values.cache,\n tps: values.tps,\n wall: values.wall,\n firstAt,\n lastAt,\n }\n}\n\nconst modelNames = (steps: readonly StepRow[]): string =>\n [...new Set(steps.map((step) => modelKey(step.modelID ?? \"(unknown)\", step.variant)))].map((key) => modelLabel(key.slice(0, key.indexOf(\"#\")), key.slice(key.indexOf(\"#\") + 1) || undefined)).join(\"\\u0000\")\n\n/** One row per provider, over every model it served. */\nexport function providerSummaryOf(rows: readonly StepRow[]): ProviderSummary[] {\n const out: ProviderSummary[] = []\n for (const steps of groupBy(rows, (step) => step.providerID ?? \"\").values()) {\n const summary = providerOf(steps, modelNames(steps))\n out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length })\n }\n return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? \"\").localeCompare(right.provider ?? \"\"))\n}\n\n/** One row per model × provider: through which provider each model ran, and how much. */\nexport function providerBreakdownOf(rows: readonly StepRow[]): ProviderRow[] {\n const out: ProviderRow[] = []\n for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? \"(unknown)\", step.variant))) {\n for (const steps of groupBy(modelRows, (step) => step.providerID ?? \"\").values()) {\n const [modelID, variant] = [model.slice(0, model.indexOf(\"#\")), model.slice(model.indexOf(\"#\") + 1)]\n out.push({\n // One row per model, so its `models` field names that one model — in the\n // same label form the provider summary uses.\n ...providerOf(steps, modelNames(steps)),\n modelID,\n variant: variant === \"\" ? undefined : variant,\n share: steps.length / modelRows.length,\n })\n }\n }\n return out.sort((left, right) => right.usage.steps - left.usage.steps || right.cache.cached - left.cache.cached)\n}\n\n// ---------------------------------------------------------------------------\n// Calendar periods\n// ---------------------------------------------------------------------------\n\nexport type PeriodGranularity = \"day\" | \"week\" | \"month\"\n\nexport type PeriodRow = {\n key: string\n label: string\n /** Start of the bucket, local time. */\n at: number\n steps: number\n sessions: number\n usage: Usage\n cache: CacheStats\n /** Compaction/title money included in `usage.cost`, when the period has any. */\n otherCost?: number | undefined\n}\n\n/** ISO-8601 week number and its Monday, in local time. */\nexport function isoWeek(date: Date): { year: number; week: number; monday: Date } {\n const monday = new Date(date.getFullYear(), date.getMonth(), date.getDate())\n monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7))\n const thursday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 3)\n const firstThursday = new Date(thursday.getFullYear(), 0, 4)\n firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3)\n const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000))\n return { year: thursday.getFullYear(), week, monday }\n}\n\n/** Local end (exclusive) of the period that starts at `at`. */\nexport function periodEnd(at: number, granularity: PeriodGranularity): number {\n const date = new Date(at)\n if (granularity === \"month\") return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime()\n if (granularity === \"week\") return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime()\n return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime()\n}\n\n/** Key, label and local start of the period `at` falls in. */\nexport function periodStart(at: number, granularity: PeriodGranularity): { key: string; label: string; start: number } {\n const date = new Date(at)\n const pad = (value: number) => String(value).padStart(2, \"0\")\n if (granularity === \"month\") {\n const start = new Date(date.getFullYear(), date.getMonth(), 1)\n return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() }\n }\n if (granularity === \"week\") {\n const { year, week, monday } = isoWeek(date)\n return { key: `${year}-W${pad(week)}`, label: `${year}-W${pad(week)}`, start: monday.getTime() }\n }\n const start = new Date(date.getFullYear(), date.getMonth(), date.getDate())\n const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`\n return { key, label: key, start: start.getTime() }\n}\n\n/**\n * Totals per local calendar day, week or month, oldest first.\n *\n * `otherRows` are the host's non-step usage records (compaction and title\n * generations). Their cost is added to the bucket they fall in, because the\n * session's own total includes it; the token buckets stay step-based.\n */\nexport function periodsOf(\n rows: readonly StepRow[],\n granularity: PeriodGranularity,\n otherRows: readonly OtherUsageRow[] = [],\n): PeriodRow[] {\n const byKey = new Map<string, PeriodRow>()\n for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {\n const period = periodStart(steps[0]!.at, granularity)\n byKey.set(key, {\n key,\n label: period.label,\n at: period.start,\n steps: steps.length,\n sessions: new Set(steps.map((step) => step.sessionID)).size,\n usage: usageOf(steps),\n cache: cacheStatsOfSteps(steps),\n })\n }\n for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {\n const cost = group.reduce((sum, row) => sum + row.cost, 0)\n const existing = byKey.get(key)\n if (existing !== undefined) {\n existing.usage.cost += cost\n existing.otherCost = (existing.otherCost ?? 0) + cost\n continue\n }\n // A period with a compaction or title but no assistant step still has a\n // cost and a session: it must not disappear from the calendar.\n const period = periodStart(group[0]!.at, granularity)\n byKey.set(key, {\n key,\n label: period.label,\n at: period.start,\n steps: 0,\n sessions: new Set(group.map((row) => row.sessionID)).size,\n usage: { ...usageOf([]), cost },\n cache: cacheStatsOfSteps([]),\n otherCost: cost,\n })\n }\n return [...byKey.values()].sort((left, right) => left.at - right.at)\n}\n",
15
+ "/**\n * Pure turn accounting shared by the TUI line, the server recorder and the\n * stats engine.\n *\n * Everything here operates on structural shapes that mirror the session\n * messages published by OpenCode, so the logic stays testable without a host\n * runtime and without the effect-based schema types.\n */\n\nexport type ModelRefLike = {\n providerID: string\n id: string\n variant?: string | undefined\n}\n\nexport type AssistantMessage = {\n type: \"assistant\"\n id: string\n time?:\n | { created?: number | undefined; firstToken?: number | undefined; streamed?: number | undefined; completed?: number | undefined }\n | undefined\n model?: ModelRefLike | undefined\n tokens?:\n | {\n input?: number | undefined\n output?: number | undefined\n reasoning?: number | undefined\n cache?: { read?: number | undefined; write?: number | undefined } | undefined\n }\n | undefined\n cost?: number | undefined\n /** List-price estimate for a step the host reported as costing nothing. */\n listCost?: number | undefined\n finish?: string | null | undefined\n rawFinish?: string | null | undefined\n}\n\nexport type PromptMessage = {\n type: \"user\" | \"synthetic\" | \"system\"\n id?: string | undefined\n time?: { created?: number | undefined } | undefined\n}\n\nexport type TranscriptMessage =\n | AssistantMessage\n | PromptMessage\n | { type: string; id?: string | undefined; time?: { created?: number | undefined } | undefined }\n\n/** Accumulated token usage for a group of assistant steps. */\nexport type Totals = {\n input: number\n cached: number\n output: number\n reasoning: number\n cacheWrite: number\n cost: number\n /** Sum of list-price estimates for steps the host reported as $0. */\n listCost: number\n steps: number\n}\n\nexport type CacheDrop = {\n messageID: string\n /** Tokens that were expected to hit the prompt cache but did not. */\n tokens: number\n /** `cache.read` of the step that was used as the reuse reference. */\n prevCached: number\n /** Time between the reference step's completion and this step's request. */\n gapMs: number | undefined\n}\n\nexport type TurnStats = {\n /** Wall clock time of the last step's completion. */\n endAt: number | undefined\n /** Creation time of the first settled step of the turn. */\n startAt: number | undefined\n /** Creation time of the prompt that opened this turn. */\n promptAt: number | undefined\n /** Time between the previous prompt and this turn's prompt. */\n promptGapMs: number | undefined\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n /** Provider ID differs from the previous turn in the same transcript. */\n providerChanged: boolean\n /** Provider is the same but the model or variant differs. */\n modelChanged: boolean\n totals: Totals\n /** Passed through from the caller (session-wide accumulated usage). */\n session: Totals | undefined\n /**\n * Prompt-side usage of the last finished step: the context the turn ended\n * with. Summing `input`/`cached` over the steps of a turn counts the same\n * re-sent prompt once per step, which is not what a context view means.\n */\n latest: Totals\n drops: CacheDrop[]\n cacheDropTokens: number\n cacheExpired: boolean\n /** Assistant steps in the turn. */\n steps: number\n}\n\nexport type TurnSegment = {\n assistants: AssistantMessage[]\n prompt: TranscriptMessage | undefined\n}\n\n/** Message types that open a turn: a run of assistants belongs to the last one. */\nexport const PROMPT_BOUNDARIES: ReadonlySet<string> = new Set([\"user\", \"synthetic\", \"system\"])\n\n/**\n * Split a transcript into turns. A turn is a run of assistant steps opened by\n * a prompt boundary (`user`, `synthetic`, `system`). Idle notices, info\n * messages, compactions and shell entries keep the current turn open so a\n * single execution is never split in two.\n */\nexport function transcriptSegments(messages: readonly TranscriptMessage[]): TurnSegment[] {\n const segments: TurnSegment[] = []\n let current: AssistantMessage[] = []\n let prompt: TranscriptMessage | undefined\n\n for (const message of messages) {\n if (message.type === \"assistant\") {\n current.push(message as AssistantMessage)\n continue\n }\n if (!PROMPT_BOUNDARIES.has(message.type)) continue\n if (current.length > 0) {\n segments.push({ assistants: current, prompt })\n current = []\n }\n prompt = message\n }\n if (current.length > 0) segments.push({ assistants: current, prompt })\n return segments\n}\n\n/**\n * The last `count` segments, found by walking the transcript backwards. The\n * live line only needs the turn that just ended and the one before it, and a\n * long session holds tens of thousands of messages: the tail walk stops as\n * soon as it has them, instead of building a segment for every turn.\n */\nexport function transcriptTail(messages: readonly TranscriptMessage[], count: number): TurnSegment[] {\n const segments: TurnSegment[] = []\n let current: AssistantMessage[] = []\n\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!\n if (message.type === \"assistant\") {\n current.unshift(message as AssistantMessage)\n continue\n }\n if (!PROMPT_BOUNDARIES.has(message.type)) continue\n if (current.length === 0) continue\n // The boundary closes the run collected after it.\n segments.unshift({ assistants: current, prompt: message })\n if (segments.length >= count) return segments\n current = []\n }\n // A leading run with no prompt before it is a segment of its own.\n if (current.length > 0 && segments.length < count) segments.unshift({ assistants: current, prompt: undefined })\n return segments\n}\n\n/**\n * A token count or a timestamp read from a host message: `undefined` for a\n * timestamp that is not a finite number, zero for a count that is not. The\n * recorder applies the same rule before SQLite; doing it here keeps the live\n * line on the same footing when a payload is malformed.\n */\nfunction countOf(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0\n}\n\nfunction amountOf(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : 0\n}\n\nfunction stampOf(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined\n}\n\nexport function tokenCounts(message: AssistantMessage): { input: number; output: number; reasoning: number; read: number; write: number } {\n const tokens = message.tokens\n return {\n input: countOf(tokens?.input),\n output: countOf(tokens?.output),\n reasoning: countOf(tokens?.reasoning),\n read: countOf(tokens?.cache?.read),\n write: countOf(tokens?.cache?.write),\n }\n}\n\nexport function totalize(steps: readonly AssistantMessage[]): Totals {\n const totals: Totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length }\n for (const step of steps) {\n const counts = tokenCounts(step)\n totals.input += counts.input\n totals.cached += counts.read\n totals.output += counts.output\n totals.reasoning += counts.reasoning\n totals.cacheWrite += counts.write\n totals.cost += amountOf(step.cost)\n totals.listCost += amountOf(step.listCost)\n }\n return totals\n}\n\n/**\n * The identity of a model reference: the provider it runs through, the model\n * and its variant. Two steps with the same key ran the same thing the same way,\n * which is what `modelChanged` compares.\n */\nexport function identityKey(model: ModelRefLike | undefined): string | undefined {\n if (!model) return undefined\n return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : \"\"}`\n}\n\nexport function cacheRead(message: AssistantMessage | undefined): number {\n return countOf(message?.tokens?.cache?.read)\n}\n\nexport function stepCreated(message: AssistantMessage | undefined): number | undefined {\n return stampOf(message?.time?.created)\n}\n\nexport function stepEnd(message: AssistantMessage | undefined): number | undefined {\n const time = message?.time\n if (!time) return undefined\n return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created)\n}\n\n/**\n * Which identity the two steps must share for a reuse loss to be measurable.\n * `provider` is the strict one: two providers are two caches, so a switch\n * between them is not a loss but a different cache. `model` drops that test,\n * for the reports that measure what an identity change costs: forfeiting the\n * previous provider's cache is exactly the cost they report.\n */\nexport type CacheDropScope = \"provider\" | \"model\"\n\n/**\n * Cache reuse loss against a reference step, mirroring OpenCode's own\n * `turn-usage` heuristic: only comparable when the model is identical, and\n * OpenAI's API reports small reads that are not worth flagging.\n */\nexport function cacheDrop(reference: AssistantMessage | undefined, current: AssistantMessage, scope: CacheDropScope = \"provider\"): number | undefined {\n if (!reference) return undefined\n const before = reference.model\n const after = current.model\n if (!before || !after) return undefined\n if (scope === \"provider\" && before.providerID !== after.providerID) return undefined\n if (before.id !== after.id || (before.variant ?? \"\") !== (after.variant ?? \"\")) {\n return undefined\n }\n const drop = cacheRead(reference) - cacheRead(current)\n if (isNoiseDrop(after.providerID, drop)) return undefined\n return drop > 0 ? drop : undefined\n}\n\n/** Milliseconds between a reference step's completion and the next request. */\nexport function stepGap(reference: AssistantMessage | undefined, current: AssistantMessage): number | undefined {\n const ended = stepEnd(reference)\n const started = stepCreated(current)\n if (ended === undefined || started === undefined) return undefined\n return Math.max(0, started - ended)\n}\n\n/**\n * Streaming duration of a step: request start to the last streamed chunk. The\n * host's `streamed` stamp marks the end of streaming, so this is the window a\n * generation rate belongs to — not a time to first token, which the session\n * messages do not record.\n */\nexport function stepStreamMs(message: AssistantMessage): number | undefined {\n const created = stampOf(message.time?.created)\n const streamed = stampOf(message.time?.streamed)\n if (created === undefined || streamed === undefined || streamed <= created) return undefined\n return streamed - created\n}\n\n/**\n * Tokens produced per second over a window. For a step the window is the\n * streaming one: request start to the last streamed chunk (`created` →\n * `streamed`) — `completed` marks the end of the step, which for a tool-call\n * step happens after the tool calls were handled. Returns undefined when the\n * window or the produced tokens are unknown. Single definition, shared by the\n * recorder (which stores it per step) and the latency view.\n */\nexport function tokensPerSecond(produced: number, from: number | undefined, to: number | undefined): number | undefined {\n if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from) return undefined\n if (!Number.isFinite(produced) || produced <= 0) return undefined\n return (produced / (to - from)) * 1000\n}\n\n\n/**\n * Output-plus-reasoning tokens per second of a step over its decode window:\n * from the first streamed token to the end of the body. This is OpenCode's\n * definition, so the value matches the TUI and Desktop; a step recorded before\n * `firstToken` existed falls back to the request dispatch, as the host does.\n */\nexport function stepTps(message: AssistantMessage): number | undefined {\n const counts = tokenCounts(message)\n return tokensPerSecond(\n counts.output + counts.reasoning,\n message.time?.firstToken ?? message.time?.created,\n message.time?.streamed,\n )\n}\n\n/**\n * Output-plus-reasoning tokens per second over the whole request: from request\n * dispatch to the end of the body. It includes TTFT and is the conservative\n * rate, shown as `rtps` beside `tps`.\n */\nexport function stepRequestTps(message: AssistantMessage): number | undefined {\n const counts = tokenCounts(message)\n return tokensPerSecond(counts.output + counts.reasoning, message.time?.created, message.time?.streamed)\n}\n\n/** Milliseconds from request dispatch to the first streamed token. */\nexport function stepTtft(message: AssistantMessage): number | undefined {\n const created = message.time?.created\n const firstToken = message.time?.firstToken\n if (created === undefined || firstToken === undefined) return undefined\n if (!Number.isFinite(created) || !Number.isFinite(firstToken)) return undefined\n return Math.max(0, firstToken - created)\n}\n\nconst DROP_EXEMPT_PROVIDERS = new Set([\"openai\"])\n\n/**\n * True when a step has final numbers. A step that is still streaming reports\n * partial tokens (usually zero) and no cache read yet, so reading it would\n * render an empty line and invent a cache-expiry warning against it.\n */\nexport function isSettledStep(message: AssistantMessage): boolean {\n if (message.time?.completed !== undefined) return true\n return message.finish !== undefined && message.finish !== null\n}\n\n/**\n * Compute the stats of the most recent turn in a transcript, including the\n * comparison against the previous turn (a provider or model switch, and cache\n * reuse).\n *\n * Returns undefined while the newest turn is still being generated: the line\n * appears when a turn ends, never with the zeroes of an in-flight response.\n */\nexport function computeTurn(messages: readonly TranscriptMessage[], session?: Totals): TurnStats | undefined {\n const segments = transcriptTail(messages, 2)\n const last = segments[segments.length - 1]\n if (!last) return undefined\n const previous = segments[segments.length - 2]\n const lastStep = last.assistants[last.assistants.length - 1]\n if (!lastStep) return undefined\n if (!isSettledStep(lastStep)) return undefined\n const previousStep = previous?.assistants[previous.assistants.length - 1]\n // Defensive: a step that never settled mid-turn carries no usable numbers,\n // so it is neither a cache reference nor a reuse candidate.\n const settled = last.assistants.filter(isSettledStep)\n\n const drops: CacheDrop[] = []\n let reference: AssistantMessage | undefined = previousStep !== undefined && isSettledStep(previousStep) ? previousStep : undefined\n for (const step of settled) {\n const drop = cacheDrop(reference, step)\n if (drop !== undefined) {\n drops.push({\n messageID: step.id,\n tokens: drop,\n prevCached: cacheRead(reference),\n gapMs: stepGap(reference, step),\n })\n }\n reference = step\n }\n\n const provider = lastStep.model?.providerID\n const previousProvider = previousStep?.model?.providerID\n const key = identityKey(lastStep.model)\n const previousKey = identityKey(previousStep?.model)\n\n return {\n endAt: stepEnd(lastStep),\n startAt: stepCreated(settled[0] ?? lastStep),\n promptAt: stampOf(last.prompt?.time?.created),\n promptGapMs: promptGap(last.prompt, previous?.prompt),\n providerID: provider,\n modelID: lastStep.model?.id,\n variant: lastStep.model?.variant,\n providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,\n modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,\n totals: totalize(settled),\n latest: totalize([lastStep]),\n session,\n drops,\n cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),\n cacheExpired: drops.length > 0,\n steps: settled.length,\n }\n}\n\nfunction promptGap(current: TranscriptMessage | undefined, previous: TranscriptMessage | undefined): number | undefined {\n const now = stampOf(current?.time?.created)\n const before = stampOf(previous?.time?.created)\n if (now === undefined || before === undefined) return undefined\n return Math.max(0, now - before)\n}\n\n/** True when a cache drop is small enough to be provider noise. */\nexport function isNoiseDrop(providerID: string | undefined, drop: number): boolean {\n if (providerID === undefined) return false\n return DROP_EXEMPT_PROVIDERS.has(providerID) && drop >= 1024 && drop <= 2048\n}\n\n// ---------------------------------------------------------------------------\n// Formatting\n// ---------------------------------------------------------------------------\n\nexport type LineTone = \"base\" | \"muted\" | \"warning\"\n\nexport type LineSegment = { text: string; tone: LineTone }\n\nexport type LineLabels = {\n delta: string\n turn: string\n session: string\n step: string\n steps: string\n input: string\n cached: string\n output: string\n reasoning: string\n cost: string\n /** Prefix for a list-price estimate, e.g. `cost ≈ $0.03`. */\n estimate: string\n cacheExpired: string\n providerChanged: string\n modelChanged: string\n}\n\n/**\n * How the turn segment counts prompt usage. `latest` shows the prompt size the\n * turn ended with — the context view, and what OpenCode's own turn-token debug\n * line reports. `sum` adds every step of the turn: the billing view, where a\n * tool-call loop re-sends (and re-reads) the same context once per step.\n */\nexport type TurnTotalsView = \"latest\" | \"sum\"\n\nexport type LineFields = {\n clock: boolean\n delta: boolean\n model: boolean\n variant: boolean\n turn: boolean\n session: boolean\n reasoning: boolean\n cost: boolean\n cacheExpiry: boolean\n}\n\nexport const DEFAULT_LABELS: LineLabels = {\n delta: \"Δ\",\n // The turn segment is unlabelled by default to keep the line short; set it\n // back to \"turn\" (or anything else) through `labels.turn`.\n turn: \"\",\n session: \"sess\",\n step: \"step\",\n steps: \"steps\",\n input: \"in\",\n cached: \"cached\",\n output: \"out\",\n reasoning: \"reason\",\n cost: \"cost\",\n estimate: \"≈\",\n cacheExpired: \"cache expired\",\n providerChanged: \"changed\",\n modelChanged: \"model changed\",\n}\n\nexport const DEFAULT_FIELDS: LineFields = {\n clock: true,\n delta: true,\n model: true,\n variant: true,\n turn: true,\n session: true,\n reasoning: false,\n // The turn's and the session's cost are on by default: what a session costs\n // is the question the tokens only half answer. A zero is left out, so a free\n // model reads as free instead of repeating `$0` on every line.\n cost: true,\n cacheExpiry: true,\n}\n\nexport function formatClock(ms: number): string {\n if (!Number.isFinite(ms)) return \"--:--\"\n const date = new Date(ms)\n const pad = (value: number) => String(value).padStart(2, \"0\")\n return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`\n}\n\nexport function formatDuration(ms: number): string {\n if (!Number.isFinite(ms)) return \"–\"\n const totalSeconds = Math.max(0, Math.floor(ms / 1000))\n const seconds = totalSeconds % 60\n const minutes = Math.floor(totalSeconds / 60) % 60\n const hours = Math.floor(totalSeconds / 3600) % 24\n const days = Math.floor(totalSeconds / 86400)\n if (days > 0) return `${days}d${hours}h`\n if (hours > 0) return `${hours}h${String(minutes).padStart(2, \"0\")}m`\n if (minutes > 0) return `${minutes}m${String(seconds).padStart(2, \"0\")}s`\n return `${seconds}s`\n}\n\nexport function formatTokens(value: number): string {\n const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0\n if (n < 1_000) return String(n)\n if (n < 999_500) {\n const k = n / 1_000\n return `${trimZeros(k.toFixed(k < 10 ? 2 : 1))}k`\n }\n if (n < 999_500_000) {\n const m = n / 1_000_000\n return `${trimZeros(m.toFixed(m < 10 ? 2 : 1))}M`\n }\n return `${Math.round(n / 1_000_000)}M`\n}\n\nfunction trimZeros(value: string): string {\n return value.includes(\".\") ? value.replace(/0+$/, \"\").replace(/\\.$/, \"\") : value\n}\n\nexport function formatCost(value: number): string {\n if (!Number.isFinite(value) || value <= 0) return \"$0\"\n // Four decimals is the display precision below a dollar; a real, positive\n // amount that rounds to `$0.0000` would read as free, so it is shown as a\n // bound instead. This keeps a tiny list estimate distinguishable from zero.\n if (value < 0.00005) return \"<$0.0001\"\n if (value < 1) return `$${value.toFixed(4)}`\n return `$${value.toFixed(2)}`\n}\n\n/**\n * Charged and estimated money as one string. A mixed total keeps both parts\n * visible so list price is never mistaken for money that was charged:\n * `$0.12 + ≈ $3.40`. Returns undefined when there is no money to show.\n */\nexport function formatMoney(charged: number, estimated: number, marker = \"≈\"): string | undefined {\n const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined\n const estimate =\n Number.isFinite(estimated) && estimated > 0\n ? `${marker.trim() === \"\" ? \"\" : `${marker.trim()} `}${formatCost(estimated)}`\n : undefined\n if (paid !== undefined && estimate !== undefined) return `${paid} + ${estimate}`\n return paid ?? estimate\n}\n\n/**\n * The list-equivalent total for a compact table cell: charged money plus the\n * estimates, marked with `≈` when any part is estimated.\n */\nexport function formatSpend(charged: number, estimated: number, marker = \"≈\"): string {\n const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0\n const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0\n if (estimate > 0) return `${marker.trim()}${formatCost(paid + estimate)}`\n return formatCost(paid)\n}\n\n/**\n * The buckets the line displays, derived from a totals group. `input` is the\n * *uncached* part of the prompt (fresh input plus cache writes, i.e. what the\n * debug line's `new` counts on the prompt side), `prompt` is the whole prompt\n * of the request and `output` is everything the model generated (visible output\n * + reasoning). OpenCode's own debug line reconciles with these:\n * `new = in + out` and `total = prompt + out`, with `prompt = in + cached`.\n * The stored buckets stay raw; only the display folds.\n */\nexport type DisplayTotals = Totals & {\n /** Whole prompt of the request: fresh input + cached reads + cache writes. */\n prompt: number\n}\n\nexport function displayTotals(totals: Totals): DisplayTotals {\n const prompt = totals.input + totals.cached + totals.cacheWrite\n return {\n input: prompt - totals.cached,\n cached: totals.cached,\n cacheWrite: totals.cacheWrite,\n output: totals.output + totals.reasoning,\n reasoning: totals.reasoning,\n cost: totals.cost,\n listCost: totals.listCost,\n steps: totals.steps,\n prompt,\n }\n}\n\n/**\n * The numbers of one totals group. `cost` is passed explicitly because the two\n * callers mean different money: a turn's cost is the sum over its steps\n * whatever view its tokens follow, and money never comes from a \"latest\" step.\n * A charged cost of zero is left out; a list-price estimate is shown with `≈`.\n */\nfunction totalsText(\n prefix: string,\n totals: Totals,\n labels: LineLabels,\n fields: LineFields,\n stepCount = 0,\n cost = totals.cost,\n listCost = totals.listCost,\n estimates = true,\n): string {\n const display = displayTotals(totals)\n // The parenthesised value is the whole prompt, shown only when it differs\n // from the uncached part the label leads with.\n const input =\n display.prompt === display.input\n ? `${labels.input} ${formatTokens(display.input)}`\n : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`\n const parts = [\n input,\n `${labels.cached} ${formatTokens(display.cached)}`,\n `${labels.output} ${formatTokens(display.output)}`,\n ]\n if (fields.reasoning) parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`)\n const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined\n if (money !== undefined) parts.push(`${labels.cost} ${money}`)\n // An empty label (the default for the turn) leaves the numbers unlabelled; a\n // multi-step turn still says how many requests it took.\n const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : \"\"\n const head = [prefix, steps].filter((piece) => piece !== \"\").join(\" \")\n const numbers = parts.join(\", \")\n if (head === \"\") return numbers\n return stepCount > 1 ? `${head} · ${numbers}` : `${head} ${numbers}`\n}\n\n/**\n * The session totals as the line's `sess` segment alone. The Desktop badge\n * shows this while a turn is running: the turn has no final numbers yet, so\n * the badge reports the session's accumulated spend and this is its tooltip.\n */\nexport function formatSessionLine(\n totals: Totals,\n options?: { labels?: Partial<LineLabels>; fields?: Partial<LineFields>; estimates?: boolean },\n): string {\n const labels = { ...DEFAULT_LABELS, ...options?.labels }\n const fields = { ...DEFAULT_FIELDS, ...options?.fields }\n const estimates = options?.estimates !== false\n return totalsText(labels.session, totals, labels, fields, 0, totals.cost, totals.listCost, estimates)\n}\n\n/**\n * Render the telemetry line as toned segments. The caller maps tones onto\n * theme colors; `formatLine` joins the segments as plain text.\n */\nexport function formatLineSegments(\n stats: TurnStats,\n options?: { labels?: Partial<LineLabels>; fields?: Partial<LineFields>; turnTotals?: TurnTotalsView; estimates?: boolean },\n): LineSegment[] {\n const labels = { ...DEFAULT_LABELS, ...options?.labels }\n const fields = { ...DEFAULT_FIELDS, ...options?.fields }\n const turnTotals = options?.turnTotals ?? \"latest\"\n const estimates = options?.estimates !== false\n const segments: LineSegment[] = []\n\n if (fields.clock && stats.endAt !== undefined) {\n segments.push({ text: formatClock(stats.endAt), tone: \"muted\" })\n }\n if (fields.delta && stats.promptGapMs !== undefined) {\n segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: \"muted\" })\n }\n // The turn's identity is the provider the model ran through and the model\n // itself: the same model can come from different providers, so both are\n // shown, and a provider switch is the change the line warns about.\n if (stats.providerID !== undefined) {\n let text = stats.providerID\n if (fields.model && stats.modelID !== undefined) text += `/${stats.modelID}`\n if (fields.variant && stats.variant) text += ` ${stats.variant}`\n segments.push({ text, tone: stats.providerChanged ? \"warning\" : \"base\" })\n if (stats.providerChanged) segments.push({ text: labels.providerChanged, tone: \"warning\" })\n else if (stats.modelChanged) segments.push({ text: labels.modelChanged, tone: \"muted\" })\n }\n if (fields.turn && stats.totals.steps > 0) {\n const totals = turnTotals === \"sum\" ? stats.totals : stats.latest\n // The tokens follow the view — `latest` is the context the turn ended with\n // — but money is paid per step: the turn's cost is the sum over its steps,\n // never the last step's share of it.\n segments.push({\n text: totalsText(\n labels.turn,\n totals,\n labels,\n fields,\n turnTotals === \"sum\" ? stats.totals.steps : stats.steps,\n stats.totals.cost,\n stats.totals.listCost,\n estimates,\n ),\n tone: \"base\",\n })\n }\n if (fields.session && stats.session) {\n segments.push({\n text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),\n tone: \"muted\",\n })\n }\n if (fields.cacheExpiry && stats.cacheExpired) {\n const count = stats.drops.length > 1 ? `×${stats.drops.length}` : \"\"\n segments.push({ text: `⚠ ${labels.cacheExpired} (−${formatTokens(stats.cacheDropTokens)}${count})`, tone: \"warning\" })\n }\n return segments\n}\n\nexport function formatLine(\n stats: TurnStats,\n options?: { labels?: Partial<LineLabels>; fields?: Partial<LineFields>; turnTotals?: TurnTotalsView; estimates?: boolean },\n): string {\n return formatLineSegments(stats, options)\n .map((segment) => segment.text)\n .join(\" · \")\n}\n",
16
+ "import type { Database } from \"bun:sqlite\"\nimport { cacheDrop, stepGap, tokensPerSecond, type AssistantMessage } from \"../core\"\n\n/**\n * Read side of the stats engine: every function takes an open database and\n * returns plain rows for the TUI panel, the report script and the NDJSON\n * exports. Aggregations stay in SQL; comparisons and percentiles that would\n * need window functions or custom SQLite builds are computed in JS.\n */\n\n/**\n * Idle gap above which a cache reuse loss is attributed to provider-side\n * expiry rather than to a mid-session event. Heuristic: the empirical TTL\n * evidence view narrows this down with real observations.\n */\nexport const DEFAULT_TTL_HINT_MS = 10 * 60 * 1000\n\nexport type Range = {\n from?: number | undefined\n to?: number | undefined\n}\n\n/**\n * Panel filters. They narrow every aggregation to one model, one provider or\n * one session, and are applied with the same `WHERE` builder the range uses so\n * a filtered view and a drill-down agree.\n */\nexport type Filters = {\n /** Model id, variant excluded. */\n modelID?: string | undefined\n /**\n * One model *and* its variant, as `modelKey` builds it (`m1#max`). A variant\n * is a different model to the provider, so a drill-down into one variant must\n * not pick up its family.\n */\n modelKey?: string | undefined\n /**\n * The provider the model ran through, as OpenCode configured it\n * (`opencode-go`, `deepseek`, `deepinfra`). It is the identity every view\n * groups by: a gateway may re-route the request, but the upstream that\n * actually ran it is not observable.\n */\n provider?: string | undefined\n /**\n * One session, exactly. Used by the `session` range and by the overview's\n * \"this session\" block, which must not pick up the steps of every other\n * session that happened to run after it started.\n */\n sessionID?: string | undefined\n}\n\nexport type Usage = {\n steps: number\n input: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n /** List-price estimate for steps the host reported as costing nothing. */\n listCost: number\n}\n\n/**\n * What the selection costs: charged money plus the list-price estimate of the\n * steps the host reported as free. Display code marks the estimated part.\n */\nexport function spend(usage: Pick<Usage, \"cost\" | \"listCost\">): number {\n return usage.cost + usage.listCost\n}\n\n/** True when at least one step in the aggregate is an estimate. */\nexport function hasEstimate(usage: Pick<Usage, \"listCost\">): boolean {\n return usage.listCost > 0\n}\n\n/**\n * The list-price estimate of one session, from the steps the plugin recorded.\n * The live line uses it for the `sess` segment; a session with no recorded\n * estimate (or a database without the column) answers 0.\n */\nexport function sessionListCost(db: Database, sessionID: string): number {\n const row = db\n .query(\"SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?\")\n .get(sessionID) as { listCost: number | null } | null\n return row?.listCost ?? 0\n}\n\n/**\n * Money the host reported with no assistant step behind it: a compaction\n * summary or a generated title. It is part of the session's own cost, so the\n * totals that claim to describe a session include it.\n */\nexport type OtherUsage = {\n /** Host usage records behind the number. */\n entries: number\n cost: number\n}\n\nexport const EMPTY_OTHER: OtherUsage = { entries: 0, cost: 0 }\n\n/** True when the database has the table the non-step usage lives in. */\nfunction hasUsageTable(db: Database): boolean {\n try {\n return db.query(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'\").get() !== null\n } catch {\n return false\n }\n}\n\n/**\n * `WHERE` for non-step usage. A model or provider filter cannot be honored:\n * the host usage record carries neither, so including it under a filter would\n * attribute money to a model that did not earn it. A session filter can: the\n * row is the session's.\n */\nfunction otherWhere(\n range: Range | undefined,\n filters?: Filters | undefined,\n): { where: string; params: (string | number)[] } | undefined {\n if (filters?.modelID !== undefined && filters.modelID !== \"\") return undefined\n if (filters?.modelKey !== undefined && filters.modelKey !== \"\") return undefined\n if (filters?.provider !== undefined && filters.provider !== \"\") return undefined\n const span = rangeWhere(range, \"at\")\n const clauses = span.where === \"\" ? [] : [span.where.slice(\"WHERE \".length)]\n const params: (string | number)[] = [...span.params]\n if (filters?.sessionID !== undefined && filters.sessionID !== \"\") {\n clauses.push(\"session_id = ?\")\n params.push(filters.sessionID)\n }\n return { where: clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\", params }\n}\n\n/** Non-step usage in the selection. */\nexport function otherUsage(db: Database, range?: Range | undefined, filters?: Filters | undefined): OtherUsage {\n const filter = otherWhere(range, filters)\n if (filter === undefined || !hasUsageTable(db)) return { ...EMPTY_OTHER }\n try {\n const row = db\n .query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`)\n .get(...filter.params) as { entries: number | null; cost: number | null } | null\n return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 }\n } catch {\n return { ...EMPTY_OTHER }\n }\n}\n\n/** Non-step usage per session, for the session rows. */\nexport function otherUsageBySession(db: Database, range?: Range | undefined, filters?: Filters | undefined): Map<string, OtherUsage> {\n const out = new Map<string, OtherUsage>()\n const filter = otherWhere(range, filters)\n if (filter === undefined || !hasUsageTable(db)) return out\n try {\n const rows = db\n .query(\n `SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost\n FROM usage ${filter.where}\n GROUP BY session_id`,\n )\n .all(...filter.params) as Array<{ sessionID: string; entries: number | null; cost: number | null }>\n for (const row of rows) out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 })\n } catch {\n // An older database has no usage table: step totals alone are still valid.\n }\n return out\n}\n\nexport type OtherUsageRow = {\n sessionID: string\n at: number\n cost: number\n}\n\n/**\n * Non-step usage as one row per host record, so calendar buckets can fold it\n * into their periods with the same local-time rule the steps use.\n */\nexport function otherUsageRows(db: Database, range?: Range | undefined, filters?: Filters | undefined): OtherUsageRow[] {\n const filter = otherWhere(range, filters)\n if (filter === undefined || !hasUsageTable(db)) return []\n const where = filter.where === \"\" ? \"WHERE at IS NOT NULL\" : `${filter.where} AND at IS NOT NULL`\n try {\n return db\n .query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`)\n .all(...filter.params) as OtherUsageRow[]\n } catch {\n return []\n }\n}\n\ntype UsageRow = {\n steps: number | null\n input: number | null\n cached: number | null\n cacheWrite: number | null\n output: number | null\n reasoning: number | null\n cost: number | null\n listCost: number | null\n}\n\nexport const STEP_TIME = \"COALESCE(created_at, recorded_at)\"\n\n/**\n * The identity of a model *and* its variant, in SQL: `modelKey` says a variant\n * is a different model to the provider, so a variant never shares a row with\n * its family. The JS twin is `modelKey` below; both have to agree.\n */\nexport const MODEL_KEY_SEPARATOR = \"#\"\n/**\n * The identity of a model *and* its variant, in SQL: `modelKey` says a variant\n * is a different model to the provider, so a variant never shares a row with\n * its family. `prefix` qualifies the columns for a query that joins another\n * table. The JS twin is `modelKey` below; both have to agree.\n */\nfunction modelKeySQL(prefix = \"\"): string {\n return `COALESCE(${prefix}model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(${prefix}variant, '')`\n}\n\n/** `modelKey(modelID, variant)`: the family, with the variant as a suffix. */\nexport function modelKey(modelID: string, variant: string | undefined): string {\n return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? \"\"}`\n}\n\n/** Human label of a model key or a model id and variant. */\nexport function modelLabel(modelID: string, variant: string | undefined): string {\n return variant === undefined ? modelID : `${modelID} ${variant}`\n}\nconst USAGE_SELECT = `COUNT(*) AS steps,\n COALESCE(SUM(input_tokens), 0) AS input,\n COALESCE(SUM(cache_read), 0) AS cached,\n COALESCE(SUM(cache_write), 0) AS cacheWrite,\n COALESCE(SUM(output_tokens), 0) AS output,\n COALESCE(SUM(reasoning_tokens), 0) AS reasoning,\n COALESCE(SUM(cost), 0) AS cost,\n COALESCE(SUM(list_cost), 0) AS listCost`\n\nfunction usageFrom(row: UsageRow): Usage {\n return {\n steps: row.steps ?? 0,\n input: row.input ?? 0,\n cached: row.cached ?? 0,\n cacheWrite: row.cacheWrite ?? 0,\n output: row.output ?? 0,\n reasoning: row.reasoning ?? 0,\n cost: row.cost ?? 0,\n listCost: row.listCost ?? 0,\n }\n}\n\nfunction rangeWhere(range: Range | undefined, column = STEP_TIME): { where: string; params: number[] } {\n const clauses: string[] = []\n const params: number[] = []\n if (range?.from !== undefined) {\n clauses.push(`${column} >= ?`)\n params.push(range.from)\n }\n if (range?.to !== undefined) {\n clauses.push(`${column} < ?`)\n params.push(range.to)\n }\n return { where: clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\", params }\n}\n\n/**\n * `WHERE` for a range plus the panel filters. Shared with the analysis layer so\n * a filtered view and a drill-down agree on what is in scope. `prefix` qualifies\n * the filter columns; a query that joins another table must pass its `steps`\n * alias (`\"st.\"`), or a column the two tables share is ambiguous.\n */\nexport function buildWhere(\n range: Range | undefined,\n filters?: Filters | undefined,\n column = STEP_TIME,\n prefix = \"\",\n): { where: string; params: (string | number)[] } {\n const rangeClause = rangeWhere(range, column)\n const clauses = rangeClause.where === \"\" ? [] : [rangeClause.where.slice(\"WHERE \".length)]\n const params: (string | number)[] = [...rangeClause.params]\n if (filters?.modelID !== undefined && filters.modelID !== \"\") {\n clauses.push(`${prefix}model_id = ?`)\n params.push(filters.modelID)\n }\n if (filters?.modelKey !== undefined && filters.modelKey !== \"\") {\n clauses.push(`${modelKeySQL(prefix)} = ?`)\n params.push(filters.modelKey)\n }\n if (filters?.provider !== undefined && filters.provider !== \"\") {\n clauses.push(`${prefix}provider_id = ?`)\n params.push(filters.provider)\n }\n if (filters?.sessionID !== undefined && filters.sessionID !== \"\") {\n clauses.push(`${prefix}session_id = ?`)\n params.push(filters.sessionID)\n }\n return { where: clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\", params }\n}\n\n/**\n * Share of the whole prompt that came from the cache. The denominator is what\n * the provider saw: cache reads, fresh input and cache writes.\n */\nexport function cacheHitRatio(usage: Pick<Usage, \"input\" | \"cached\" | \"cacheWrite\">): number | undefined {\n const total = usage.cached + usage.input + usage.cacheWrite\n return total > 0 ? usage.cached / total : undefined\n}\n\nexport type Overview = Usage & {\n sessions: number\n prompts: number\n /** Compaction/title money included in `cost`, when the range has any. */\n otherCost?: number | undefined\n firstAt: number | undefined\n lastAt: number | undefined\n cacheHitRatio: number | undefined\n /**\n * Output-plus-reasoning tokens per second over the decode window, over the\n * whole selection: produced tokens divided by the summed `firstToken →\n * streamed` windows. This is OpenCode's definition; a step without a first\n * token falls back to its request dispatch. Weighted, not the mean of the\n * per-step rates the latency view reports as p50.\n */\n tps: number | undefined\n /**\n * The same tokens over the request window (`created → streamed`), including\n * TTFT and queueing. The conservative rate, shown as `rtps`.\n */\n requestTps: number | undefined\n /** Median milliseconds from request dispatch to the first streamed token. */\n ttft: number | undefined\n}\n\nexport function overview(db: Database, range?: Range, filters?: Filters): Overview {\n const steps = buildWhere(range, filters)\n const row = db\n .query(\n `SELECT ${USAGE_SELECT},\n COUNT(DISTINCT session_id) AS sessions,\n MIN(${STEP_TIME}) AS firstAt,\n MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,\n COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,\n COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,\n COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,\n COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)\n THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow\n FROM steps ${steps.where}`,\n )\n .get(...steps.params) as\n | (UsageRow & {\n sessions: number | null\n firstAt: number | null\n lastAt: number | null\n produced: number | null\n window: number | null\n decodeProduced: number | null\n decodeWindow: number | null\n })\n | null\n\n const prompts = rangeWhere(range, \"created_at\")\n const promptClauses = prompts.where === \"\" ? [] : [prompts.where.slice(\"WHERE \".length)]\n const promptParams: (string | number)[] = [...prompts.params]\n // The session block asks for one session: a prompt has no model, so the\n // session filter is the one that can be honored here. Ignoring it counted\n // every prompt in the range, including those of other sessions.\n if (filters?.sessionID !== undefined && filters.sessionID !== \"\") {\n promptClauses.push(\"session_id = ?\")\n promptParams.push(filters.sessionID)\n }\n const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(\" AND \")}` : \"\"\n const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams) as {\n prompts: number\n } | null\n\n // A median needs the values, not an aggregate; the narrow two-column read is\n // still bounded by the range's index. Steps without a first token are left\n // out: they have no TTFT to contribute.\n const ttftFilter = steps.where === \"\" ? \"WHERE\" : `${steps.where} AND`\n const ttftRows = db\n .query(\n `SELECT MAX(0, first_token_at - created_at) AS ttft\n FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`,\n )\n .all(...steps.params) as { ttft: number }[]\n const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50)\n\n const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 })\n const other = otherUsage(db, range, filters)\n return {\n ...usage,\n // The host's session cost includes compactions and titles; a total that\n // claims to describe the selection has to include them too. Tokens stay\n // step-based so the cache views keep comparing like with like.\n cost: usage.cost + other.cost,\n sessions: row?.sessions ?? 0,\n prompts: promptRow?.prompts ?? 0,\n otherCost: other.cost,\n firstAt: row?.firstAt ?? undefined,\n lastAt: row?.lastAt ?? undefined,\n cacheHitRatio: cacheHitRatio(usage),\n tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),\n requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),\n ttft,\n }\n}\n\nexport type ProviderUsage = Usage & {\n providerID: string\n firstAt: number | undefined\n lastAt: number | undefined\n}\n\nexport type ModelUsage = {\n modelID: string\n variant: string | undefined\n providers: ProviderUsage[]\n totals: Usage\n}\n\ntype ModelRow = UsageRow & {\n provider_id: string | null\n model_id: string | null\n variant: string | null\n first_at: number | null\n last_at: number | null\n}\n\n/**\n * Usage per model, each with the providers that served it. This is the view\n * that answers \"through which provider is this model actually coming, over the\n * selected period\".\n */\nexport function models(db: Database, range?: Range, filters?: Filters): ModelUsage[] {\n const filter = buildWhere(range, filters)\n const rows = db\n .query(\n `SELECT provider_id, model_id, variant,\n ${USAGE_SELECT},\n MIN(${STEP_TIME}) AS first_at,\n MAX(COALESCE(completed_at, recorded_at)) AS last_at\n FROM steps ${filter.where}\n GROUP BY provider_id, model_id, variant\n ORDER BY steps DESC, cached DESC`,\n )\n .all(...filter.params) as ModelRow[]\n\n const models = new Map<string, ModelUsage>()\n for (const row of rows) {\n const modelID = row.model_id ?? \"(unknown)\"\n const variant = row.variant ?? undefined\n const key = `${modelID}#${variant ?? \"\"}`\n let model = models.get(key)\n if (!model) {\n model = { modelID, variant, providers: [], totals: emptyUsage() }\n models.set(key, model)\n }\n const usage = usageFrom(row)\n model.providers.push({\n ...usage,\n providerID: row.provider_id ?? \"(unknown)\",\n firstAt: row.first_at ?? undefined,\n lastAt: row.last_at ?? undefined,\n })\n addUsage(model.totals, usage)\n }\n return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals))\n}\n\nfunction emptyUsage(): Usage {\n return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 }\n}\n\nfunction addUsage(target: Usage, source: Usage): void {\n target.steps += source.steps\n target.input += source.input\n target.cached += source.cached\n target.cacheWrite += source.cacheWrite\n target.output += source.output\n target.reasoning += source.reasoning\n target.cost += source.cost\n target.listCost += source.listCost\n}\n\n/**\n * Every bucket a provider bills for: the whole prompt (fresh input, cache\n * reads and writes) plus visible output and reasoning. Leaving `cacheWrite`\n * or `reasoning` out ranked a model with heavy cache writes or thinking below\n * one with more visible output, which is not what \"most tokens\" means.\n */\nfunction billedTokens(usage: Pick<Usage, \"input\" | \"cached\" | \"cacheWrite\" | \"output\" | \"reasoning\">): number {\n return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning\n}\n\nexport type TimelineBucket = { at: number } & Usage\n\n/** Usage aggregated into fixed time buckets (for example one hour or day). */\nexport function timeline(db: Database, range: Range | undefined, bucketMs: number): TimelineBucket[] {\n const filter = rangeWhere(range)\n const rows = db\n .query(\n `SELECT CAST(${STEP_TIME} / ? AS INTEGER) * ? AS bucket, ${USAGE_SELECT}\n FROM steps ${filter.where}\n GROUP BY bucket\n ORDER BY bucket`,\n )\n .all(bucketMs, bucketMs, ...filter.params) as (UsageRow & { bucket: number })[]\n return rows.map((row) => ({ at: row.bucket, ...usageFrom(row) }))\n}\n\nexport type LatencyStats = {\n count: number\n p50: number | undefined\n p90: number | undefined\n p99: number | undefined\n}\n\nexport type LatencyReport = {\n /** Milliseconds from request to completed response. */\n wall: LatencyStats\n /** Milliseconds from request to the last streamed chunk (the streaming window). */\n stream: LatencyStats\n /** Milliseconds from request dispatch to the first streamed token. */\n ttft: LatencyStats\n /** Output-plus-reasoning tokens per second over the decode window. */\n tps: LatencyStats\n /** Output-plus-reasoning tokens per second over the request window (includes TTFT). */\n requestTps: LatencyStats\n}\n\n/** Nearest-rank percentile over an unsorted sample. */\nexport function percentile(values: readonly number[], p: number): number | undefined {\n if (values.length === 0) return undefined\n const sorted = [...values].sort((a, b) => a - b)\n const rank = Math.ceil((p / 100) * sorted.length)\n const index = Math.min(sorted.length - 1, Math.max(0, rank - 1))\n return sorted[index]\n}\n\nexport function latencyStats(values: number[]): LatencyStats {\n return {\n count: values.length,\n p50: percentile(values, 50),\n p90: percentile(values, 90),\n p99: percentile(values, 99),\n }\n}\n\nconst statsFor = latencyStats\n\nexport type SessionUsage = Usage & {\n sessionID: string\n parentID: string | undefined\n title: string | undefined\n directory: string | undefined\n providers: string[]\n models: string[]\n prompts: number\n /** Compaction/title money included in `cost`, when the session has any. */\n otherCost?: number | undefined\n firstAt: number | undefined\n lastAt: number | undefined\n cacheHitRatio: number | undefined\n}\n\nexport function sessions(\n db: Database,\n options?: { range?: Range; filters?: Filters; limit?: number; sessionIDs?: readonly string[] },\n): SessionUsage[] {\n if (options?.sessionIDs !== undefined && options.sessionIDs.length === 0) return []\n const range = options?.range\n const filter = buildWhere(range, options?.filters, \"COALESCE(st.created_at, st.recorded_at)\", \"st.\")\n const limit = options?.limit ?? 20\n const clauses = filter.where === \"\" ? [] : [filter.where.slice(\"WHERE \".length)]\n const params: (number | string)[] = [...filter.params]\n // The session row is for a range, so its prompt count has to be for that\n // range too: a 7-day row must not show the prompts of the session's whole\n // history. The placeholders sit in the SELECT list, before the WHERE ones.\n const promptRange: string[] = []\n const promptParams: number[] = []\n if (range?.from !== undefined) {\n promptRange.push(\"p.created_at >= ?\")\n promptParams.push(range.from)\n }\n if (range?.to !== undefined) {\n promptRange.push(\"p.created_at < ?\")\n promptParams.push(range.to)\n }\n const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(\" AND \")}` : \"\"\n if (options?.sessionIDs !== undefined) {\n // A specific set of sessions (the subagents of one session): the group by\n // then reads one index range per session instead of every step recorded.\n const ids = options.sessionIDs.slice(0, 500)\n clauses.push(`st.session_id IN (${ids.map(() => \"?\").join(\", \")})`)\n params.push(...ids)\n }\n const rows = db\n .query(\n `SELECT st.session_id, s.title, s.directory, s.parent_id,\n GROUP_CONCAT(DISTINCT st.provider_id) AS providers,\n GROUP_CONCAT(DISTINCT st.model_id) AS models,\n (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,\n COUNT(*) AS steps,\n COALESCE(SUM(st.input_tokens), 0) AS input,\n COALESCE(SUM(st.cache_read), 0) AS cached,\n COALESCE(SUM(st.cache_write), 0) AS cacheWrite,\n COALESCE(SUM(st.output_tokens), 0) AS output,\n COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,\n COALESCE(SUM(st.cost), 0) AS cost,\n COALESCE(SUM(st.list_cost), 0) AS listCost,\n MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,\n MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at\n FROM steps st\n LEFT JOIN sessions s ON s.session_id = st.session_id\n ${clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\"}\n GROUP BY st.session_id\n ORDER BY last_at DESC\n LIMIT ?`,\n )\n .all(\n ...promptParams,\n ...params,\n limit,\n ) as (UsageRow & {\n session_id: string\n title: string | null\n directory: string | null\n parent_id: string | null\n providers: string | null\n models: string | null\n prompts: number | null\n first_at: number | null\n last_at: number | null\n })[]\n\n // The host's session cost includes compactions and titles; the session row\n // has to include them too, or it disagrees with the line's `sess` segment.\n const other = otherUsageBySession(db, range, options?.filters)\n return rows.map((row) => {\n const usage = usageFrom(row)\n const extra = other.get(row.session_id)?.cost ?? 0\n return {\n ...usage,\n cost: usage.cost + extra,\n sessionID: row.session_id,\n parentID: row.parent_id ?? undefined,\n title: row.title ?? undefined,\n directory: row.directory ?? undefined,\n providers: row.providers ? row.providers.split(\",\").filter(Boolean) : [],\n models: row.models ? row.models.split(\",\").filter(Boolean) : [],\n prompts: row.prompts ?? 0,\n otherCost: extra,\n firstAt: row.first_at ?? undefined,\n lastAt: row.last_at ?? undefined,\n cacheHitRatio: cacheHitRatio(usage),\n }\n })\n}\n\n/** Sessions whose parent is `parentID`: the subagents of one session. */\nexport function childSessionIDs(db: Database, parentID: string): string[] {\n return (db.query(\"SELECT session_id FROM sessions WHERE parent_id = ? ORDER BY session_id\").all(parentID) as { session_id: string }[]).map(\n (row) => row.session_id,\n )\n}\n\n/** Session usage rows for a specific set of sessions (subagent rollups). */\nexport function sessionUsageOf(db: Database, sessionIDs: readonly string[], filters?: Filters): SessionUsage[] {\n return sessions(db, { sessionIDs, limit: sessionIDs.length, filters })\n}\n\nexport type TurnDrop = {\n messageID: string\n tokens: number\n gapMs: number | undefined\n}\n\n/**\n * One finished turn of a session, built from the recorded steps and prompts. It\n * carries the same buckets the telemetry line uses, so the panel can render the\n * per-prompt history with the line's own formatter.\n */\nexport type TurnUsage = {\n sessionID: string\n /** Creation time of the prompt that opened the turn, when it was recorded. */\n promptAt: number | undefined\n endAt: number | undefined\n /**\n * Wall time of the turn's execution: the first step's request to the last\n * step's completion. Tool-call gaps inside the turn are included; time spent\n * queued before the first request is not.\n */\n durationMs: number | undefined\n /** Time between the previous finished turn's prompt and this turn's prompt. */\n promptGapMs: number | undefined\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n providerChanged: boolean\n modelChanged: boolean\n steps: number\n /** Raw buckets of the last step: the prompt the turn ended with. */\n latest: Usage\n /** Raw buckets summed over every step of the turn. */\n totals: Usage\n drops: TurnDrop[]\n /** Finish reason of the turn's last step. */\n finish: string | undefined\n /**\n * Output-plus-reasoning tokens per second over the turn's decode windows:\n * produced tokens divided by the summed `firstToken → streamed` windows. For\n * a one-step turn it is that step's rate, matching OpenCode.\n */\n tps: number | undefined\n /** The same tokens over the request windows, including TTFT; the conservative rate. */\n requestTps: number | undefined\n /** Milliseconds from the first step's dispatch to its first streamed token. */\n ttft: number | undefined\n}\n\ntype TurnStepRow = {\n message_id: string\n session_id: string\n provider_id: string | null\n model_id: string | null\n variant: string | null\n input_tokens: number | null\n cache_read: number | null\n cache_write: number | null\n output_tokens: number | null\n reasoning_tokens: number | null\n cost: number | null\n list_cost: number | null\n created_at: number | null\n first_token_at: number | null\n streamed_at: number | null\n recorded_at: number\n completed_at: number | null\n finish: string | null\n}\n\n/** A turn is finished when its last step ended without asking for more tools. */\nfunction turnFinished(finish: string | null): boolean {\n return finish !== null && finish !== \"\" && finish !== \"tool-calls\"\n}\n\nfunction stepUsage(row: TurnStepRow): Usage {\n return {\n steps: 1,\n input: row.input_tokens ?? 0,\n cached: row.cache_read ?? 0,\n cacheWrite: row.cache_write ?? 0,\n output: row.output_tokens ?? 0,\n reasoning: row.reasoning_tokens ?? 0,\n cost: row.cost ?? 0,\n listCost: row.list_cost ?? 0,\n }\n}\n\n/** Structural view of a recorded step, so the shared cache-drop rule applies. */\nfunction stepMessage(row: TurnStepRow): AssistantMessage {\n return {\n type: \"assistant\",\n id: row.message_id,\n time: {\n created: row.created_at ?? row.recorded_at,\n firstToken: row.first_token_at ?? undefined,\n completed: row.completed_at ?? undefined,\n },\n model:\n row.provider_id !== null && row.model_id !== null\n ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined }\n : undefined,\n tokens: {\n input: row.input_tokens ?? 0,\n output: row.output_tokens ?? 0,\n reasoning: row.reasoning_tokens ?? 0,\n cache: { read: row.cache_read ?? 0, write: row.cache_write ?? 0 },\n },\n finish: row.finish ?? undefined,\n }\n}\n\n/**\n * Finished turns, newest first. Steps belong to the newest prompt recorded at or\n * before them; a turn whose last step asked for tools is dropped, because it is\n * still running — the same rule the telemetry line follows.\n *\n * For one session the read is bounded by a window of the newest prompts. The\n * window grows until it holds `limit` finished turns: a prompt can be empty\n * (the host records a synthetic system-reminder next to the user prompt) and\n * the newest turn can still be running, so a fixed one-prompt margin is not\n * enough. `complete` means the window covers every prompt of the session.\n */\nexport function turns(\n db: Database,\n options?: { sessionID?: string | undefined; range?: Range | undefined; filters?: Filters | undefined; limit?: number | undefined },\n): TurnUsage[] {\n const requested = options?.limit ?? 50\n const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50\n const filter = buildWhere(options?.range, options?.filters)\n const baseClauses = filter.where === \"\" ? [] : [filter.where.slice(\"WHERE \".length)]\n const baseParams: (number | string)[] = [...filter.params]\n if (options?.sessionID !== undefined) {\n baseClauses.push(\"session_id = ?\")\n baseParams.push(options.sessionID)\n }\n\n /** Read the turns inside the given prompt window, newest first. */\n function read(promptCount: number): { rows: TurnUsage[]; complete: boolean } {\n const clauses = [...baseClauses]\n const params = [...baseParams]\n const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount)\n if (floor !== undefined) {\n clauses.push(`${STEP_TIME} >= ?`)\n params.push(floor)\n }\n const steps = db\n .query(\n `SELECT message_id, session_id, provider_id, model_id, variant,\n input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,\n created_at, first_token_at, streamed_at, recorded_at, completed_at, finish\n FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(\" AND \")}` : \"\"}\n ORDER BY session_id, ${STEP_TIME}, message_id`,\n )\n .all(...params) as TurnStepRow[]\n\n const promptClause = options?.sessionID === undefined ? \"\" : `WHERE session_id = ?${floor === undefined ? \"\" : \" AND created_at >= ?\"}`\n const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor]\n const promptRows = db\n .query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`)\n .all(...promptParams) as { session_id: string; created_at: number | null }[]\n\n const promptsBySession = new Map<string, number[]>()\n for (const row of promptRows) {\n if (row.created_at === null) continue\n const list = promptsBySession.get(row.session_id) ?? []\n list.push(row.created_at)\n promptsBySession.set(row.session_id, list)\n }\n\n const result: TurnUsage[] = []\n let sessionID: string | undefined\n let bucket: TurnStepRow[] = []\n let promptIndex = -2\n let promptAt: number | undefined\n\n function close(): void {\n const last = bucket[bucket.length - 1]\n if (last === undefined || !turnFinished(last.finish)) {\n bucket = []\n return\n }\n const totals = emptyUsage()\n for (const row of bucket) addUsage(totals, stepUsage(row))\n const drops: TurnDrop[] = []\n let reference: AssistantMessage | undefined\n for (const row of bucket) {\n const message = stepMessage(row)\n const drop = cacheDrop(reference, message)\n if (drop !== undefined) {\n drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) })\n }\n reference = message\n }\n const providerID = last.provider_id ?? undefined\n const modelID = last.model_id ?? undefined\n const variant = last.variant ?? undefined\n let produced = 0\n let window = 0\n let decodeProduced = 0\n let decodeWindow = 0\n for (const row of bucket) {\n const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0)\n if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {\n produced += tokens\n window += row.streamed_at - row.created_at\n }\n const start = row.first_token_at ?? row.created_at\n if (start !== null && row.streamed_at !== null && row.streamed_at > start) {\n decodeProduced += tokens\n decodeWindow += row.streamed_at - start\n }\n }\n const first = bucket[0]\n const ttft =\n first !== undefined && first.created_at !== null && first.first_token_at !== null\n ? Math.max(0, first.first_token_at - first.created_at)\n : undefined\n const previous = result.length > 0 && result[result.length - 1]!.sessionID === last.session_id ? result[result.length - 1] : undefined\n const endAt = last.completed_at ?? last.created_at ?? last.recorded_at\n // A turn starts when the first request goes out; a step recorded without\n // its own start stamp falls back to the prompt that opened the turn.\n const firstAt = bucket[0]?.created_at ?? promptAt\n result.push({\n sessionID: last.session_id,\n promptAt,\n endAt,\n durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,\n // The gap is against the previous *turn*, not the previous prompt row:\n // a synthetic system-reminder prompt can sit between two user turns.\n promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,\n providerID,\n modelID,\n variant,\n providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,\n modelChanged:\n previous !== undefined &&\n previous.providerID === providerID &&\n `${previous.modelID ?? \"\"}#${previous.variant ?? \"\"}` !== `${modelID ?? \"\"}#${variant ?? \"\"}`,\n steps: bucket.length,\n latest: stepUsage(last),\n totals,\n drops,\n finish: last.finish ?? undefined,\n tps: tokensPerSecond(decodeProduced, 0, decodeWindow),\n requestTps: tokensPerSecond(produced, 0, window),\n ttft,\n })\n bucket = []\n }\n\n for (const row of steps) {\n if (row.session_id !== sessionID) {\n close()\n sessionID = row.session_id\n promptIndex = -2\n promptAt = undefined\n }\n const time = row.created_at ?? row.recorded_at\n const prompts = promptsBySession.get(row.session_id) ?? []\n let index = -1\n for (let candidate = prompts.length - 1; candidate >= 0; candidate -= 1) {\n if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {\n index = candidate\n break\n }\n }\n if (index !== promptIndex) {\n close()\n promptIndex = index\n promptAt = index >= 0 ? prompts[index] : undefined\n }\n bucket.push(row)\n }\n close()\n\n // Once the window reaches a prompt at or before the range's start, no older\n // prompt can be the newest one before a step inside the range: the window\n // already covers every turn the range can contain.\n const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from\n return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart }\n }\n\n let promptCount = Math.max(1, limit + 1)\n for (;;) {\n const { rows, complete } = read(promptCount)\n if (rows.length >= limit || complete) return rows.slice(0, limit)\n const next = promptCount * 2 + 1\n if (!Number.isFinite(next) || next <= promptCount) return rows.slice(0, limit)\n promptCount = next\n }\n}\n\n/**\n * Creation time of the `count`-th newest prompt of a session, or undefined\n * when it has fewer. Used to bound the steps a `turns` read has to load.\n */\nfunction promptFloor(db: Database, sessionID: string, count: number): number | undefined {\n const rows = db\n .query(\"SELECT created_at FROM prompts WHERE session_id = ? AND created_at IS NOT NULL ORDER BY created_at DESC LIMIT ?\")\n .all(sessionID, count) as { created_at: number }[]\n return rows.length === count ? rows[count - 1]!.created_at : undefined\n}\n\n// ---------------------------------------------------------------------------\n// Filter pickers\n// ---------------------------------------------------------------------------\n\nexport type FilterOption = { value: string; steps: number }\n\n/** Distinct models and providers, most used first. */\nexport function filterOptions(db: Database): { models: FilterOption[]; providers: FilterOption[] } {\n const pick = (column: string): FilterOption[] =>\n (\n db\n .query(`SELECT ${column} AS value, COUNT(*) AS steps FROM steps WHERE ${column} IS NOT NULL GROUP BY ${column} ORDER BY steps DESC`)\n .all() as { value: string; steps: number }[]\n ).map((row) => ({ value: row.value, steps: row.steps }))\n return { models: pick(\"model_id\"), providers: pick(\"provider_id\") }\n}\n",
17
+ "/**\n * The analysis layer: the reports the panel and the CLI show.\n *\n * Two shapes, chosen by measurement rather than taste:\n *\n * 1. **Aggregates in SQLite** — totals, counts, distinct values. `coverageOf`\n * and the filter pickers never move a row into JavaScript.\n * 2. **Narrow rows plus arithmetic in JS** — percentiles, pair rules, calendar\n * buckets. SQLite's window functions cost about 17 µs per row per report\n * here (a sort plus a materialisation), while reading the four to twelve\n * columns a report actually needs costs 1–4 µs per row. The percentiles and\n * the pair comparisons are therefore computed over lean projections: on the\n * audit's 120k-step database a whole view costs a few hundred milliseconds,\n * and on a normal one it is instant.\n *\n * The rules are not restated here. Cache reuse, idle gaps and the noise\n * threshold come from `core.ts` — the same functions the live line uses — so\n * the panel and the line can never disagree about what a cache loss is.\n * `test/reports.test.ts` holds every report to those rules.\n */\n\nimport type { Database } from \"bun:sqlite\"\nimport { cacheDrop, stepGap, tokensPerSecond, type AssistantMessage } from \"../core\"\nimport {\n buildWhere,\n DEFAULT_TTL_HINT_MS,\n latencyStats,\n MODEL_KEY_SEPARATOR,\n modelKey,\n modelLabel,\n percentile,\n type Filters,\n type LatencyStats,\n type OtherUsageRow,\n type Range,\n type Usage,\n} from \"./queries\"\n\n/** The step's own clock, the expression the `steps_at` index covers. */\nexport const STEP_AT = \"COALESCE(created_at, recorded_at)\"\n\ntype Options = { range?: Range | undefined; filters?: Filters | undefined }\n\n// ---------------------------------------------------------------------------\n// Lean projections\n// ---------------------------------------------------------------------------\n\n/**\n * Turn `null` into `undefined` in place, so a row costs one object and not two.\n * Every query aliases its columns to the field names they are read through;\n * only the optional ones have to be normalized.\n */\nfunction normalize<Row>(rows: Row[], optional: readonly string[]): Row[] {\n for (const row of rows as unknown as Array<Record<string, unknown>>) {\n for (const key of optional) if (row[key] === null) row[key] = undefined\n }\n return rows\n}\n\nfunction groupBy<Value, Key>(items: readonly Value[], key: (item: Value) => Key): Map<Key, Value[]> {\n const groups = new Map<Key, Value[]>()\n for (const item of items) {\n const group = key(item)\n const list = groups.get(group)\n if (list !== undefined) list.push(item)\n else groups.set(group, [item])\n }\n return groups\n}\n\n/** One recorded step, as the reports read it. */\nexport type StepRow = {\n messageID: string\n sessionID: string\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n input: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n listCost: number\n createdAt: number | undefined\n firstTokenAt: number | undefined\n streamedAt: number | undefined\n completedAt: number | undefined\n /** `COALESCE(created_at, recorded_at)`: the ordering time of the step. */\n at: number\n /** Set on the single step loaded before the range, as a reference. */\n boundary?: boolean | undefined\n}\n\nconst STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,\n model_id AS modelID, variant,\n COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,\n COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,\n COALESCE(list_cost, 0) AS listCost,\n created_at AS createdAt, first_token_at AS firstTokenAt, streamed_at AS streamedAt,\n completed_at AS completedAt, ${STEP_AT} AS at`\n\nconst STEP_OPTIONAL = [\"providerID\", \"modelID\", \"variant\", \"createdAt\", \"firstTokenAt\", \"streamedAt\", \"completedAt\"] as const\n\n/**\n * A step as the pair reports read it. Their projection leaves the generated\n * tokens out (nothing they compute sums them), and the type says so: an\n * aggregate that reads `output` cannot be handed a pair row by mistake.\n */\nexport type PairRow = Omit<StepRow, \"output\" | \"reasoning\">\n\n/** The pair reports read no generated tokens: `output` and `reasoning` stay out. */\nconst PAIR_COLUMNS = STEP_COLUMNS.replace(\"COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, \", \"\")\n\n/** The steps of the range, narrow. Ordering is only paid for where it is read. */\nexport function stepRows(db: Database, options?: Options): StepRow[] {\n const filter = buildWhere(options?.range, options?.filters)\n const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params) as Array<Record<string, unknown>>\n return normalize(rows, STEP_OPTIONAL) as StepRow[]\n}\n\n/**\n * The steps of the range plus, for every session with a step inside it, the one\n * step before the range: the pair reports compare a step with the one that\n * preceded it, so the first step of a range has to see it.\n *\n * The boundary is one seek per session on the `(session_id, time)` index — a\n * few milliseconds for a far wider history — never the whole history of the\n * sessions in range.\n */\nexport function cachePairs(db: Database, options?: Options): PairRow[] {\n const filter = buildWhere(options?.range, options?.filters)\n const rows = normalize(\n db\n .query(`SELECT ${PAIR_COLUMNS} FROM steps ${filter.where} ORDER BY session_id, ${STEP_AT}, message_id`)\n .all(...filter.params) as Array<Record<string, unknown>>,\n STEP_OPTIONAL,\n ) as PairRow[]\n const from = options?.range?.from\n if (from === undefined || rows.length === 0) return rows\n const seek = db.query(\n `SELECT ${PAIR_COLUMNS} FROM steps\n WHERE session_id = ? AND COALESCE(created_at, recorded_at) < ?\n ORDER BY COALESCE(created_at, recorded_at) DESC, message_id DESC LIMIT 1`,\n )\n for (const sessionID of new Set(rows.map((row) => row.sessionID))) {\n const boundary = seek.get(sessionID, from) as Record<string, unknown> | null\n if (boundary === null) continue\n const step = normalize([boundary], STEP_OPTIONAL)[0] as PairRow\n step.boundary = true\n rows.push(step)\n }\n rows.sort((left, right) => {\n if (left.sessionID !== right.sessionID) return left.sessionID < right.sessionID ? -1 : 1\n if (left.at !== right.at) return left.at - right.at\n return left.messageID < right.messageID ? -1 : left.messageID > right.messageID ? 1 : 0\n })\n return rows\n}\n\n/** The same step in the message shape the shared pair rules are written for. */\nfunction message(step: PairRow): AssistantMessage {\n return {\n type: \"assistant\",\n id: step.messageID,\n ...(step.modelID === undefined\n ? {}\n : { model: { providerID: step.providerID ?? \"\", id: step.modelID, ...(step.variant === undefined ? {} : { variant: step.variant }) } }),\n tokens: { cache: { read: step.cached } },\n time: {\n ...(step.createdAt === undefined ? {} : { created: step.createdAt }),\n ...(step.streamedAt === undefined ? {} : { streamed: step.streamedAt }),\n ...(step.completedAt === undefined ? {} : { completed: step.completedAt }),\n },\n }\n}\n\n/** Consecutive steps of the same session, in order. */\nfunction pairsOf(rows: readonly PairRow[]): Array<{ previous: PairRow; current: PairRow }> {\n const pairs: Array<{ previous: PairRow; current: PairRow }> = []\n for (let index = 1; index < rows.length; index += 1) {\n const previous = rows[index - 1]!\n const current = rows[index]!\n if (previous.sessionID !== current.sessionID) continue\n pairs.push({ previous, current })\n }\n return pairs\n}\n\ntype Counted = { input: number; cached: number; cacheWrite: number; output: number; reasoning: number; cost: number; listCost: number }\n\n/** The buckets the panel and the line agree on. */\nfunction usageOf(steps: readonly Counted[]): Usage {\n const usage: Usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 }\n for (const step of steps) {\n usage.steps += 1\n usage.input += step.input\n usage.cached += step.cached\n usage.cacheWrite += step.cacheWrite\n usage.output += step.output\n usage.reasoning += step.reasoning\n usage.cost += step.cost\n usage.listCost += step.listCost\n }\n return usage\n}\n\n// ---------------------------------------------------------------------------\n// Coverage\n// ---------------------------------------------------------------------------\n\nexport type CoverageReport = {\n steps: number\n models: number\n /** Providers the steps ran through. A step whose provider is unknown is counted nowhere. */\n providers: number\n missingModel: number\n unsettled: number\n missingTps: number\n /**\n * Steps with a rate but no `firstToken`: their `tps` falls back to the\n * request window, and the share shows how much of `tps` is not true decode.\n */\n missingFirstToken: number\n firstAt: number | undefined\n lastAt: number | undefined\n}\n\n/**\n * What the panel cannot answer honestly: how many steps lack a model, and how\n * many never settled. A zero in the switch counts means \"never switched\" only\n * when this coverage is complete.\n */\nexport function coverageOf(db: Database, options?: Options): CoverageReport {\n const filter = buildWhere(options?.range, options?.filters)\n const row = db\n .query(\n `SELECT COUNT(*) AS steps,\n COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,\n COUNT(DISTINCT provider_id) AS providers,\n COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,\n COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,\n COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at THEN 0 ELSE 1 END), 0) AS missingTps,\n COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at AND first_token_at IS NULL THEN 1 ELSE 0 END), 0) AS missingFirstToken,\n MIN(${STEP_AT}) AS firstAt,\n MAX(${STEP_AT}) AS lastAt\n FROM steps ${filter.where}`,\n )\n .get(...filter.params) as {\n steps: number\n models: number\n providers: number\n missingModel: number\n unsettled: number\n missingTps: number\n missingFirstToken: number\n firstAt: number | null\n lastAt: number | null\n }\n return {\n steps: row.steps,\n models: row.models,\n providers: row.providers,\n missingModel: row.missingModel,\n unsettled: row.unsettled,\n missingTps: row.missingTps,\n missingFirstToken: row.missingFirstToken,\n firstAt: row.firstAt ?? undefined,\n lastAt: row.lastAt ?? undefined,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Latency\n// ---------------------------------------------------------------------------\n\n/** The steps a latency report is built from. It reads no generated tokens. */\ntype GroupedRow = StepRow\n\nfunction groupedRows(db: Database, options?: Options): GroupedRow[] {\n const filter = buildWhere(options?.range, options?.filters)\n const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params) as Array<Record<string, unknown>>\n return normalize(rows, STEP_OPTIONAL) as StepRow[]\n}\n\n/** The measures a latency report is made of. */\nfunction timingOf(step: StepRow): {\n wall: number | undefined\n stream: number | undefined\n ttft: number | undefined\n tps: number | undefined\n requestTps: number | undefined\n} {\n // A clock adjustment can stamp a step as completed before it was created.\n // A negative wall time is not a latency; it would also drag the percentiles\n // down, so the window is clamped at zero.\n const wall =\n step.createdAt !== undefined && step.completedAt !== undefined\n ? Math.max(0, step.completedAt - step.createdAt)\n : undefined\n const stream =\n step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined\n // The first token is the start of the decode window. A step recorded before\n // the host emitted it has no TTFT, and its rate falls back to the request\n // window exactly as OpenCode does.\n const ttft =\n step.createdAt !== undefined && step.firstTokenAt !== undefined ? Math.max(0, step.firstTokenAt - step.createdAt) : undefined\n return {\n wall,\n stream,\n ttft,\n tps: tokensPerSecond(step.output + step.reasoning, step.firstTokenAt ?? step.createdAt, step.streamedAt),\n requestTps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt),\n }\n}\n\nexport type LatencyReport = {\n wall: LatencyStats\n stream: LatencyStats\n ttft: LatencyStats\n tps: LatencyStats\n requestTps: LatencyStats\n}\n\n/** The timings of the range: one read, shared by the overall report and the groups. */\nexport function timingRows(db: Database, options?: Options): GroupedRow[] {\n return groupedRows(db, options)\n}\n\n/** Overall wall, streaming, TTFT and throughput percentiles. */\nexport function latencyOf(rows: readonly StepRow[]): LatencyReport {\n const wall: number[] = []\n const stream: number[] = []\n const ttft: number[] = []\n const tps: number[] = []\n const requestTps: number[] = []\n for (const step of rows) {\n const timing = timingOf(step)\n if (timing.wall !== undefined) wall.push(timing.wall)\n if (timing.stream !== undefined) stream.push(timing.stream)\n if (timing.ttft !== undefined) ttft.push(timing.ttft)\n if (timing.tps !== undefined) tps.push(timing.tps)\n if (timing.requestTps !== undefined) requestTps.push(timing.requestTps)\n }\n return {\n wall: latencyStats(wall),\n stream: latencyStats(stream),\n ttft: latencyStats(ttft),\n tps: latencyStats(tps),\n requestTps: latencyStats(requestTps),\n }\n}\n\nexport type LatencyGroupRow = {\n key: string\n label: string\n count: number\n usage: Usage\n wall: LatencyStats\n stream: LatencyStats\n ttft: LatencyStats\n tps: LatencyStats\n requestTps: LatencyStats\n}\n\nexport type Dimension = \"model\" | \"provider\"\n\n/** Wall, streaming, TTFT and throughput percentiles per group. */\nexport function latencyGroupsOf(rows: readonly StepRow[], by: Dimension): LatencyGroupRow[] {\n const key = (step: StepRow) => (by === \"model\" ? modelKey(step.modelID ?? \"(unknown)\", step.variant) : step.providerID ?? \"(unknown)\")\n const groups: LatencyGroupRow[] = []\n for (const [group, steps] of groupBy(rows, key)) {\n const wall: number[] = []\n const stream: number[] = []\n const ttft: number[] = []\n const tps: number[] = []\n const requestTps: number[] = []\n for (const step of steps) {\n const timing = timingOf(step)\n if (timing.wall !== undefined) wall.push(timing.wall)\n if (timing.stream !== undefined) stream.push(timing.stream)\n if (timing.ttft !== undefined) ttft.push(timing.ttft)\n if (timing.tps !== undefined) tps.push(timing.tps)\n if (timing.requestTps !== undefined) requestTps.push(timing.requestTps)\n }\n const { modelID, variant } = splitModelKey(group)\n groups.push({\n key: group,\n label: by === \"model\" ? (variant === undefined ? modelID : `${modelID} ${variant}`) : group,\n count: steps.length,\n usage: usageOf(steps),\n wall: latencyStats(wall),\n stream: latencyStats(stream),\n ttft: latencyStats(ttft),\n tps: latencyStats(tps),\n requestTps: latencyStats(requestTps),\n })\n }\n return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key))\n}\n\n// ---------------------------------------------------------------------------\n// Cache reuse\n// ---------------------------------------------------------------------------\n\nexport type CacheStats = {\n steps: number\n input: number\n cached: number\n cacheWrite: number\n /** The whole prompt the provider saw: `cached + input + cache_write`. */\n prompt: number\n /** Token-weighted reuse over the whole selection. */\n hit: number | undefined\n /** Median of the per-step reuse ratios: a few huge steps cannot hide a split pattern. */\n hitP50: number | undefined\n}\n\nconst EMPTY_CACHE: CacheStats = { steps: 0, input: 0, cached: 0, cacheWrite: 0, prompt: 0, hit: undefined, hitP50: undefined }\n\n/** Reuse of the prompt cache over a set of steps. */\nfunction cacheStatsOfSteps(steps: readonly { input: number; cached: number; cacheWrite: number }[]): CacheStats {\n let input = 0\n let cached = 0\n let cacheWrite = 0\n const ratios: number[] = []\n for (const step of steps) {\n input += step.input\n cached += step.cached\n cacheWrite += step.cacheWrite\n const prompt = step.input + step.cached + step.cacheWrite\n if (prompt > 0) ratios.push(step.cached / prompt)\n }\n const prompt = input + cached + cacheWrite\n return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) }\n}\n\n/** Reuse of the prompt cache over the range, as one row. */\nexport function cacheStatsOf(db: Database, options?: Options): CacheStats {\n const rows = stepRows(db, options)\n return rows.length === 0 ? EMPTY_CACHE : cacheStatsOfSteps(rows)\n}\n\nexport type CacheModelRow = {\n modelID: string\n variant: string | undefined\n cache: CacheStats\n}\n\n/**\n * Reuse of the prompt cache per model, most cached first, over the steps of the\n * range. A boundary step is not part of the range, so it is left out.\n */\nexport function cacheStatsByModel(rows: readonly PairRow[]): CacheModelRow[] {\n const out: CacheModelRow[] = []\n const inRange = rows.filter((row) => row.boundary !== true)\n for (const [, group] of groupBy(inRange, (row) => modelKey(row.modelID ?? \"(unknown)\", row.variant))) {\n out.push({ modelID: group[0]!.modelID ?? \"(unknown)\", variant: group[0]!.variant, cache: cacheStatsOfSteps(group) })\n }\n return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID))\n}\n\n// ---------------------------------------------------------------------------\n// Pairs: switches, cache survival, TTL, losses\n// ---------------------------------------------------------------------------\n\nexport type SwitchRow = {\n modelID: string\n variant: string | undefined\n steps: number\n pairs: number\n /** Steps whose model, variant or provider differed from the step before. */\n changes: number\n /** Of those, the ones whose model (or variant) differed. */\n modelChanges: number\n /** Of those, the ones whose provider differed. */\n providerChanges: number\n /** Cache the changes cost: only a provider switch can forfeit a reusable cache. */\n cacheLost: number\n cacheLostEvents: number\n}\n\nexport type SwitchReport = {\n rows: SwitchRow[]\n totals: { pairs: number; changes: number; cacheLost: number; cacheLostEvents: number }\n}\n\n/**\n * Switches between consecutive steps of a session, by the two dimensions that\n * decide which cache holds the work: the model (with its variant) and the\n * provider.\n *\n * A switch is not by itself a fault — it is usually the user choosing another\n * model — so the report only names a cost where one is measurable: a provider\n * switch that leaves the model intact forfeits the cache the previous provider\n * held. A model switch has no measurable cost by definition, because two models\n * never share a cache to lose.\n */\nexport function switchesOf(rows: readonly PairRow[]): SwitchReport {\n const perModel = new Map<string, SwitchRow>()\n const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 }\n\n for (const { previous, current } of pairsOf(rows)) {\n if (previous.modelID === undefined || current.modelID === undefined) continue\n const key = modelKey(current.modelID, current.variant)\n const row = perModel.get(key) ?? {\n modelID: current.modelID,\n variant: current.variant,\n steps: 0,\n pairs: 0,\n changes: 0,\n modelChanges: 0,\n providerChanges: 0,\n cacheLost: 0,\n cacheLostEvents: 0,\n }\n row.steps += 1\n row.pairs += 1\n totals.pairs += 1\n\n const modelChanged = key !== modelKey(previous.modelID, previous.variant)\n const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID\n if (modelChanged) row.modelChanges += 1\n if (providerChanged) row.providerChanges += 1\n if (modelChanged || providerChanged) {\n row.changes += 1\n totals.changes += 1\n // The scope is the model alone: a provider switch forfeits the cache the\n // previous provider held, and that is the cost this report names.\n const lost = cacheDrop(message(previous), message(current), \"model\")\n if (lost !== undefined) {\n row.cacheLost += lost\n row.cacheLostEvents += 1\n totals.cacheLost += lost\n totals.cacheLostEvents += 1\n }\n }\n perModel.set(key, row)\n }\n\n return {\n rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),\n totals,\n }\n}\n\nexport type GapBucket = {\n label: string\n samples: number\n /** Pairs that still reused the prompt cache. */\n retained: number\n drops: number\n lostTokens: number\n retainedRatio: number | undefined\n}\n\nexport type ProviderReuseRow = {\n /** The provider, or `(unknown)` when a step ran without one. */\n provider: string\n samples: number\n retained: number\n drops: number\n lostTokens: number\n retainedRatio: number | undefined\n}\n\nexport type GapReport = {\n buckets: GapBucket[]\n providers: ProviderReuseRow[]\n samples: number\n}\n\n/**\n * Idle-gap buckets. The cache cliff sits in the 15–60m window, so that hour is\n * split in four: the coarse buckets would fold a TTL boundary into one row.\n */\nexport const GAP_BUCKETS: ReadonlyArray<readonly [string, number, number | undefined]> = [\n [\"<1m\", 0, 60_000],\n [\"1–5m\", 60_000, 5 * 60_000],\n [\"5–15m\", 5 * 60_000, 15 * 60_000],\n [\"15–20m\", 15 * 60_000, 20 * 60_000],\n [\"20–30m\", 20 * 60_000, 30 * 60_000],\n [\"30–45m\", 30 * 60_000, 45 * 60_000],\n [\"45–60m\", 45 * 60_000, 60 * 60_000],\n [\"1–6h\", 60 * 60_000, 6 * 60 * 60_000],\n [\">6h\", 6 * 60 * 60_000, undefined],\n]\n\nfunction bucketFor(gapMs: number): number {\n const index = GAP_BUCKETS.findIndex(([, from, to]) => gapMs >= from && (to === undefined || gapMs < to))\n return index === -1 ? GAP_BUCKETS.length - 1 : index\n}\n\n/**\n * How long an idle gap the prompt cache survives, per gap bucket and per\n * provider. Only pairs of the same model are comparable, which is exactly the\n * set the cache rule already uses.\n */\nexport function gapReportOf(rows: readonly PairRow[]): GapReport {\n const buckets: GapBucket[] = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }))\n const providers = new Map<string, ProviderReuseRow>()\n let samples = 0\n\n for (const { previous, current } of pairsOf(rows)) {\n if (previous.modelID === undefined || current.modelID === undefined) continue\n if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant)) continue\n // A pair that switched provider is not a survival sample: the switch\n // tally owns that case, and a switch is not an idle gap.\n if ((previous.providerID ?? \"\") !== (current.providerID ?? \"\")) continue\n const gap = stepGap(message(previous), message(current))\n if (gap === undefined) continue\n const lost = cacheDrop(message(previous), message(current))\n const bucket = buckets[bucketFor(gap)]!\n bucket.samples += 1\n samples += 1\n if (lost === undefined) bucket.retained += 1\n else {\n bucket.drops += 1\n bucket.lostTokens += lost\n }\n\n const provider = current.providerID ?? previous.providerID ?? \"(unknown)\"\n const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }\n row.samples += 1\n if (lost === undefined) row.retained += 1\n else {\n row.drops += 1\n row.lostTokens += lost\n }\n providers.set(provider, row)\n }\n\n for (const bucket of buckets) bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined\n for (const row of providers.values()) row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined\n return {\n buckets,\n providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),\n samples,\n }\n}\n\nexport type TtlEvidenceRow = {\n providerID: string\n modelID: string\n samples: number\n /** Largest idle gap that still hit the cache. */\n maxHitGapMs: number | undefined\n /** Smallest idle gap after which reuse was lost. */\n minDropGapMs: number | undefined\n}\n\n/**\n * Empirical bounds on the provider cache TTL: the longest idle gap that still\n * reused the cache, and the shortest gap that lost it. Comparing the two per\n * provider turns TTL guesses into observations.\n */\nexport function ttlEvidenceOf(rows: readonly PairRow[]): TtlEvidenceRow[] {\n const evidence = new Map<string, TtlEvidenceRow>()\n\n for (const { previous, current } of pairsOf(rows)) {\n if (previous.modelID === undefined || current.modelID === undefined) continue\n const key = `${current.providerID ?? \"\"}/${current.modelID}`\n const before = `${previous.providerID ?? \"\"}/${previous.modelID}#${previous.variant ?? \"\"}`\n const after = `${current.providerID ?? \"\"}/${current.modelID}#${current.variant ?? \"\"}`\n if (before !== after) continue\n\n const row = evidence.get(key) ?? {\n providerID: current.providerID ?? \"(unknown)\",\n modelID: current.modelID,\n samples: 0,\n maxHitGapMs: undefined,\n minDropGapMs: undefined,\n }\n row.samples += 1\n const gapMs = stepGap(message(previous), message(current))\n if (gapMs !== undefined) {\n const lost = cacheDrop(message(previous), message(current))\n if (lost === undefined) row.maxHitGapMs = row.maxHitGapMs === undefined ? gapMs : Math.max(row.maxHitGapMs, gapMs)\n else row.minDropGapMs = row.minDropGapMs === undefined ? gapMs : Math.min(row.minDropGapMs, gapMs)\n }\n evidence.set(key, row)\n }\n return [...evidence.values()].sort(\n (left, right) => right.samples - left.samples || `${left.providerID}/${left.modelID}`.localeCompare(`${right.providerID}/${right.modelID}`),\n )\n}\n\nexport type DropReason = \"compaction\" | \"expired\" | \"unknown\"\n\nexport type CacheDropRow = {\n sessionID: string\n messageID: string\n providerID: string | undefined\n modelID: string | undefined\n variant: string | undefined\n at: number\n tokens: number\n gapMs: number | undefined\n prevCached: number\n reason: DropReason\n}\n\n/**\n * Cache reuse losses with a best-effort reason: a compaction in between, an\n * idle gap long enough to be provider-side expiry, or unknown.\n *\n * Compactions come from the `compactions` table: one query for the sessions in\n * play, never one per loss.\n */\nexport function cacheDropsOf(db: Database, rows: readonly PairRow[], options?: { ttlHintMs?: number }): CacheDropRow[] {\n const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS\n const losses: Array<{ previous: PairRow; current: PairRow; tokens: number; gapMs: number | undefined }> = []\n for (const { previous, current } of pairsOf(rows)) {\n // The model scope: a provider switch forfeits the cache the previous\n // provider held, which is a loss like any other.\n const tokens = cacheDrop(message(previous), message(current), \"model\")\n if (tokens === undefined) continue\n losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) })\n }\n if (losses.length === 0) return []\n\n const times = new Map<string, number[]>()\n const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))]\n const timeline = db\n .query(\n `SELECT session_id, at FROM compactions\n WHERE at IS NOT NULL AND session_id IN (${sessionIDs.map(() => \"?\").join(\", \")})\n ORDER BY at`,\n )\n .all(...sessionIDs) as { session_id: string; at: number }[]\n for (const row of timeline) {\n const list = times.get(row.session_id)\n if (list !== undefined) list.push(row.at)\n else times.set(row.session_id, [row.at])\n }\n\n return losses\n .map((loss) => {\n const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt\n const compacted = (times.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at)\n const reason: DropReason = compacted ? \"compaction\" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? \"expired\" : \"unknown\"\n return {\n sessionID: loss.current.sessionID,\n messageID: loss.current.messageID,\n providerID: loss.current.providerID,\n modelID: loss.current.modelID,\n variant: loss.current.variant,\n at: loss.current.at,\n tokens: loss.tokens,\n gapMs: loss.gapMs,\n prevCached: loss.previous.cached,\n reason,\n }\n })\n .sort((left, right) => left.at - right.at)\n}\n\n// ---------------------------------------------------------------------------\n// Providers\n// ---------------------------------------------------------------------------\n\nexport type ProviderSummary = {\n /** The provider, or undefined for steps recorded without one. */\n provider: string | undefined\n /** Models this provider served. */\n models: string[]\n share: number\n usage: Usage\n cache: CacheStats\n tps: number | undefined\n requestTps: number | undefined\n ttft: number | undefined\n wall: number | undefined\n firstAt: number | undefined\n lastAt: number | undefined\n}\n\nexport type ProviderRow = ProviderSummary & {\n modelID: string\n variant: string | undefined\n}\n\n/** The numbers of one group of steps. */\nfunction groupValues(steps: readonly StepRow[]): {\n cache: CacheStats\n tps: number | undefined\n requestTps: number | undefined\n ttft: number | undefined\n wall: number | undefined\n} {\n const wall: number[] = []\n const tps: number[] = []\n const requestTps: number[] = []\n const ttft: number[] = []\n for (const step of steps) {\n const timing = timingOf(step)\n if (timing.wall !== undefined) wall.push(timing.wall)\n if (timing.tps !== undefined) tps.push(timing.tps)\n if (timing.requestTps !== undefined) requestTps.push(timing.requestTps)\n if (timing.ttft !== undefined) ttft.push(timing.ttft)\n }\n return {\n cache: cacheStatsOfSteps(steps),\n tps: latencyStats(tps).p50,\n requestTps: latencyStats(requestTps).p50,\n ttft: latencyStats(ttft).p50,\n wall: latencyStats(wall).p50,\n }\n}\n\nconst MODEL_LIST_SEPARATOR = \"\\u0000\"\n\n/** Split `modelKey` back into its model and optional variant. */\nfunction splitModelKey(key: string): { modelID: string; variant: string | undefined } {\n const separator = key.indexOf(MODEL_KEY_SEPARATOR)\n if (separator === -1) return { modelID: key, variant: undefined }\n const variant = key.slice(separator + 1)\n return { modelID: key.slice(0, separator), variant: variant === \"\" ? undefined : variant }\n}\n\nfunction providerOf(steps: readonly StepRow[], models: string): Omit<ProviderSummary, \"provider\"> & { provider: string | undefined } {\n const values = groupValues(steps)\n // A long-lived provider can hold a million steps. Spreading that into\n // `Math.min`/`Math.max` exceeds the call-stack argument limit, so the bounds\n // are folded instead.\n let firstAt: number | undefined\n let lastAt: number | undefined\n for (const step of steps) {\n if (firstAt === undefined || step.at < firstAt) firstAt = step.at\n if (lastAt === undefined || step.at > lastAt) lastAt = step.at\n }\n return {\n provider: steps[0]!.providerID,\n models: models.split(MODEL_LIST_SEPARATOR),\n share: 0,\n usage: usageOf(steps),\n cache: values.cache,\n tps: values.tps,\n requestTps: values.requestTps,\n ttft: values.ttft,\n wall: values.wall,\n firstAt,\n lastAt,\n }\n}\n\nconst modelNames = (steps: readonly StepRow[]): string =>\n [...new Set(steps.map((step) => modelKey(step.modelID ?? \"(unknown)\", step.variant)))]\n .map((key) => {\n const { modelID, variant } = splitModelKey(key)\n return modelLabel(modelID, variant)\n })\n .join(MODEL_LIST_SEPARATOR)\n\n/** One row per provider, over every model it served. */\nexport function providerSummaryOf(rows: readonly StepRow[]): ProviderSummary[] {\n const out: ProviderSummary[] = []\n for (const steps of groupBy(rows, (step) => step.providerID ?? \"\").values()) {\n const summary = providerOf(steps, modelNames(steps))\n out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length })\n }\n return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? \"\").localeCompare(right.provider ?? \"\"))\n}\n\n/** One row per model × provider: through which provider each model ran, and how much. */\nexport function providerBreakdownOf(rows: readonly StepRow[]): ProviderRow[] {\n const out: ProviderRow[] = []\n for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? \"(unknown)\", step.variant))) {\n for (const steps of groupBy(modelRows, (step) => step.providerID ?? \"\").values()) {\n const { modelID, variant } = splitModelKey(model)\n out.push({\n // One row per model, so its `models` field names that one model — in the\n // same label form the provider summary uses.\n ...providerOf(steps, modelNames(steps)),\n modelID,\n variant: variant === \"\" ? undefined : variant,\n share: steps.length / modelRows.length,\n })\n }\n }\n return out.sort((left, right) => right.usage.steps - left.usage.steps || right.cache.cached - left.cache.cached)\n}\n\n// ---------------------------------------------------------------------------\n// Calendar periods\n// ---------------------------------------------------------------------------\n\nexport type PeriodGranularity = \"day\" | \"week\" | \"month\"\n\nexport type PeriodRow = {\n key: string\n label: string\n /** Start of the bucket, local time. */\n at: number\n steps: number\n sessions: number\n usage: Usage\n cache: CacheStats\n /** Compaction/title money included in `usage.cost`, when the period has any. */\n otherCost?: number | undefined\n}\n\n/** ISO-8601 week number and its Monday, in local time. */\nexport function isoWeek(date: Date): { year: number; week: number; monday: Date } {\n const monday = new Date(date.getFullYear(), date.getMonth(), date.getDate())\n monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7))\n const thursday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 3)\n const firstThursday = new Date(thursday.getFullYear(), 0, 4)\n firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3)\n const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000))\n return { year: thursday.getFullYear(), week, monday }\n}\n\n/** Local end (exclusive) of the period that starts at `at`. */\nexport function periodEnd(at: number, granularity: PeriodGranularity): number {\n const date = new Date(at)\n if (granularity === \"month\") return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime()\n if (granularity === \"week\") return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime()\n return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime()\n}\n\n/** Key, label and local start of the period `at` falls in. */\nexport function periodStart(at: number, granularity: PeriodGranularity): { key: string; label: string; start: number } {\n const date = new Date(at)\n const pad = (value: number) => String(value).padStart(2, \"0\")\n if (granularity === \"month\") {\n const start = new Date(date.getFullYear(), date.getMonth(), 1)\n return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() }\n }\n if (granularity === \"week\") {\n const { year, week, monday } = isoWeek(date)\n return { key: `${year}-W${pad(week)}`, label: `${year}-W${pad(week)}`, start: monday.getTime() }\n }\n const start = new Date(date.getFullYear(), date.getMonth(), date.getDate())\n const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`\n return { key, label: key, start: start.getTime() }\n}\n\n/**\n * Totals per local calendar day, week or month, oldest first.\n *\n * `otherRows` are the host's non-step usage records (compaction and title\n * generations). Their cost is added to the bucket they fall in, because the\n * session's own total includes it; the token buckets stay step-based.\n */\nexport function periodsOf(\n rows: readonly StepRow[],\n granularity: PeriodGranularity,\n otherRows: readonly OtherUsageRow[] = [],\n): PeriodRow[] {\n const byKey = new Map<string, PeriodRow>()\n for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {\n const period = periodStart(steps[0]!.at, granularity)\n byKey.set(key, {\n key,\n label: period.label,\n at: period.start,\n steps: steps.length,\n sessions: new Set(steps.map((step) => step.sessionID)).size,\n usage: usageOf(steps),\n cache: cacheStatsOfSteps(steps),\n })\n }\n for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {\n const cost = group.reduce((sum, row) => sum + row.cost, 0)\n const existing = byKey.get(key)\n if (existing !== undefined) {\n existing.usage.cost += cost\n existing.otherCost = (existing.otherCost ?? 0) + cost\n continue\n }\n // A period with a compaction or title but no assistant step still has a\n // cost and a session: it must not disappear from the calendar.\n const period = periodStart(group[0]!.at, granularity)\n byKey.set(key, {\n key,\n label: period.label,\n at: period.start,\n steps: 0,\n sessions: new Set(group.map((row) => row.sessionID)).size,\n usage: { ...usageOf([]), cost },\n cache: cacheStatsOfSteps([]),\n otherCost: cost,\n })\n }\n return [...byKey.values()].sort((left, right) => left.at - right.at)\n}\n",
13
18
  "import { formatDuration } from \"./core\"\n\n/**\n * OpenCode Go allowance math and formatting.\n *\n * The host publishes one meter per window: `rolling` (5 hours), `weekly` and\n * `monthly`. Each meter carries the percentage used, whether Go refuses\n * requests until it resets, and the reset instant. The host does not publish\n * when the monthly cycle started, so the forecast infers it as one calendar\n * month before the reset. That assumption is shown in the UI instead of being\n * hidden in the number.\n */\n\nexport const QUOTA_VIEW = \"go\" as const\nexport const QUOTA_POLL_MS = 60_000\n/** The host does not expose the paid plan; this is the conservative default. */\nexport const DEFAULT_QUOTA_NAME = \"OpenCode Go\"\nconst DAY_MS = 24 * 60 * 60 * 1000\n/** Below this much of a cycle the integer percentage is too coarse to project. */\nconst MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000\n\n/**\n * The subscription label shown in the UI. The host's usage payload has no\n * `planType` (Go and Go Plus share the same meters), so an explicit\n * `quotaName` wins; otherwise use the provider's display name if the host\n * provides one, and finally the full default name.\n */\nexport function quotaNameOf(explicit?: string | undefined, providerName?: string | undefined): string {\n const custom = explicit?.trim()\n if (custom !== undefined && custom !== \"\") return custom\n const provider = providerName?.trim()\n if (provider !== undefined && provider !== \"\") return provider\n return DEFAULT_QUOTA_NAME\n}\n\nexport type GoMeter = {\n percent: number\n limited: boolean\n resetsAt: number\n}\n\nexport type GoWorkspace = {\n id: string\n name?: string | undefined\n usageURL?: string | undefined\n}\n\nexport type GoQuota = {\n workspace?: GoWorkspace | undefined\n rolling: GoMeter\n weekly: GoMeter\n monthly: GoMeter\n observedAt: number\n}\n\n/** What a successful or explanatory quota read means for the UI. */\nexport type QuotaFetch =\n | { kind: \"ok\"; quota: GoQuota }\n | { kind: \"none\"; reason: \"console\" | \"subscription\" }\n\n/** Reactive quota state shared by the TUI panel and sidebar. */\nexport type QuotaResource = {\n readonly state: () => QuotaFetch | undefined\n readonly loading: () => boolean\n readonly error: () => string | undefined\n readonly refresh: () => void\n}\n\nexport type MonthlyForecast = {\n /** Inferred start of the monthly cycle. */\n startAt: number\n /** Monthly reset reported by the host. */\n endAt: number\n elapsedMs: number\n remainingMs: number\n /** Percentage points used per day over the cycle so far. */\n ratePerDay: number\n /** Percentage at the reset if the current pace continues. */\n projectedPercent: number\n /** When the monthly allowance reaches 100% before the reset. */\n exhaustAt?: number | undefined\n /** The meter is already limited or at 100%. */\n reached: boolean\n /** The cycle has run long enough for the projection to mean something. */\n available: boolean\n /** The limit is expected before the reset. */\n willExhaust: boolean\n}\n\nexport type QuotaChart = {\n /** Whole percentage used now, clamped to 0-100. */\n current: number\n /** Whole percentage at the reset, clamped to 0-100. */\n forecast: number\n /** Percentage points left at the reset. */\n headroom: number\n /** The projection goes past 100%. */\n over: boolean\n /** The meter is already at 100%; the projection is not useful. */\n reached: boolean\n available: boolean\n /** Monthly reset reported by the host. */\n resetsAt: number\n exhaustAt?: number | undefined\n}\n\nfunction finite(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value)\n}\n\nfunction clamp(value: number, minimum: number, maximum: number): number {\n return Math.min(maximum, Math.max(minimum, value))\n}\n\n/**\n * The start of the cycle that ends at `endAt`, assuming the paid period has\n * the same day in the previous month. A shorter previous month uses its last\n * day, so 31 March maps to 28/29 February instead of overflowing into March.\n */\nexport function previousCycleStart(endAt: number): number {\n if (!finite(endAt)) return endAt\n const end = new Date(endAt)\n const year = end.getUTCFullYear()\n const month = end.getUTCMonth()\n const day = end.getUTCDate()\n const start = new Date(\n Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()),\n )\n const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate()\n start.setUTCDate(Math.min(day, lastDay))\n return start.getTime()\n}\n\n/**\n * Project the month's percentage to its reset from the cycle's average pace.\n * The projection is intentionally simple: with one observation per window it\n * is the only honest forecast the host data supports. It never invents a\n * sample history.\n */\nexport function forecastMonthly(meter: GoMeter, now: number): MonthlyForecast {\n const endAt = finite(meter.resetsAt) ? meter.resetsAt : now\n const startAt = previousCycleStart(endAt)\n const total = Math.max(1, endAt - startAt)\n const elapsedMs = clamp(now - startAt, 0, total)\n const remainingMs = Math.max(0, endAt - now)\n const percent = clamp(finite(meter.percent) ? meter.percent : 0, 0, 100)\n const reached = meter.limited === true || percent >= 100\n const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0\n ? percent / (elapsedMs / DAY_MS)\n : 0\n const projectedPercent = reached\n ? 100\n : ratePerDay > 0\n ? percent + ratePerDay * (remainingMs / DAY_MS)\n : percent\n const rawExhaustAt =\n !reached && ratePerDay > 0 && percent < 100\n ? now + ((100 - percent) / ratePerDay) * DAY_MS\n : undefined\n const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined\n const willExhaust = exhaustAt !== undefined\n const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0)\n\n return {\n startAt,\n endAt,\n elapsedMs,\n remainingMs,\n ratePerDay,\n projectedPercent,\n ...(exhaustAt !== undefined ? { exhaustAt } : {}),\n reached,\n available,\n willExhaust,\n }\n}\n\n/** The values a bar chart needs, with the projection clamped to the track. */\nexport function quotaChart(meter: GoMeter, now: number): QuotaChart {\n const forecast = forecastMonthly(meter, now)\n const current = clamp(Math.round(finite(meter.percent) ? meter.percent : 0), 0, 100)\n const projected = forecast.reached ? 100 : Math.round(forecast.projectedPercent)\n return {\n current,\n forecast: clamp(projected, 0, 100),\n headroom: Math.max(0, 100 - clamp(projected, 0, 100)),\n over: !forecast.reached && forecast.projectedPercent > 100,\n reached: forecast.reached,\n available: forecast.available,\n resetsAt: forecast.endAt,\n ...(forecast.exhaustAt !== undefined ? { exhaustAt: forecast.exhaustAt } : {}),\n }\n}\n\n/** A ten-cell ASCII bar that fits the TUI panel and the sidebar. */\nexport function quotaBar(percent: number, width = 10): string {\n const value = clamp(finite(percent) ? percent : 0, 0, 100)\n const cells = Math.max(1, Math.round(width))\n const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round((value / 100) * cells)))\n return `[${\"#\".repeat(filled)}${\"-\".repeat(cells - filled)}]`\n}\n\n/** `15 Dec 2026 22:06` in the user's local time, or a fixed zone in tests. */\nexport function formatRenewal(at: number, timeZone?: string | undefined): string {\n if (!finite(at)) return \"–\"\n try {\n return new Intl.DateTimeFormat(\"en-GB\", {\n day: \"2-digit\",\n month: \"short\",\n year: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n ...(timeZone !== undefined ? { timeZone } : {}),\n })\n .format(new Date(at))\n .replace(/,/g, \"\")\n } catch {\n return \"–\"\n }\n}\n\n/** `15 Dec 22:06` for the narrow sidebar. */\nexport function formatRenewalCompact(at: number, timeZone?: string | undefined): string {\n if (!finite(at)) return \"–\"\n try {\n return new Intl.DateTimeFormat(\"en-GB\", {\n day: \"2-digit\",\n month: \"short\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n ...(timeZone !== undefined ? { timeZone } : {}),\n })\n .format(new Date(at))\n .replace(/,/g, \"\")\n } catch {\n return \"–\"\n }\n}\n\n/** `in 2d 4h`; a reset in the past reads `due`. */\nexport function formatCountdown(at: number, now: number): string {\n const remaining = at - now\n if (!finite(remaining)) return \"–\"\n if (remaining <= 0) return \"due\"\n return formatDuration(remaining)\n}\n\n/** The status line shared by the TUI and the chart. */\nexport function quotaStatus(quota: GoQuota): string {\n const limited: string[] = []\n if (quota.rolling.limited || quota.rolling.percent >= 100) limited.push(\"5-hour\")\n if (quota.weekly.limited || quota.weekly.percent >= 100) limited.push(\"weekly\")\n if (quota.monthly.limited || quota.monthly.percent >= 100) limited.push(\"monthly\")\n return limited.length === 0 ? \"active\" : `${limited.join(\" / \")} limit reached`\n}\n",
14
- "import {\n DEFAULT_FIELDS,\n DEFAULT_LABELS,\n displayTotals,\n formatClock,\n formatCost,\n formatDuration,\n formatLine,\n formatMoney,\n formatSpend,\n formatTokens,\n type LineFields,\n type LineLabels,\n type TurnStats,\n type TurnTotalsView,\n} from \"./core\"\nimport type {\n CacheDropRow,\n LatencyReport,\n ModelUsage,\n Overview,\n Range,\n SessionUsage,\n TurnUsage,\n TtlEvidenceRow,\n} from \"./stats/queries\"\nimport type { DbInfo } from \"./stats/maintenance\"\nimport type {\n CacheStats,\n CoverageReport,\n ProviderRow,\n ProviderSummary,\n GapReport,\n LatencyGroupRow,\n PeriodGranularity,\n PeriodRow,\n SwitchRow,\n} from \"./stats/aggregates\"\nimport { modelKey } from \"./stats/queries\"\nimport { sanitizeText } from \"./text\"\nimport {\n DEFAULT_QUOTA_NAME,\n QUOTA_VIEW,\n formatCountdown,\n formatRenewal,\n formatRenewalCompact,\n forecastMonthly,\n quotaBar,\n quotaStatus,\n type GoMeter,\n type QuotaFetch,\n} from \"./quota\"\n\n/**\n * View models and formatting for the stats panel. Everything here is pure:\n * the panel component feeds query results in and renders the lines out, which\n * keeps the layout testable without a terminal. Lines may carry a `row`, the\n * identity the cursor selects and Enter drills into.\n */\n\nexport const PANEL_NAME = \"usage-insights\"\n\nexport const PANEL_VIEWS = [\"overview\", \"models\", \"providers\", \"cache\", \"periods\", \"latency\", \"sessions\", \"turns\", \"db\"] as const\n/**\n * The panel catalogue seen by the TUI and the Desktop. `go` is client-side\n * because the server part cannot reach the host's usage-limits endpoint; the\n * database-backed views stay in `PANEL_VIEWS`.\n */\nexport const CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW] as const\nexport type PanelView = (typeof PANEL_VIEWS)[number] | typeof QUOTA_VIEW\n\nexport const RANGE_KEYS = [\"session\", \"today\", \"7d\", \"30d\", \"all\"] as const\nexport type RangeKey = (typeof RANGE_KEYS)[number]\n\nexport const GRANULARITIES = [\"day\", \"week\", \"month\"] as const\nexport type Granularity = (typeof GRANULARITIES)[number]\n\nexport type PanelTone = \"base\" | \"muted\" | \"warning\" | \"accent\"\n\n/** What a selectable line stands for; Enter drills into it. */\nexport type PanelRow = {\n kind: \"model\" | \"session\" | \"period\" | \"provider\" | \"turn\" | \"prune\" | \"wipe\"\n value: string\n variant?: string | undefined\n}\n\nexport type PanelLine = {\n text: string\n tone?: PanelTone\n row?: PanelRow | undefined\n /** TUI-only key hint; the desktop GUI filters these lines out. */\n hint?: boolean | undefined\n}\n\n/** Sorting options per view; the first is the default. */\nexport const SORT_KEYS: Partial<Record<PanelView, readonly string[]>> = {\n models: [\"steps\", \"cached\", \"hit\", \"out\", \"cost\"],\n providers: [\"steps\", \"cached\", \"hit\", \"cost\", \"share\", \"tps\"],\n latency: [\"n\", \"tps\", \"wall\"],\n sessions: [\"last\", \"steps\", \"cached\", \"cost\"],\n turns: [\"time\", \"cost\", \"tokens\"],\n}\n\nexport function sortKeys(view: PanelView): readonly string[] {\n return SORT_KEYS[view] ?? []\n}\n\nexport function defaultSort(view: PanelView): string {\n return sortKeys(view)[0] ?? \"\"\n}\n\n/**\n * The Desktop view menu places Go immediately after Overview, because it is\n * live host state rather than a database report. The TUI keeps its numeric\n * key order (9 is db, 0 is go); only the Desktop dropdown uses this order.\n */\nexport function desktopViewOrder(views: readonly PanelView[]): readonly PanelView[] {\n const go = views.indexOf(QUOTA_VIEW)\n if (go === -1) return views\n const withoutGo = views.filter((view) => view !== QUOTA_VIEW)\n const overview = withoutGo.indexOf(\"overview\")\n const at = overview === -1 ? 0 : overview + 1\n return [...withoutGo.slice(0, at), QUOTA_VIEW, ...withoutGo.slice(at)]\n}\n\nexport function nextSort(view: PanelView, current: string, step: number): string {\n const keys = sortKeys(view)\n if (keys.length === 0) return current\n const index = keys.indexOf(current)\n if (index === -1) return keys[0]!\n return keys[(index + step + keys.length) % keys.length]!\n}\n\n/** The views and ranges, as the command and the panel header understand them. */\nexport function parseArgs(input: string | undefined, views: readonly PanelView[] = CLIENT_VIEWS): { view?: PanelView; range?: RangeKey } {\n const parsed: { view?: PanelView; range?: RangeKey } = {}\n for (const token of (input ?? \"\").split(/\\s+/)) {\n const value = token.trim().toLowerCase()\n if (value === \"\") continue\n if ((views as readonly string[]).includes(value)) parsed.view = value as PanelView\n else if ((RANGE_KEYS as readonly string[]).includes(value)) parsed.range = value as RangeKey\n }\n return parsed\n}\n\nexport function rangeFor(key: RangeKey, now: number, sessionStart?: number | undefined): Range | undefined {\n switch (key) {\n case \"session\":\n return sessionStart === undefined ? undefined : { from: sessionStart }\n case \"today\": {\n const start = new Date(now)\n start.setHours(0, 0, 0, 0)\n return { from: start.getTime() }\n }\n case \"7d\":\n return { from: now - 7 * 24 * 60 * 60 * 1000 }\n case \"30d\":\n return { from: now - 30 * 24 * 60 * 60 * 1000 }\n case \"all\":\n return undefined\n }\n}\n\nexport function rangeLabel(key: RangeKey): string {\n switch (key) {\n case \"session\":\n return \"this session\"\n case \"today\":\n return \"today\"\n case \"7d\":\n return \"7 days\"\n case \"30d\":\n return \"30 days\"\n case \"all\":\n return \"all time\"\n }\n}\n\nexport function nextIn<Value>(values: readonly Value[], current: Value, step: number): Value {\n const index = values.indexOf(current)\n if (index === -1) return values[0]!\n return values[(index + step + values.length) % values.length]!\n}\n\n/** Which turns the `turns` view lists: the open session, or every session. */\nexport type TurnsScope = \"session\" | \"all\"\n\n/**\n * Everything the panel remembers between openings. Stored through the host's\n * durable storage, so the panel reopens where the user left it.\n */\nexport type PanelSettings = {\n view: PanelView\n range: RangeKey\n sort: string\n sortDesc: boolean\n granularity: Granularity\n turnsScope: TurnsScope\n /** Empty string means \"no filter\". */\n modelID: string\n /** The provider the model ran through. */\n providerID: string\n}\n\nexport const DEFAULT_SETTINGS: PanelSettings = {\n view: \"overview\",\n range: \"all\",\n sort: \"\",\n sortDesc: true,\n granularity: \"day\",\n turnsScope: \"session\",\n modelID: \"\",\n providerID: \"\",\n}\n\n/** Merge persisted state with the defaults, dropping anything unrecognized. */\nexport function sanitizeSettings(\n raw: Partial<PanelSettings> | undefined,\n views: readonly PanelView[] = CLIENT_VIEWS,\n): PanelSettings {\n const settings = { ...DEFAULT_SETTINGS, ...(raw ?? {}) }\n return {\n view: (views as readonly string[]).includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,\n range: (RANGE_KEYS as readonly string[]).includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,\n sort: typeof settings.sort === \"string\" ? settings.sort : DEFAULT_SETTINGS.sort,\n sortDesc: settings.sortDesc === true,\n granularity: (GRANULARITIES as readonly string[]).includes(settings.granularity) ? settings.granularity : DEFAULT_SETTINGS.granularity,\n turnsScope: settings.turnsScope === \"all\" ? \"all\" : \"session\",\n modelID: typeof settings.modelID === \"string\" ? settings.modelID : \"\",\n providerID: typeof settings.providerID === \"string\" ? settings.providerID : \"\",\n }\n}\n\n// ---------------------------------------------------------------------------\n// Primitive formatting\n// ---------------------------------------------------------------------------\n\nexport function formatPercent(value: number | undefined, digits = 1): string {\n if (value === undefined || !Number.isFinite(value)) return \"–\"\n return `${(value * 100).toFixed(digits)}%`\n}\n\nexport function formatCount(value: number): string {\n return Number.isFinite(value) ? Math.round(value).toLocaleString(\"en-US\") : \"–\"\n}\n\nexport function formatMs(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value)) return \"–\"\n const ms = Math.max(0, value)\n if (ms < 1_000) return `${Math.round(ms)}ms`\n if (ms < 60_000) return `${(ms / 1_000).toFixed(1)}s`\n return formatDuration(ms)\n}\n\nexport function formatTps(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value) || value < 0) return \"–\"\n return `${value.toFixed(1)}/s`\n}\n\n/** A rate that has to fit a sidebar: whole numbers from 10 up. */\nexport function formatTpsCompact(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value) || value < 0) return \"–\"\n return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`\n}\n\n/** Idle gaps are read at a glance: seconds, minutes, hours, days. */\nexport function formatGap(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value)) return \"–\"\n const gap = Math.max(0, value)\n if (gap < 60_000) return `${Math.round(gap / 1_000)}s`\n if (gap < 3_600_000) return `${Math.round(gap / 60_000)}m`\n if (gap < 86_400_000) return `${(gap / 3_600_000).toFixed(1)}h`\n return `${(gap / 86_400_000).toFixed(1)}d`\n}\n\n/** Cut a value to the width, dropping control characters first. */\nexport function truncate(value: string, width: number): string {\n if (width <= 1) return \"\"\n const clean = sanitizeText(value)\n if (clean.length <= width) return clean\n return `${clean.slice(0, width - 1).trimEnd()}…`\n}\n\n/** Keep both ends of a long id: the family reads first, the `#variant` last. */\nexport function truncateMiddle(value: string, width: number): string {\n if (width <= 1) return \"\"\n const clean = sanitizeText(value)\n if (clean.length <= width) return clean\n const head = Math.ceil((width - 1) / 2)\n const tail = width - 1 - head\n return `${clean.slice(0, head)}…${clean.slice(clean.length - tail)}`\n}\n\n/**\n * A model cell keeps the variant visible: two rows of the same family must not\n * read alike after truncation.\n */\nexport function modelCell(modelID: string, variant: string | undefined, width: number): string {\n return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width)\n}\n\nexport function padCell(value: string, width: number, align: \"left\" | \"right\" = \"left\"): string {\n if (value.length >= width) return value\n const padding = \" \".repeat(width - value.length)\n return align === \"right\" ? `${padding}${value}` : `${value}${padding}`\n}\n\nexport function formatTableRow(cells: readonly string[], widths: readonly number[], aligns?: readonly (\"left\" | \"right\")[]): string {\n const parts: string[] = []\n for (let index = 0; index < cells.length; index += 1) {\n const width = widths[index] ?? 8\n const align = aligns?.[index] ?? \"left\"\n parts.push(padCell(truncate(cells[index] ?? \"\", width), width, align))\n }\n return parts.join(\" \")\n}\n\n/**\n * One column in a table that has to fit a panel width. `width` is the compact\n * width (and the fixed width when `max` is omitted); `max` is the widest it may\n * grow into leftover space; optional columns carry a priority and are added\n * only when they fit. `reserve` keeps the space an optional column would\n * otherwise take from the text column before it (a model name, a provider).\n */\nexport type TableColumnFit = {\n width: number\n max?: number | undefined\n priority?: number | undefined\n reserve?: number | undefined\n}\n\nexport type FittedWidth = {\n index: number\n width: number\n}\n\n/**\n * Fit a table's columns into the panel width. Required columns are kept,\n * optional ones are added in priority order while they fit, and the leftover\n * goes to the columns in display order, each up to its maximum. Dropped\n * columns are absent from the result, so a caller never renders a zero-width\n * cell. The growth order is the display order: the text column is first.\n */\nexport function fitTableColumns(columns: readonly TableColumnFit[], width: number): FittedWidth[] {\n const chosen = new Set<number>()\n for (let index = 0; index < columns.length; index += 1) {\n if (columns[index]!.priority === undefined) chosen.add(index)\n }\n if (chosen.size === 0) return []\n const total = (): number => {\n let sum = chosen.size - 1\n for (const index of chosen) sum += columns[index]!.width\n return sum\n }\n const optional = columns\n .map((column, index) => ({ column, index }))\n .filter((entry) => entry.column.priority !== undefined)\n .sort((left, right) => left.column.priority! - right.column.priority! || left.index - right.index)\n for (const { column, index } of optional) {\n if (total() + column.width + 1 + (column.reserve ?? 0) <= width) chosen.add(index)\n }\n // A panel narrower than the required set drops its trailing columns. Every\n // formatter orders the least important required column last for this case.\n while (chosen.size > 1 && total() > width) chosen.delete(Math.max(...chosen))\n const widths = new Map<number, number>()\n let room = width - total()\n for (let index = 0; index < columns.length && room > 0; index += 1) {\n if (!chosen.has(index)) continue\n const column = columns[index]!\n const grow = Math.min(room, (column.max ?? column.width) - column.width)\n if (grow <= 0) continue\n widths.set(index, column.width + grow)\n room -= grow\n }\n return [...chosen]\n .sort((left, right) => left - right)\n .map((index) => ({ index, width: widths.get(index) ?? columns[index]!.width }))\n}\n\n/** A fitted column ready to render: header, final width, alignment and cell. */\nexport type FittedTableColumn<Row> = {\n /** The column's position in the input, so callers can find a special one. */\n index: number\n header: string\n width: number\n align: \"left\" | \"right\"\n cell: (row: Row) => string\n}\n\nexport function fitTable<Row>(\n columns: readonly (TableColumnFit & {\n header: string\n align?: \"left\" | \"right\" | undefined\n cell: (row: Row) => string\n })[],\n width: number,\n): FittedTableColumn<Row>[] {\n return fitTableColumns(columns, width).map(({ index, width: fitted }) => {\n const column = columns[index]!\n return { index, header: column.header, width: fitted, align: column.align ?? \"left\", cell: column.cell }\n })\n}\n\n\nexport function count(n: number, singular: string, plural = `${singular}s`): string {\n return `${formatCount(n)} ${n === 1 ? singular : plural}`\n}\n\n/** Two label/value pairs per row, collapsed to one pair on narrow panels. */\nexport function kvGrid(pairs: readonly (readonly [string, string])[], width: number): PanelLine[] {\n const lines: PanelLine[] = []\n const label = 11\n const column = Math.floor(width / 2)\n // A pair that cannot fit on one line keeps its label and moves the value to\n // its own indented line. The coverage window is the long one: splitting it\n // preserves the whole range instead of cutting the end date.\n const pairLines = (pair: readonly [string, string]): string[] => {\n const text = `${padCell(pair[0], label)}${pair[1]}`\n if (text.length <= width) return [text]\n return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width))\n }\n for (let index = 0; index < pairs.length; index += 2) {\n const left = pairs[index]!\n const right = pairs[index + 1]\n if (right === undefined) {\n for (const text of pairLines(left)) lines.push({ text, tone: \"base\" })\n continue\n }\n const leftText = `${padCell(left[0], label)}${left[1]}`\n const rightText = `${padCell(right[0], label)}${right[1]}`\n // Both columns have to fit the requested width: the value on the right may\n // be wider than half the panel (the coverage window dates are), and a line\n // that overflows wraps in the terminal instead of ending.\n const gap = Math.max(2, column - leftText.length)\n if (leftText.length + gap + rightText.length <= width) {\n lines.push({ text: `${leftText}${\" \".repeat(gap)}${rightText}`, tone: \"base\" })\n } else {\n for (const text of pairLines(left)) lines.push({ text, tone: \"base\" })\n for (const text of pairLines(right)) lines.push({ text, tone: \"base\" })\n }\n }\n return lines\n}\n\nconst HEADER_TONE: PanelTone = \"accent\"\nconst SPARK = [\"▁\", \"▂\", \"▃\", \"▄\", \"▅\", \"▆\", \"▇\", \"█\"] as const\n\n/** Fold a series into at most `maxBars` summed buckets, so a sparkline stays a line. */\nexport function reduceSeries(values: readonly number[], maxBars = 48): number[] {\n if (values.length <= maxBars) return [...values]\n const group = Math.ceil(values.length / maxBars)\n const reduced: number[] = []\n for (let index = 0; index < values.length; index += group) {\n reduced.push(values.slice(index, index + group).reduce((sum, value) => sum + value, 0))\n }\n return reduced\n}\n\n/** Text sparkline: trends at a glance without a chart renderable. */\nexport function sparkline(values: readonly number[], maxBars = 48): string {\n if (values.length === 0) return \"\"\n const series = reduceSeries(values, maxBars)\n const max = Math.max(...series)\n if (max <= 0) return SPARK[0]!.repeat(series.length)\n return series.map((value) => SPARK[Math.min(SPARK.length - 1, Math.max(0, Math.round((value / max) * (SPARK.length - 1))))]!).join(\"\")\n}\n\n/**\n * The live line's buckets, so every aggregate the panel shows reconciles with\n * it: `in` is the uncached prompt (fresh input *and* cache writes), `prompt` is\n * what the provider saw, `out` is everything generated (visible *and*\n * reasoning). `write` and `reasoning` are the parts of `in` and `out`.\n */\nexport type UsageBuckets = {\n steps: number\n input: number\n prompt: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n listCost: number\n hit: number | undefined\n}\n\nexport function usageBuckets(usage: {\n steps: number\n input: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n listCost?: number | undefined\n}): UsageBuckets {\n const prompt = usage.input + usage.cached + usage.cacheWrite\n return {\n steps: usage.steps,\n input: prompt - usage.cached,\n prompt,\n cached: usage.cached,\n cacheWrite: usage.cacheWrite,\n output: usage.output + usage.reasoning,\n reasoning: usage.reasoning,\n cost: usage.cost,\n listCost: usage.listCost ?? 0,\n hit: prompt > 0 ? usage.cached / prompt : undefined,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Chrome shared by every view\n// ---------------------------------------------------------------------------\n\n/**\n * The view tabs. The active one is bracketed so a single tone still reads\n * clearly; on a narrow panel the names shorten instead of wrapping, and the\n * active view always keeps its full name.\n */\nexport function viewBar(view: PanelView, width = 200, views: readonly PanelView[] = CLIENT_VIEWS): PanelLine {\n // Ten client views, ten digits: `0` is the tenth.\n const key = (index: number) => String((index + 1) % 10)\n const full = views.map((name, index) => (name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`))\n const candidates = [full, views.map((name, index) => (name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`))]\n for (const parts of candidates) {\n const text = parts.join(\" \")\n if (text.length <= width) return { text, tone: \"muted\" }\n }\n const index = views.indexOf(view)\n return { text: `[${index === -1 ? \"?\" : key(index)} ${view}] · 1-9 0 or [ ] to switch`, tone: \"muted\" }\n}\n\nexport function keysFor(of: PanelView): string {\n if (of === QUOTA_VIEW) return \"r refresh · t range · 0 view · ? help · the quotas come from OpenCode Go\"\n if (of === \"db\") return \"↑↓ pick a retention · enter prune · the last row wipes · e backfill · v vacuum · r refresh · 1-9 0 view · ? help\"\n if (of === \"periods\") return \"↑↓ move · enter drill · b bucket · t range · m/p filter · x clear · 1-9 0 view · ? help\"\n if (of === \"turns\") return \"↑↓ move · a scope · t range · m/p filter · x clear · 1-9 0 view · ? help\"\n return \"↑↓ move · enter drill · s sort · t range · m/p filter · x clear · 1-9 0 view · ? help\"\n}\n\nexport function filterSummary(filters: { modelID?: string | undefined; providerID?: string | undefined }): string | undefined {\n const parts: string[] = []\n if (filters.modelID !== undefined && filters.modelID !== \"\") parts.push(`model=${filters.modelID}`)\n if (filters.providerID !== undefined && filters.providerID !== \"\") parts.push(`provider=${filters.providerID}`)\n return parts.length > 0 ? parts.join(\" · \") : undefined\n}\n\nexport function granularityLabel(granularity: PeriodGranularity): string {\n return granularity === \"day\" ? \"per day\" : granularity === \"week\" ? \"per week\" : \"per month\"\n}\n\n/** Help overlay: the keys and the exact meaning of every number. */\nexport function helpLines(width: number): PanelLine[] {\n const lines: PanelLine[] = [\n { text: \"keys\", tone: HEADER_TONE },\n { text: \" ↑ ↓ j k move the cursor · enter drills in · backspace goes back\" },\n { text: \" 1-9 0 [ ] choose a view · cycle views (9 is db, 0 is go)\" },\n { text: \" t shift+t previous / next range\" },\n { text: \" s shift+s cycle sort column · reverse\" },\n { text: \" b periods bucket: day → week → month\" },\n { text: \" a turns scope: this session ↔ all sessions\" },\n { text: \" m p filter by model / provider (x clears)\" },\n { text: \" r re-read the database · f full screen · escape close\" },\n { text: \" e db: backfill list-price estimates for the $0 steps\" },\n { text: \"\" },\n { text: \"go quota · the host's OpenCode Go allowance\", tone: HEADER_TONE },\n { text: \" rolling the 5-hour window · weekly · monthly\" },\n { text: \" forecast the monthly percentage at its reset, from the\" },\n { text: \" cycle's average pace (not a sample history)\" },\n { text: \" renews the monthly reset reported by the host\" },\n { text: \" the plugin reads the host's local usage-limits endpoint;\" },\n { text: \" it never reads your API key and never talks to the Console.\" },\n { text: \"numbers · the same buckets as the live line\", tone: HEADER_TONE },\n { text: \" prompt everything the provider saw: cached + fresh + writes\" },\n { text: \" in the uncached part: fresh input + cache writes\" },\n { text: \" cached prompt read from the provider prompt cache\" },\n { text: \" write part of `in`: prompt written into that cache\" },\n { text: \" hit cached / prompt, weighted over the selection\" },\n { text: \" hit p50 median of the per-step hit: spots a split pattern\" },\n { text: \" out everything generated: visible output + reasoning\" },\n { text: \" reasoning part of `out`\" },\n { text: \" cost money, not tokens: a turn sums every step; $0 is left out\" },\n { text: \" other compaction/title usage: money with no assistant step;\" },\n { text: \" overview, periods and sessions include it; model rows do not\" },\n { text: \" ≈ list-price estimate for steps the host reported as $0;\" },\n { text: \" `$0.12 + ≈ $3.40` keeps charged and estimated money apart\" },\n { text: \" wall request → completed step · stream request → last chunk\" },\n { text: \" tps out / streaming seconds, shown as p50\" },\n { text: \" switches how often a step's model or provider differs from the step\" },\n { text: \" before it in the same session (the models view's detail), with\" },\n { text: \" the cache a provider switch cost\" },\n { text: \"\" },\n { text: \"identity\", tone: HEADER_TONE },\n { text: \" provider the provider the model ran through, as OpenCode is configured\" },\n { text: \" (opencode, opencode-go, deepseek, …). A gateway may re-route\" },\n { text: \" a request, but the upstream that ran the inference is not\" },\n { text: \" observable, so the provider is the identity every view shows.\" },\n { text: \"\" },\n { text: \"database\", tone: HEADER_TONE },\n { text: \" the db view shows where the file lives, what it holds and how much\" },\n { text: \" of it is old: ↑↓ pick a retention or wipe, enter asks before it\" },\n { text: \" deletes, e backfills list estimates, v gives the space back\" },\n { text: \" local time · SQLite in the OpenCode state directory\" },\n ]\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n}\n\n// ---------------------------------------------------------------------------\n// OpenCode Go quota\n// ---------------------------------------------------------------------------\n\nfunction quotaMeterLine(label: string, meter: GoMeter, now: number): PanelLine {\n const state = meter.limited || meter.percent >= 100 ? \"rate-limited\" : `${Math.round(meter.percent)}% used`\n const countdown = formatCountdown(meter.resetsAt, now)\n return {\n text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} · ${countdown === \"due\" ? \"resets due\" : `resets in ${countdown}`}`,\n tone: meter.limited || meter.percent >= 100 ? \"warning\" : \"base\",\n }\n}\n\n/** The full `go` view: the three meters, the monthly forecast and renewal. */\nexport function goQuotaLines(\n state: QuotaFetch | undefined,\n options: { now: number; width: number; name?: string | undefined; loading?: boolean | undefined; error?: string | undefined },\n): PanelLine[] {\n const { now, width, loading, error } = options\n const name = options.name?.trim() || DEFAULT_QUOTA_NAME\n const lines: PanelLine[] = []\n const push = (text: string, tone: PanelTone = \"base\"): void => {\n lines.push({ text, tone })\n }\n\n if (state === undefined) {\n if (error !== undefined && error !== \"\") push(`Go quota unavailable: ${error}`, \"warning\")\n else if (loading === true) push(\"reading OpenCode Go quota…\", \"muted\")\n else push(\"OpenCode Go quota is unavailable\", \"muted\")\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n }\n\n if (state.kind === \"none\") {\n push(name, \"accent\")\n push(\n state.reason === \"console\"\n ? \"Connect OpenCode Console with /connect to see your Go allowance.\"\n : \"This workspace has no active OpenCode Go subscription.\",\n \"muted\",\n )\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n }\n\n const quota = state.quota\n const workspace = quota.workspace?.name ?? quota.workspace?.id ?? \"workspace\"\n const status = quotaStatus(quota)\n const forecast = forecastMonthly(quota.monthly, now)\n\n push(`${name} · ${workspace}`, \"accent\")\n push(`status ${status}`, status === \"active\" ? \"base\" : \"warning\")\n // The three meters keep their own line; the helper carries the tone.\n lines.push(quotaMeterLine(\"rolling\", quota.rolling, now))\n lines.push(quotaMeterLine(\"weekly\", quota.weekly, now))\n lines.push(quotaMeterLine(\"monthly\", quota.monthly, now))\n push(\"\")\n\n if (forecast.reached || quota.monthly.limited) {\n push(`forecast monthly limit reached · renews ${formatRenewal(quota.monthly.resetsAt)}`, \"warning\")\n } else if (now >= forecast.endAt) {\n push(\"forecast monthly reset due · refresh\", \"warning\")\n } else if (!forecast.available) {\n push(\"forecast too early in the cycle to project a monthly pace\", \"muted\")\n } else if (quota.monthly.percent === 0) {\n push(\"forecast no monthly usage yet this cycle\", \"muted\")\n } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {\n push(\n `forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} · ${formatDuration(\n forecast.exhaustAt - now,\n )} from now · ${forecast.ratePerDay.toFixed(1)}%/day`,\n \"warning\",\n )\n } else {\n const projected = Math.min(999, Math.round(forecast.projectedPercent))\n const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent))\n push(`forecast ~${projected}% at reset · ${headroom}% headroom · ${forecast.ratePerDay.toFixed(1)}%/day`)\n }\n\n const renewal = formatRenewal(quota.monthly.resetsAt)\n const countdown = formatCountdown(quota.monthly.resetsAt, now)\n push(`renews ${renewal} · ${countdown === \"due\" ? \"renewal due\" : `in ${countdown}`}`, \"muted\")\n if (quota.workspace?.usageURL !== undefined) push(`console ${quota.workspace.usageURL}`, \"muted\")\n const age = Math.max(0, now - quota.observedAt)\n push(`updated ${age < 1_000 ? \"just now\" : `${formatDuration(age)} ago`}`, \"muted\")\n if (loading === true) push(\"refreshing…\", \"muted\")\n if (error !== undefined && error !== \"\") push(`quota refresh failed: ${error}`, \"warning\")\n\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n}\n\n/** The compact block the TUI sidebar and Desktop Turns panel show before the session summary. */\nexport function goSidebarLines(\n state: QuotaFetch | undefined,\n now: number,\n width: number,\n name = DEFAULT_QUOTA_NAME,\n): PanelLine[] {\n if (state?.kind !== \"ok\" || width <= 0) return []\n const quota = state.quota\n const status = quotaStatus(quota)\n const forecast = forecastMonthly(quota.monthly, now)\n const base = `5h ${Math.round(quota.rolling.percent)}% · week ${Math.round(\n quota.weekly.percent,\n )}% · month ${Math.round(quota.monthly.percent)}%`\n const baseTone: PanelTone = status !== \"active\" || quota.monthly.percent >= 80 ? \"warning\" : \"base\"\n let forecastText = \"forecast too early\"\n let forecastTone: PanelTone = \"muted\"\n if (forecast.reached || quota.monthly.limited) {\n forecastText = \"monthly limit reached\"\n forecastTone = \"warning\"\n } else if (forecast.willExhaust) {\n forecastText = \"limit before renewal\"\n forecastTone = \"warning\"\n } else if (forecast.available && quota.monthly.percent > 0) {\n forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`\n } else if (forecast.available && quota.monthly.percent === 0) {\n forecastText = \"forecast no usage yet\"\n }\n return [\n { text: truncate(name, width), tone: \"accent\" },\n { text: truncate(base, width), tone: baseTone },\n { text: truncate(forecastText, width), tone: forecastTone },\n { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: \"muted\" },\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Overview\n// ---------------------------------------------------------------------------\n\nfunction usagePairs(usage: Overview | SessionUsage | undefined, estimates = true): (readonly [string, string])[] {\n if (usage === undefined) return []\n const buckets = usageBuckets(usage)\n const pairs: (readonly [string, string])[] = [\n [\"steps\", formatCount(buckets.steps)],\n [\"in\", formatTokens(buckets.input)],\n [\"prompt\", formatTokens(buckets.prompt)],\n [\"cached\", formatTokens(buckets.cached)],\n [\"hit\", formatPercent(buckets.hit)],\n [\"out\", formatTokens(buckets.output)],\n [\"write\", formatTokens(buckets.cacheWrite)],\n ]\n if (buckets.reasoning > 0) pairs.push([\"reasoning\", formatTokens(buckets.reasoning)])\n pairs.push([\"cost\", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)])\n // The cost total includes compaction and title generations, which have no\n // step of their own. The row keeps that part visible instead of hiding it in\n // a total the step views cannot explain.\n const other = usage.otherCost ?? 0\n if (other > 0) pairs.push([\"other\", `${formatCost(other)} comp/title`])\n // The selection's average throughput, the same number the sidebar's session\n // block shows.\n if (\"tps\" in usage && usage.tps !== undefined) pairs.push([\"tps\", formatTps(usage.tps)])\n return pairs\n}\n\nexport function overviewLines(\n data: {\n usage: Overview\n session: Overview | undefined\n /** Child sessions of the open session, when it has any. */\n subagents?: readonly SessionUsage[] | undefined\n range: RangeKey\n activity?: readonly number[] | undefined\n coverage?: CoverageReport | undefined\n /** `false` hides list-price estimates. */\n estimates?: boolean | undefined\n },\n width: number,\n): PanelLine[] {\n const lines: PanelLine[] = []\n const estimates = data.estimates !== false\n lines.push({\n text: truncate(\n `${rangeLabel(data.range)} · ${count(data.usage.steps, \"step\")} · ${count(data.usage.sessions, \"session\")} · ${count(data.usage.prompts, \"prompt\")}`,\n width,\n ),\n tone: \"muted\",\n })\n lines.push(...kvGrid(buildOverviewPairs(data.usage, \"all\", estimates), width))\n if (data.activity !== undefined && data.activity.length > 1) {\n const suffix = ` ${count(data.activity.length, \"bucket\")}`\n const bars = Math.max(4, width - \"activity \".length - suffix.length)\n const series = reduceSeries(data.activity, bars)\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: \"muted\" })\n }\n if (data.session !== undefined) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"this session\", tone: HEADER_TONE })\n lines.push(...kvGrid(buildOverviewPairs(data.session, \"session\", estimates), width))\n if (data.subagents !== undefined && data.subagents.length > 0) {\n const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0)\n const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0)\n const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0)\n lines.push({\n text: truncate(\n ` subagents ${count(data.subagents.length, \"session\")} · ${count(steps, \"step\")} · ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,\n width,\n ),\n tone: \"muted\",\n })\n }\n }\n if (data.coverage !== undefined) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"data coverage\", tone: HEADER_TONE })\n lines.push(...kvGrid(coveragePairs(data.coverage), width))\n }\n return lines\n}\n\nfunction buildOverviewPairs(usage: Overview, scope: \"all\" | \"session\", estimates = true): (readonly [string, string])[] {\n const pairs = usagePairs(usage, estimates)\n if (scope === \"all\") {\n pairs.push([\"first\", usage.firstAt === undefined ? \"–\" : new Date(usage.firstAt).toLocaleString(\"en-GB\")])\n pairs.push([\"last\", usage.lastAt === undefined ? \"–\" : new Date(usage.lastAt).toLocaleString(\"en-GB\")])\n }\n return pairs\n}\n\nfunction coveragePairs(coverage: CoverageReport): (readonly [string, string])[] {\n const share = (missing: number) => (coverage.steps === 0 ? \"–\" : `${((missing / coverage.steps) * 100).toFixed(1)}%`)\n return [\n [\"models\", `${formatCount(coverage.models)} · unknown ${share(coverage.missingModel)}`],\n [\"providers\", formatCount(coverage.providers)],\n [\"unsettled\", `${formatCount(coverage.unsettled)} · no tps ${share(coverage.missingTps)}`],\n [\n \"window\",\n `${coverage.firstAt === undefined ? \"–\" : new Date(coverage.firstAt).toLocaleString(\"en-GB\")} → ${\n coverage.lastAt === undefined ? \"–\" : new Date(coverage.lastAt).toLocaleString(\"en-GB\")\n }`,\n ],\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Models\n// ---------------------------------------------------------------------------\n\nexport type ModelExtras = {\n /** Reuse stats per `modelKey`, computed from the step facts. */\n cache?: Map<string, CacheStats> | undefined\n /** Switches per `modelKey`, computed from the consecutive step pairs. */\n switches?: Map<string, SwitchRow> | undefined\n}\n\ntype ModelRowView = {\n modelID: string\n variant: string | undefined\n steps: string\n prompt: string\n cached: string\n hit: string\n output: string\n cost: string\n providers: string\n detail: string\n}\n\n/**\n * Usage per model with the cache it actually got, the providers it ran through\n * and how often its identity changed. One line per model; `providers` keeps the\n * per-provider detail.\n */\nexport function modelsLines(rows: readonly ModelUsage[], width: number, extras?: ModelExtras, limit = 40, estimates = true): PanelLine[] {\n // The name cell needs the final column width; fitTable only measures the\n // specs, so the value is filled in after the fit and before any row renders.\n let modelWidth = 14\n const columns = fitTable<ModelRowView>(\n [\n { header: \"model\", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => row.steps },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", cell: (row) => row.prompt },\n { header: \"cached\", width: 7, max: 10, align: \"right\", cell: (row) => row.cached },\n { header: \"hit\", width: 6, max: 7, priority: 2, reserve: 10, align: \"right\", cell: (row) => row.hit },\n { header: \"out\", width: 7, max: 9, priority: 3, reserve: 10, align: \"right\", cell: (row) => row.output },\n { header: \"cost\", width: 8, max: 9, priority: 1, align: \"right\", cell: (row) => row.cost },\n { header: \"providers\", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers },\n ],\n width,\n )\n modelWidth = columns.find((column) => column.index === 0)?.width ?? 0\n if (columns.length === 0) return [{ text: truncate(\"no room for a table at this width\", width), tone: \"muted\" }]\n const lines: PanelLine[] = [\n {\n text: formatTableRow(\n columns.map((column) => column.header),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: HEADER_TONE,\n },\n ]\n\n for (const model of rows.slice(0, limit)) {\n const key = modelKey(model.modelID, model.variant)\n const buckets = usageBuckets(model.totals)\n // The same model can come from more than one provider, so the column names\n // them; the detail line below carries the reuse and the change count.\n const providers = unique(model.providers.map((provider) => provider.providerID))\n const cache = extras?.cache?.get(key)\n const switches = extras?.switches?.get(key)\n const details: string[] = []\n if (cache !== undefined) details.push(`p50 hit ${formatPercent(cache.hitP50)}`)\n if (switches !== undefined && switches.changes > 0) {\n // The dimensions overlap — a single switch can change both — so the\n // provider count is given as the part of the total that can cost a cache.\n const scope = switches.providerChanges > 0 ? ` (${formatCount(switches.providerChanges)} provider)` : \"\"\n details.push(`${count(switches.changes, \"switch\", \"switches\")}${scope}`)\n if (switches.cacheLost > 0) details.push(`${formatTokens(switches.cacheLost)} lost on a switch`)\n }\n const view: ModelRowView = {\n modelID: model.modelID,\n variant: model.variant,\n steps: formatCount(buckets.steps),\n prompt: formatTokens(buckets.prompt),\n cached: formatTokens(buckets.cached),\n hit: formatPercent(cache?.hit ?? buckets.hit),\n output: formatTokens(buckets.output),\n cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),\n providers: providers.join(\", \"),\n detail: details.join(\" · \"),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(view)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: \"base\",\n row: { kind: \"model\", value: model.modelID, ...(model.variant !== undefined ? { variant: model.variant } : {}) },\n })\n if (view.detail !== \"\") {\n lines.push({ text: truncate(`${\" \".repeat(modelWidth + 1)}${view.detail}`, width), tone: \"muted\" })\n }\n }\n if (rows.length > limit) lines.push({ text: truncate(`… ${count(rows.length - limit, \"more model\")} · narrow the range or filter`, width), tone: \"muted\" })\n if (rows.length === 0) lines.push({ text: truncate(\"no usage recorded for this range\", width), tone: \"muted\" })\n return lines\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)]\n}\n\n// ---------------------------------------------------------------------------\n// Providers (model × provider)\n// ---------------------------------------------------------------------------\n\n/**\n * A table column. Header, fitting spec, alignment and cell come from the same\n * definition, so dropping a column can never shift the others. The cell gets\n * the final width so a name can be shortened in the middle.\n */\ntype TableSpec<Row> = TableColumnFit & {\n header: string\n align?: \"left\" | \"right\" | undefined\n cell: (row: Row, width: number) => string\n}\n\nfunction renderTable<Row>(\n rows: readonly Row[],\n columns: readonly TableSpec<Row>[],\n width: number,\n options: { limit: number; empty: string; row?: (row: Row) => PanelRow | undefined; tone?: (row: Row) => PanelTone },\n): PanelLine[] {\n const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {\n const column = columns[index]!\n const align: \"left\" | \"right\" = column.align ?? \"left\"\n return { ...column, width: fitted, align }\n })\n if (chosen.length === 0) return [{ text: truncate(options.empty, width), tone: \"muted\" }]\n const widths = chosen.map((column) => column.width)\n const aligns = chosen.map((column) => column.align)\n const lines: PanelLine[] = [\n { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE },\n ]\n if (rows.length === 0) lines.push({ text: truncate(options.empty, width), tone: \"muted\" })\n for (const row of rows.slice(0, options.limit)) {\n const identity = options.row?.(row)\n lines.push({\n text: formatTableRow(\n chosen.map((column) => column.cell(row, column.width)),\n widths,\n aligns,\n ),\n tone: options.tone?.(row) ?? \"base\",\n ...(identity === undefined ? {} : { row: identity }),\n })\n }\n if (rows.length > options.limit) {\n lines.push({ text: truncate(`… ${count(rows.length - options.limit, \"more row\")}`, width), tone: \"muted\" })\n }\n return lines\n}\n\n/** One row per provider, over every model it served. */\nexport function providerSummaryLines(rows: readonly ProviderSummary[], width: number, limit = 40, estimates = true): PanelLine[] {\n const lines = renderTable(\n rows,\n [\n { header: \"provider\", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? \"– (unknown)\", column) },\n { header: \"models\", width: 6, align: \"right\", priority: 4, cell: (row) => formatCount(row.models.length) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => formatCount(row.usage.steps) },\n { header: \"share\", width: 6, align: \"right\", priority: 3, cell: (row) => formatPercent(row.share, 0) },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.prompt) },\n { header: \"cached\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.cached) },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 2, cell: (row) => formatPercent(row.cache.hit) },\n { header: \"tps p50\", width: 8, align: \"right\", priority: 5, cell: (row) => formatTps(row.tps) },\n { header: \"wall\", width: 7, align: \"right\", priority: 6, cell: (row) => formatMs(row.wall) },\n { header: \"cost\", width: 8, max: 9, align: \"right\", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) },\n ],\n width,\n {\n limit,\n empty: \"no usage recorded for this range\",\n // A step recorded without a provider is not a row to drill into.\n row: (row) => (row.provider === undefined ? undefined : { kind: \"provider\", value: row.provider }),\n tone: (row) => (row.provider === undefined ? \"muted\" : \"base\"),\n },\n )\n return lines\n}\n\n/** One row per model × provider: the providers each model ran through. */\nexport function providerLines(rows: readonly ProviderRow[], width: number, limit = 40, estimates = true): PanelLine[] {\n return renderTable(\n rows,\n [\n { header: \"model\", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },\n { header: \"provider\", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? \"– (unknown)\", column) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => formatCount(row.usage.steps) },\n { header: \"share\", width: 6, align: \"right\", priority: 5, cell: (row) => formatPercent(row.share, 0) },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },\n { header: \"cached\", width: 7, max: 10, align: \"right\", priority: 3, cell: (row) => formatTokens(row.cache.cached) },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 4, cell: (row) => formatPercent(row.cache.hit) },\n { header: \"tps p50\", width: 8, align: \"right\", priority: 6, cell: (row) => formatTps(row.tps) },\n { header: \"wall\", width: 7, align: \"right\", priority: 7, cell: (row) => formatMs(row.wall) },\n { header: \"cost\", width: 8, max: 9, align: \"right\", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) },\n ],\n width,\n {\n limit,\n empty: \"no usage recorded for this range\",\n row: (row) => ({ kind: \"model\", value: row.modelID, ...(row.variant !== undefined ? { variant: row.variant } : {}) }),\n tone: (row) => (row.provider === undefined ? \"muted\" : \"base\"),\n },\n )\n}\n\n// ---------------------------------------------------------------------------\n// Cache\n// ---------------------------------------------------------------------------\n\n/** One model's reuse row, shared by the models and cache views. */\nexport type CacheModelRow = {\n usage: { modelID: string; variant: string | undefined }\n cache: CacheStats\n}\n\nexport function cacheLines(\n data: {\n drops: readonly CacheDropRow[]\n evidence: readonly TtlEvidenceRow[]\n gap?: GapReport | undefined\n models?: readonly CacheModelRow[] | undefined\n },\n width: number,\n): PanelLine[] {\n const lines: PanelLine[] = []\n const push = (text: string, tone: PanelTone = \"base\"): void => {\n lines.push({ text: truncate(text, width), tone })\n }\n const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0)\n push(`reuse losses ${count(data.drops.length, \"event\")} · ${formatTokens(total)} tokens`, total > 0 ? \"warning\" : \"base\")\n for (const reason of [\"expired\", \"compaction\", \"unknown\"] as const) {\n const group = data.drops.filter((drop) => drop.reason === reason)\n if (group.length === 0) continue\n const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0)\n push(` ${padCell(reason, 11)}${formatCount(group.length)} · ${formatTokens(tokens)}`, reason === \"expired\" ? \"warning\" : \"muted\")\n }\n if (data.drops.length === 0) push(\" none: prompt cache held through every gap\", \"muted\")\n\n if (data.models !== undefined && data.models.length > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"reuse by model\", HEADER_TONE)\n // The model name keeps the variant visible; the width has to be known\n // before a cell is built, so it is filled in after the fit.\n let modelWidth = 12\n const reuse = fitTable<CacheModelRow>(\n [\n { header: \"model\", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => formatCount(row.cache.steps) },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.prompt) },\n { header: \"cached\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.cached) },\n { header: \"write\", width: 6, max: 8, align: \"right\", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 2, cell: (row) => formatPercent(row.cache.hit) },\n { header: \"hit p50\", width: 7, max: 9, align: \"right\", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) },\n ],\n width,\n )\n modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0\n if (reuse.length > 0) {\n lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: \"muted\" })\n for (const row of data.models.slice(0, 10)) {\n lines.push({\n text: formatTableRow(\n reuse.map((column) => column.cell(row)),\n reuse.map((column) => column.width),\n reuse.map((column) => column.align),\n ),\n tone: \"base\",\n row: { kind: \"model\", value: row.usage.modelID, ...(row.usage.variant !== undefined ? { variant: row.usage.variant } : {}) },\n })\n }\n }\n }\n\n if (data.gap !== undefined && data.gap.samples > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"cache survival against idle time\", HEADER_TONE)\n const buckets = data.gap.buckets\n const survival = fitTable<(typeof buckets)[number]>(\n [\n { header: \"gap\", width: 8, max: 12, cell: (bucket) => bucket.label },\n { header: \"pairs\", width: 6, align: \"right\", cell: (bucket) => formatCount(bucket.samples) },\n { header: \"kept\", width: 7, align: \"right\", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },\n { header: \"drops\", width: 7, align: \"right\", cell: (bucket) => formatCount(bucket.drops) },\n { header: \"lost\", width: 8, align: \"right\", cell: (bucket) => formatTokens(bucket.lostTokens) },\n ],\n width,\n )\n if (survival.length > 0) {\n lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: \"muted\" })\n for (const bucket of buckets) {\n if (bucket.samples === 0) continue\n lines.push({\n text: formatTableRow(\n survival.map((column) => column.cell(bucket)),\n survival.map((column) => column.width),\n survival.map((column) => column.align),\n ),\n tone: bucket.drops > 0 ? \"warning\" : \"base\",\n })\n }\n }\n if (data.gap.providers.length > 1) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"reuse kept, by provider\", HEADER_TONE)\n const providers = data.gap.providers\n const reuse = fitTable<(typeof providers)[number]>(\n [\n { header: \"provider\", width: 12, max: 30, cell: (row) => row.provider },\n { header: \"pairs\", width: 6, align: \"right\", cell: (row) => formatCount(row.samples) },\n { header: \"kept\", width: 7, align: \"right\", cell: (row) => formatPercent(row.retainedRatio, 0) },\n { header: \"lost\", width: 8, align: \"right\", cell: (row) => formatTokens(row.lostTokens) },\n ],\n width,\n )\n if (reuse.length > 0) {\n lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: \"muted\" })\n for (const row of providers.slice(0, 8)) {\n lines.push({\n text: formatTableRow(\n reuse.map((column) => column.cell(row)),\n reuse.map((column) => column.width),\n reuse.map((column) => column.align),\n ),\n tone: \"base\",\n })\n }\n }\n }\n }\n\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"observed cache TTL bounds\", HEADER_TONE)\n if (data.evidence.length === 0) {\n push(\" no comparable step pairs yet\", \"muted\")\n } else {\n const evidence = fitTable<TtlEvidenceRow>(\n [\n { header: \"model\", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },\n { header: \"hits up to\", width: 10, align: \"right\", cell: (row) => formatGap(row.maxHitGapMs) },\n { header: \"drops from\", width: 10, align: \"right\", cell: (row) => formatGap(row.minDropGapMs) },\n { header: \"samples\", width: 7, align: \"right\", priority: 1, cell: (row) => formatCount(row.samples) },\n ],\n width,\n )\n if (evidence.length > 0) {\n lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: \"muted\" })\n for (const row of data.evidence.slice(0, 10)) {\n lines.push({\n text: formatTableRow(\n evidence.map((column) => column.cell(row)),\n evidence.map((column) => column.width),\n evidence.map((column) => column.align),\n ),\n tone: \"base\",\n })\n }\n }\n }\n\n if (data.drops.length > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"recent losses\", HEADER_TONE)\n const losses = fitTable<CacheDropRow>(\n [\n { header: \"when\", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString(\"en-GB\") },\n { header: \"provider/model\", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? \"\"}/${drop.modelID ?? \"\"}` },\n { header: \"tokens\", width: 7, align: \"right\", cell: (drop) => `−${formatTokens(drop.tokens)}` },\n { header: \"idle\", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle · ${drop.reason}` },\n ],\n width,\n )\n if (losses.length > 0) {\n lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: \"muted\" })\n for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {\n lines.push({\n text: formatTableRow(\n losses.map((column) => column.cell(drop)),\n losses.map((column) => column.width),\n losses.map((column) => column.align),\n ),\n tone: drop.reason === \"expired\" ? \"warning\" : \"base\",\n })\n }\n }\n }\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Periods\n// ---------------------------------------------------------------------------\n\ntype PeriodView = {\n label: string\n steps: string\n sessions: string\n prompt: string\n cached: string\n hit: string\n output: string\n cost: string\n}\n\nexport function periodLines(\n rows: readonly PeriodRow[],\n width: number,\n granularity: PeriodGranularity,\n limit = 40,\n estimates = true,\n totalSessions?: number,\n): PanelLine[] {\n const lines: PanelLine[] = []\n const totals = rows.reduce(\n (sum, row) => {\n sum.steps += row.usage.steps\n sum.sessions += row.sessions\n sum.input += row.usage.input\n sum.cached += row.usage.cached\n sum.cacheWrite += row.usage.cacheWrite\n sum.output += row.usage.output\n sum.reasoning += row.usage.reasoning\n sum.cost += row.usage.cost\n sum.listCost += row.usage.listCost\n return sum\n },\n { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 },\n )\n const overall = usageBuckets(totals)\n lines.push({\n text: truncate(\n `${granularityLabel(granularity)} · ${count(rows.length, \"period\")} · ${count(totals.steps, \"step\")} · hit ${formatPercent(overall.hit)}`,\n width,\n ),\n tone: \"muted\",\n })\n if (rows.length > 1) {\n const bars = Math.max(4, width - 8)\n lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: \"muted\" })\n lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: \"muted\" })\n lines.push({\n text: truncate(\n `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 10_000)), bars)}`,\n width,\n ),\n tone: \"muted\",\n })\n }\n const columns = fitTable<PeriodView>(\n [\n { header: \"period\", width: 10, max: 24, cell: (row) => row.label },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => row.steps },\n { header: \"sess\", width: 6, align: \"right\", priority: 5, cell: (row) => row.sessions },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", priority: 1, cell: (row) => row.prompt },\n { header: \"cached\", width: 7, max: 10, align: \"right\", priority: 2, cell: (row) => row.cached },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 3, cell: (row) => row.hit },\n { header: \"out\", width: 7, max: 9, align: \"right\", priority: 4, cell: (row) => row.output },\n { header: \"cost\", width: 8, max: 9, align: \"right\", cell: (row) => row.cost },\n ],\n width,\n )\n if (columns.length === 0) return [...lines, { text: truncate(\"no room for a table at this width\", width), tone: \"muted\" }]\n const header = formatTableRow(\n columns.map((column) => column.header),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n )\n lines.push({ text: header, tone: HEADER_TONE })\n\n const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit)\n for (const row of newest) {\n const buckets = usageBuckets(row.usage)\n const view: PeriodView = {\n label: row.label,\n steps: formatCount(row.steps),\n sessions: formatCount(row.sessions),\n prompt: formatTokens(buckets.prompt),\n cached: formatTokens(buckets.cached),\n hit: formatPercent(buckets.hit, 0),\n output: formatTokens(buckets.output),\n cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(view)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: \"base\",\n row: { kind: \"period\", value: row.key },\n })\n }\n lines.push({ text: \"\", tone: \"muted\" })\n const total: PeriodView = {\n label: \"total\",\n steps: formatCount(totals.steps),\n // A session active in several periods is one session, not one per period:\n // the total row uses the range's distinct count when given.\n sessions: formatCount(totalSessions ?? totals.sessions),\n prompt: formatTokens(overall.prompt),\n cached: formatTokens(overall.cached),\n hit: formatPercent(overall.hit, 0),\n output: formatTokens(overall.output),\n cost: formatSpend(overall.cost, estimates ? overall.listCost : 0),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(total)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: HEADER_TONE,\n })\n if (rows.length === 0) lines.push({ text: truncate(\"no usage recorded for this range\", width), tone: \"muted\" })\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Latency\n// ---------------------------------------------------------------------------\n\n/** One metric line for a panel too narrow for the fixed percentile table. */\nfunction latencyMetric(label: string, values: readonly string[], width: number): string {\n const prefix = padCell(label, 11)\n let text = `${prefix}${values[0] ?? \"–\"}`\n for (let index = 1; index < values.length; index += 1) {\n const next = `${text} · ${values[index]!}`\n if (next.length > width) break\n text = next\n }\n return text\n}\n\nexport function latencyLines(report: LatencyReport, width: number, groups?: readonly LatencyGroupRow[] | undefined, limit = 12, estimates = true): PanelLine[] {\n const lines: PanelLine[] = []\n if (width >= 68) {\n lines.push({\n text: formatTableRow(\n [\"wall\", \"p50\", formatMs(report.wall.p50), \"p90\", formatMs(report.wall.p90), \"p99\", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`],\n [10, 4, 9, 4, 9, 4, 9, 12],\n ),\n tone: \"base\",\n })\n lines.push({\n text: formatTableRow([\"stream\", \"p50\", formatMs(report.stream.p50), \"p90\", formatMs(report.stream.p90), \"p99\", formatMs(report.stream.p99)], [10, 4, 9, 4, 9, 4, 9]),\n tone: \"base\",\n })\n lines.push({\n text: formatTableRow([\"throughput\", \"p50\", formatTps(report.tps.p50), \"p90\", formatTps(report.tps.p90), \"p99\", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),\n tone: \"base\",\n })\n } else {\n // The three-row percentile table needs 68 columns. Below that each metric\n // keeps p50 and adds p90/p99 while they fit, instead of overflowing.\n lines.push({\n text: latencyMetric(\"wall\", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),\n tone: \"base\",\n })\n lines.push({\n text: latencyMetric(\"stream\", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),\n tone: \"base\",\n })\n lines.push({\n text: latencyMetric(\"throughput\", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),\n tone: \"base\",\n })\n }\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({\n text: truncate(\"wall = request to completed · stream = request to last chunk · throughput = output+reasoning tokens/s\", width),\n tone: \"muted\",\n })\n if (report.wall.count === 0) lines.push({ text: truncate(\"no completed steps for this range\", width), tone: \"muted\" })\n\n if (groups !== undefined && groups.length > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"by group\", tone: HEADER_TONE })\n const columns = fitTable<LatencyGroupRow>(\n [\n { header: \"group\", width: 8, max: 32, cell: (row) => row.label },\n { header: \"n\", width: 4, align: \"right\", cell: (row) => formatCount(row.count) },\n { header: \"wall p50\", width: 8, align: \"right\", cell: (row) => formatMs(row.wall.p50) },\n { header: \"wall p90\", width: 8, max: 9, align: \"right\", priority: 1, cell: (row) => formatMs(row.wall.p90) },\n { header: \"stream\", width: 6, max: 9, align: \"right\", priority: 2, cell: (row) => formatMs(row.stream.p50) },\n { header: \"tps p50\", width: 8, max: 9, align: \"right\", cell: (row) => formatTps(row.tps.p50) },\n { header: \"tps p90\", width: 8, max: 9, align: \"right\", priority: 3, cell: (row) => formatTps(row.tps.p90) },\n { header: \"cost\", width: 8, max: 9, align: \"right\", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) },\n ],\n width,\n )\n if (columns.length > 0) {\n lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: \"muted\" })\n for (const row of groups.slice(0, limit)) {\n const thin = row.count < 5\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(row)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: thin ? \"muted\" : \"base\",\n row: { kind: \"model\", value: row.key },\n })\n }\n }\n lines.push({ text: truncate(\"n < 5 is dimmed: too few samples to compare\", width), tone: \"muted\" })\n }\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\ntype SessionView = {\n title: string\n steps: string\n prompt: string\n cached: string\n hit: string\n output: string\n cost: string\n}\n\nexport function sessionsLines(\n rows: readonly SessionUsage[],\n width: number,\n options?: {\n limit?: number | undefined\n estimates?: boolean | undefined\n rollup?: { subagentSteps: number; subagentCost: number; subagentListCost?: number | undefined } | undefined\n },\n): PanelLine[] {\n const limit = options?.limit ?? 20\n const estimates = options?.estimates !== false\n const columns = fitTable<SessionView>(\n [\n { header: \"title\", width: 10, max: 48, cell: (row) => row.title },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => row.steps },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", priority: 1, cell: (row) => row.prompt },\n { header: \"cached\", width: 7, max: 10, align: \"right\", priority: 2, cell: (row) => row.cached },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 3, cell: (row) => row.hit },\n { header: \"out\", width: 7, max: 9, align: \"right\", priority: 4, cell: (row) => row.output },\n // The cost is the one column a narrow panel must keep: the list is a\n // spend report before it is a token report.\n { header: \"cost\", width: 8, max: 9, align: \"right\", cell: (row) => row.cost },\n ],\n width,\n )\n const lines: PanelLine[] = [\n {\n text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),\n tone: HEADER_TONE,\n },\n ]\n const byID = new Map(rows.map((row) => [row.sessionID, row]))\n const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID))\n const children = rows.filter((row) => row.parentID !== undefined && byID.has(row.parentID))\n const orderedAll = [...ordered, ...children]\n\n for (const row of orderedAll.slice(0, limit)) {\n const child = row.parentID !== undefined && byID.has(row.parentID)\n const buckets = usageBuckets(row)\n const view: SessionView = {\n title: `${child ? \"↳ \" : \"\"}${row.title ?? row.sessionID}`,\n steps: formatCount(buckets.steps),\n prompt: formatTokens(buckets.prompt),\n cached: formatTokens(buckets.cached),\n hit: formatPercent(buckets.hit, 0),\n output: formatTokens(buckets.output),\n cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(view)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: child ? \"muted\" : \"base\",\n row: { kind: \"session\", value: row.sessionID },\n })\n const details = [\n row.directory ?? \"\",\n row.models.length > 1 ? count(row.models.length, \"model\") : \"\",\n (row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost!)}` : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" · \")\n lines.push({ text: truncate(`${\" \".repeat(child ? 2 : 0)} ${details}`, width), tone: \"muted\" })\n }\n if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {\n const share = rows.reduce((sum, row) => sum + row.steps, 0)\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({\n text: truncate(\n `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) · ${formatSpend(\n options.rollup.subagentCost,\n estimates ? (options.rollup.subagentListCost ?? 0) : 0,\n )}`,\n width,\n ),\n tone: \"muted\",\n })\n }\n if (rows.length > limit) lines.push({ text: truncate(`… ${count(rows.length - limit, \"more session\")} · narrow the range`, width), tone: \"muted\" })\n if (rows.length === 0) lines.push({ text: truncate(\"no sessions recorded for this range\", width), tone: \"muted\" })\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Database\n// ---------------------------------------------------------------------------\n\n/** The database view: where it lives, what it holds, and the two cleanups. */\nexport function dbLines(data: { info: DbInfo; busy?: boolean | undefined; now: number; estimates?: boolean | undefined }, width: number): PanelLine[] {\n const lines: PanelLine[] = []\n const size = (bytes: number) => `${(bytes / 1_048_576).toFixed(1)} MB`\n lines.push({ text: truncate(data.info.path, width), tone: \"base\" })\n lines.push({\n text: truncate(\n `${size(data.info.bytes)}${data.info.walBytes === undefined ? \"\" : ` + ${size(data.info.walBytes)} wal`} · schema v${data.info.schemaVersion}`,\n width,\n ),\n tone: \"muted\",\n })\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"what it holds\", tone: HEADER_TONE })\n for (const table of data.info.tables) {\n lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? \"muted\" : \"base\" })\n }\n lines.push({\n text: truncate(\n ` window ${data.info.firstAt === undefined ? \"–\" : new Date(data.info.firstAt).toLocaleDateString(\"en-GB\")} → ${\n data.info.lastAt === undefined ? \"–\" : new Date(data.info.lastAt).toLocaleDateString(\"en-GB\")\n }`,\n width,\n ),\n tone: \"muted\",\n })\n\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"clean up\", tone: HEADER_TONE })\n // The retention rows and the wipe row are the only selectable lines here, so\n // the hint says how to pick one and what Enter does: a retention row is a\n // cutoff, not a count, and the last row is everything. Only the TUI renders\n // this line; the desktop panel has buttons instead.\n lines.push({\n text: truncate(\n ` ↑↓ pick a retention · enter prunes from its cutoff · the wipe row deletes everything (asks first)${\n data.estimates === false ? \"\" : \" · e backfills list estimates\"\n } · v gives the space back`,\n width,\n ),\n tone: \"muted\",\n hint: true,\n })\n if (data.estimates !== false) {\n lines.push({\n text: truncate(\n data.info.schemaVersion < 10\n ? \" list estimates the recorder must upgrade this database first\"\n : data.info.unpriced === 0\n ? \" list estimates every $0 step has a price\"\n : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price`,\n width,\n ),\n tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? \"base\" : \"muted\",\n })\n }\n const widths = [9, 11, 10]\n lines.push({ text: formatTableRow([\"keep\", \"prunes\", \"older than\"], widths, [\"left\", \"right\", \"left\"]), tone: \"muted\" })\n for (const option of data.info.removable) {\n const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString(\"en-GB\")\n lines.push({\n text: formatTableRow([`${option.days} days`, `${formatCount(option.steps)} steps`, before], widths, [\"left\", \"right\", \"left\"]),\n tone: option.steps === 0 ? \"muted\" : \"base\",\n row: { kind: \"prune\", value: String(option.days) },\n })\n }\n const steps = data.info.tables.find((table) => table.name === \"steps\")?.rows ?? 0\n const sessions = data.info.tables.find((table) => table.name === \"sessions\")?.rows ?? 0\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({\n text: truncate(` wipe everything · ${formatCount(steps)} steps · ${formatCount(sessions)} sessions · cannot be undone`, width),\n tone: steps === 0 && sessions === 0 ? \"muted\" : \"warning\",\n row: { kind: \"wipe\", value: \"all\" },\n })\n if (data.busy === true) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: truncate(\"the recorder is writing: try the vacuum again in a moment\", width), tone: \"warning\" })\n }\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Turns\n// ---------------------------------------------------------------------------\n\nexport type LineFormatOptions = {\n labels?: Partial<LineLabels> | undefined\n fields?: Partial<LineFields> | undefined\n turnTotals?: TurnTotalsView | undefined\n /** `false` hides list-price estimates everywhere this line is rendered. */\n estimates?: boolean | undefined\n}\n\n/** The line's own view of a recorded turn, so both render identically. */\nexport function turnStats(turn: TurnUsage): TurnStats {\n return {\n endAt: turn.endAt,\n startAt: turn.promptAt ?? turn.endAt,\n promptAt: turn.promptAt,\n promptGapMs: turn.promptGapMs,\n providerID: turn.providerID,\n modelID: turn.modelID,\n variant: turn.variant,\n providerChanged: turn.providerChanged,\n modelChanged: turn.modelChanged,\n totals: turn.totals,\n latest: turn.latest,\n session: undefined,\n drops: turn.drops.map((drop) => ({ messageID: drop.messageID, tokens: drop.tokens, prevCached: 0, gapMs: drop.gapMs })),\n cacheDropTokens: turn.drops.reduce((sum, drop) => sum + drop.tokens, 0),\n cacheExpired: turn.drops.length > 0,\n steps: turn.steps,\n }\n}\n\n/**\n * A budget form of the turn line for a panel too narrow for the live line.\n * It always keeps the money and the identity, then adds the token volumes\n * while they fit. `turnsLines` uses the full line whenever it fits, so this\n * only changes the rows that would otherwise have their tail cut off.\n */\nexport function compactTurnLine(stats: TurnStats, width: number, options?: LineFormatOptions): string {\n const labels = { ...DEFAULT_LABELS, ...options?.labels }\n const fields = { ...DEFAULT_FIELDS, ...options?.fields }\n const estimates = options?.estimates !== false\n const headParts: string[] = []\n if (fields.clock && stats.endAt !== undefined) headParts.push(formatClock(stats.endAt))\n if (stats.providerID !== undefined) {\n let identity = stats.providerID\n if (fields.model && stats.modelID !== undefined) identity += `/${stats.modelID}`\n if (fields.variant && stats.variant) identity += ` ${stats.variant}`\n headParts.push(identity)\n }\n let head = headParts.join(\" \")\n const totals = options?.turnTotals === \"sum\" ? stats.totals : stats.latest\n const display = displayTotals(totals)\n const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined\n const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim()\n const warning =\n fields.cacheExpiry && stats.cacheExpired\n ? `⚠ ${labels.cacheExpired} (−${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` ×${stats.drops.length}` : \"\"})`\n : undefined\n // Money and the cache warning are the facts that must survive; the tokens\n // are added only while the line still fits.\n let suffix = [warning, cost].filter((part): part is string => part !== undefined).join(\" · \")\n if (suffix !== \"\" && suffix.length + 3 > width) suffix = cost ?? suffix\n head = truncate(head, Math.max(0, width - (suffix === \"\" ? 0 : suffix.length + 3)))\n if (!fields.turn || stats.totals.steps === 0) return [head, suffix].filter((part) => part !== \"\").join(\" · \")\n const input =\n display.prompt === display.input\n ? `${labels.input} ${formatTokens(display.input)}`\n : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`\n const volumes = [\n input,\n `${labels.cached} ${formatTokens(display.cached)}`,\n `${labels.output} ${formatTokens(display.output)}`,\n ...(fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []),\n ]\n let numbers = \"\"\n for (const volume of volumes) {\n const next = numbers === \"\" ? volume : `${numbers}, ${volume}`\n if ([head, next, suffix].filter((part) => part !== \"\").join(\" · \").length > width) break\n numbers = next\n }\n return [head, numbers, suffix].filter((part) => part !== \"\").join(\" · \")\n}\n\n/**\n * Per-prompt history: one line per finished turn, rendered by the same\n * formatter as the live line (without the session segment, which would repeat\n * the same totals on every row). A narrow panel uses `compactTurnLine` rather\n * than cutting the money off the end of the line.\n */\nexport function turnsLines(rows: readonly TurnUsage[], width: number, options?: LineFormatOptions & { sessionTitles?: Map<string, string> | undefined }): PanelLine[] {\n const lines: PanelLine[] = []\n const warning = rows.filter((turn) => turn.drops.length > 0).length\n lines.push({\n text: truncate(`${count(rows.length, \"turn\")} · newest first${warning > 0 ? ` · ${count(warning, \"turn\")} with a cache loss` : \"\"}`, width),\n tone: \"muted\",\n })\n const showSession = options?.sessionTitles !== undefined\n for (const turn of rows) {\n const stats = turnStats(turn)\n const line = formatLine(stats, {\n ...options,\n fields: { ...options?.fields, session: false },\n })\n const title = showSession ? `${truncate(options!.sessionTitles!.get(turn.sessionID) ?? turn.sessionID, 18)} ` : \"\"\n const available = Math.max(0, width - title.length)\n const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`\n lines.push({\n text: truncate(text, width),\n tone: turn.drops.length > 0 || turn.providerChanged ? \"warning\" : \"base\",\n row: { kind: \"turn\", value: turn.sessionID },\n })\n }\n if (rows.length === 0) lines.push({ text: truncate(\"no finished turns for this range\", width), tone: \"muted\" })\n return lines\n}\n\n/**\n * The accumulated usage of one session, as compact lines for the sidebar. The\n * buckets are the live line's, so the sidebar, the line and the panel agree.\n */\nexport function sessionSummaryLines(usage: Overview, budget = 34, estimates = true): PanelLine[] {\n const buckets = usageBuckets(usage)\n const steps = formatCount(buckets.steps)\n const input = formatTokens(buckets.input)\n const cached = formatTokens(buckets.cached)\n const out = formatTokens(buckets.output)\n const hit = formatPercent(buckets.hit)\n const tps = formatTpsCompact(usage.tps)\n const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)\n // The same order as a turn's three lines: how much was sent (`in`, `cached`),\n // how much came back (`out`), then `hit`, the rate and the cost last.\n const first = [\n ` ${steps} steps · in ${input}`,\n ` ${steps} steps`,\n ].find((text) => text.length <= budget)\n const second = [\n ` cached ${cached} · out ${out}`,\n ` cached ${cached}`,\n ].find((text) => text.length <= budget)\n const last = [\n ` hit ${hit} · ${tps} · ${cost}`,\n ` hit ${hit} · ${cost}`,\n ` ${cost}`,\n ].find((text) => text.length <= budget)\n return [\n { text: truncate(\"session\", budget), tone: HEADER_TONE },\n { text: truncate(first ?? ` ${steps} steps`, budget), tone: \"muted\" },\n { text: truncate(second ?? ` cached ${cached}`, budget), tone: \"base\" },\n { text: truncate(last ?? ` ${cost}`, budget), tone: \"base\" },\n { text: \"\", tone: \"muted\" },\n ]\n}\n\n/**\n * The sidebar history: a compact block per turn — when and through which\n * provider and how long it took, then the prompt volumes, then the cache hit,\n * the rate and the cost.\n *\n * The model gets a line of its own at both ends of the block and on every turn\n * that changed it. The ends matter because the reader cannot tell whether a\n * block is the whole history or a window of a long session: the newest turn\n * names the model in use now, the oldest names the one the window started with,\n * and everything between them is read against the nearest line below it.\n */\nexport function sidebarLines(rows: readonly TurnUsage[], options?: LineFormatOptions & { budget?: number | undefined }): PanelLine[] {\n const budget = options?.budget ?? 34\n const labels = { input: options?.labels?.input ?? \"in\", output: options?.labels?.output ?? \"out\" }\n const lines: PanelLine[] = []\n for (const [index, turn] of rows.entries()) {\n const clock = turn.endAt !== undefined ? formatClock(turn.endAt).slice(0, 5) : \"--:--\"\n const provider = turn.providerID ?? \"unknown\"\n const display = displayTotals(turn.latest)\n const input = formatTokens(display.input)\n const prompt = formatTokens(display.prompt)\n const output = formatTokens(display.output)\n const cost =\n options?.estimates === false\n ? formatCost(turn.totals.cost)\n : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost)\n // The cache hit of the turn, on the same step the numbers come from. One\n // decimal, with a trailing `.0` dropped: the sidebar has no room to spare.\n const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\\.0%$/, \"%\")\n const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps)\n const suffix = turn.drops.length > 0 ? \" · ⚠\" : \"\"\n // Three compact lines: when and through what, for how long, the prompt\n // volumes, then what the turn cost — in tokens per second and in money —\n // and how much of the prompt came from cache. The duration is dropped\n // before the provider when the sidebar is too narrow for both.\n const header = `${clock} ${provider}`\n const timed = turn.durationMs === undefined ? undefined : `${header} · ${formatMs(turn.durationMs)}`\n const volumes = [\n ` ${labels.input} ${input} (${prompt}) · ${labels.output} ${output}`,\n ` ${labels.input} ${input} · ${labels.output} ${output}`,\n ` ${labels.input} ${input}`,\n ]\n const facts = [\n ` hit ${hit}${tps === undefined ? \"\" : ` · ${tps}`} · ${cost}${suffix}`,\n ` hit ${hit}${tps === undefined ? \"\" : ` · ${tps}`}${suffix}`,\n ` ${tps === undefined ? \"\" : `${tps} · `}${cost}${suffix}`,\n ` hit ${hit}${suffix}`,\n ]\n lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? \"warning\" : \"base\" })\n // The model appears at both ends of the block (the newest turn is the state\n // now, the oldest anchors the window) and on every turn that changed it: the\n // provider alone cannot say which model actually ran.\n const edge = index === 0 || index === rows.length - 1\n if (edge || turn.modelChanged || turn.providerChanged) {\n const model = turn.modelID === undefined ? \"unknown\" : `${turn.modelID}${turn.variant === undefined ? \"\" : ` ${turn.variant}`}`\n lines.push({ text: truncate(` ${model}`, budget), tone: \"muted\" })\n }\n lines.push({\n text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1]!, budget),\n tone: \"muted\",\n })\n lines.push({\n text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1]!, budget),\n tone: turn.drops.length > 0 ? \"warning\" : \"muted\",\n })\n }\n if (rows.length === 0) lines.push({ text: \"no finished turns yet\", tone: \"muted\" })\n return lines\n}\n",
15
- "import type { Database } from \"bun:sqlite\"\nimport { formatTokens } from \"./core\"\nimport { clampPanelWidth } from \"./limits\"\nimport {\n cacheDropsOf,\n cachePairs,\n cacheStatsByModel,\n cacheStatsOf,\n coverageOf,\n providerBreakdownOf,\n providerSummaryOf,\n gapReportOf,\n latencyGroupsOf,\n latencyOf,\n periodEnd,\n periodsOf,\n stepRows,\n switchesOf,\n timingRows,\n ttlEvidenceOf,\n type CacheStats,\n type ProviderRow,\n type PairRow,\n type ProviderSummary,\n type Dimension,\n type LatencyGroupRow,\n type SwitchRow,\n} from \"./stats/aggregates\"\nimport {\n buildWhere,\n childSessionIDs,\n modelKey,\n models,\n otherUsageRows,\n overview,\n sessionUsageOf,\n sessions,\n spend,\n STEP_TIME,\n turns,\n type Filters,\n} from \"./stats/queries\"\nimport type { DbInfo } from \"./stats/maintenance\"\nimport {\n cacheLines,\n dbLines,\n formatCount,\n kvGrid,\n latencyLines,\n modelsLines,\n overviewLines,\n periodLines,\n providerSummaryLines,\n providerLines,\n sessionsLines,\n truncate,\n turnsLines,\n type CacheModelRow,\n type Granularity,\n type LineFormatOptions,\n type PanelLine,\n type PanelRow,\n type PanelView,\n type RangeKey,\n} from \"./panel-data\"\n\n/**\n * The panel's data assembly: read the database, run the queries the active view\n * needs and hand plain lines to the renderer. Kept out of the component so\n * every view can be asserted from an in-memory database, exactly as the CLI\n * report renders it.\n */\n\nexport type TurnsScope = \"session\" | \"all\"\n\n/** Everything the panel shows, in one request object. */\nexport type PanelRequest = {\n db: Database\n view: PanelView\n range: RangeKey\n filters: Filters\n granularity: Granularity\n turnsScope: TurnsScope\n sort: string\n sortDesc: boolean\n sessionID: string\n sessionStart: number | undefined\n now: number\n format?: LineFormatOptions | undefined\n /** Drill-down target: when set, the panel shows this detail instead. */\n detail?: PanelRow | undefined\n /** The database view's own state: where the file is and what it holds. */\n database?: DbInfo | undefined\n /** Set when the last vacuum could not take the write lock. */\n busy?: boolean | undefined\n /** `false` hides list-price estimates in every view. */\n estimates?: boolean | undefined\n width: number\n}\n\n/** Sorting options per view; the first is the default. */\nexport function detailLabel(row: PanelRow): string {\n switch (row.kind) {\n case \"model\":\n return `model ${row.variant !== undefined ? `${row.value} ${row.variant}` : row.value}`\n case \"session\":\n case \"turn\":\n return `session ${row.value}`\n case \"period\":\n return `period ${row.value}`\n case \"provider\":\n return `provider ${row.value}`\n case \"prune\":\n return `prune older than ${row.value} days`\n case \"wipe\":\n return \"wipe all recorded usage\"\n }\n}\n\n/** Build the panel lines for the request. Never throws: a failure is a line. */\nexport function buildPanel(request: PanelRequest): PanelLine[] {\n // The service clamps before it asks, but this function is also the report's\n // and the tests' entry point: keep the formatters and the final guard on one\n // width whatever the caller used.\n const width = clampPanelWidth(request.width)\n try {\n // The view formatters fit their tables, but a note or a detail line can\n // still be wider than a very narrow panel. This is the last line of\n // defence: nothing reaches a renderer wider than the width it asked for.\n return build({ ...request, width }).map((line) =>\n line.text.length <= width ? line : { ...line, text: truncate(line.text, width) },\n )\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return [{ text: truncate(`stats query failed: ${message}`, width), tone: \"warning\" }]\n }\n}\n\nfunction build(request: PanelRequest): PanelLine[] {\n const { db, view, now, sessionStart, width } = request\n const estimates = request.estimates !== false\n // The `session` range is the session itself, not \"everything recorded after it\n // started\": siblings and subagents run in that window too.\n const scoped = request.range === \"session\" && request.sessionID !== \"\"\n const range = scoped ? undefined : request.range === \"session\" ? (sessionStart === undefined ? undefined : { from: sessionStart }) : rangeForRequest(request.range, now)\n const filters: Filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters\n if (request.detail !== undefined) return buildDetail(request, range, filters, estimates)\n\n switch (view) {\n case \"overview\": {\n const usage = overview(db, range, filters)\n const sessionUsage =\n request.sessionID === \"\" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID })\n // Subagents are their own sessions; showing them apart explains why the\n // line's `sess` segment (one session) is smaller than the whole family.\n const childIDs = request.sessionID === \"\" ? [] : childSessionIDs(db, request.sessionID)\n const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs)\n return overviewLines(\n {\n usage,\n session: sessionUsage,\n ...(children.length > 0 ? { subagents: children } : {}),\n range: request.range,\n activity: activityOf(db, range, filters, now),\n coverage: coverageOf(db, { range, filters }),\n estimates,\n },\n width,\n )\n }\n case \"models\": {\n const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates)\n // One read of the pairs serves the reuse table and the switch counts.\n const pairs = cachePairs(db, { range, filters })\n const switches = switchesOf(pairs)\n return modelsLines(\n rows,\n width,\n {\n cache: cacheByModel(pairs),\n switches: switchesByModel(switches.rows),\n },\n 40,\n estimates,\n )\n }\n case \"providers\":\n return providerSummaryLines(\n sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates),\n width,\n 40,\n estimates,\n )\n case \"cache\": {\n // One read of the pairs serves the losses, the TTL bounds and the\n // survival buckets: they are three views of the same comparison.\n const pairs = cachePairs(db, { range, filters })\n return cacheLines(\n {\n drops: cacheDropsOf(db, pairs),\n evidence: ttlEvidenceOf(pairs),\n gap: gapReportOf(pairs),\n models: topCacheModels(pairs),\n },\n width,\n )\n }\n case \"periods\": {\n const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters))\n // Summing the per-period distinct session counts counts a session once\n // per period; the total row uses the range's own distinct count.\n const sessions = overview(db, range, filters).sessions\n return periodLines(rows, width, request.granularity, 40, estimates, sessions)\n }\n case \"latency\": {\n // One read of the timings serves the overall block and the group table.\n const timings = timingRows(db, { range, filters })\n const by: Dimension = filters.modelID !== undefined ? \"provider\" : \"model\"\n return latencyLines(\n latencyOf(timings),\n width,\n sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc),\n 14,\n estimates,\n )\n }\n case \"sessions\": {\n const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates)\n const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID))\n return sessionsLines(rows, width, {\n limit: 20,\n estimates,\n rollup: {\n subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),\n subagentCost: child.reduce((sum, row) => sum + row.cost, 0),\n subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0),\n },\n })\n }\n case \"db\":\n // The path and the file's size are the panel's, not the database's: a\n // builder without them says so instead of inventing a location.\n return request.database === undefined\n ? [{ text: \"the database location is unavailable to this panel\", tone: \"warning\" }]\n : dbLines({ info: request.database, busy: request.busy, now, estimates }, width)\n case \"go\":\n // Quotas are live host state, not database rows. The TUI and Desktop\n // render this view from their own client; a direct RPC caller gets an\n // explanation instead of an empty table.\n return [\n {\n text: \"OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.\",\n tone: \"muted\",\n },\n ]\n case \"turns\": {\n const sessionID = request.turnsScope === \"session\" ? request.sessionID : undefined\n const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates)\n const titles =\n request.turnsScope === \"all\"\n ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID]))\n : undefined\n return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles })\n }\n }\n}\n\nfunction rangeForRequest(key: RangeKey, now: number): { from?: number | undefined; to?: number | undefined } | undefined {\n switch (key) {\n case \"today\": {\n const start = new Date(now)\n start.setHours(0, 0, 0, 0)\n return { from: start.getTime() }\n }\n case \"7d\":\n return { from: now - 7 * 24 * 60 * 60 * 1000 }\n case \"30d\":\n return { from: now - 30 * 24 * 60 * 60 * 1000 }\n default:\n return undefined\n }\n}\n\n// ---------------------------------------------------------------------------\n// Detail screens\n// ---------------------------------------------------------------------------\n\nfunction buildDetail(\n request: PanelRequest,\n range: { from?: number | undefined; to?: number | undefined } | undefined,\n filters: Filters,\n estimates: boolean,\n): PanelLine[] {\n const row = request.detail!\n const db = request.db\n const width = request.width\n const head: PanelLine = { text: detailLabel(row), tone: \"accent\" }\n const back: PanelLine = { text: \"backspace returns · the header shows where you came from\", tone: \"muted\" }\n\n if (row.kind === \"model\") {\n // The identity is the model *and* its variant: the variant is a different\n // model for the provider, so it gets its own detail.\n const scoped: Filters = { ...filters, modelKey: modelKey(row.value, row.variant) }\n const stats = cacheStatsOf(db, { range, filters: scoped })\n // One read of the steps serves the provider breakdown and the latency.\n const steps = stepRows(db, { range, filters: scoped })\n return [\n head,\n // One pair per line at a narrow width, two when they fit: the stats head\n // used to be a single 87-column line that a 68-column panel cut.\n ...kvGrid(\n [\n [\"steps\", formatCount(stats.steps)],\n [\"in\", formatTokens(stats.prompt - stats.cached)],\n [\"prompt\", formatTokens(stats.prompt)],\n [\"cached\", formatTokens(stats.cached)],\n [\"write\", formatTokens(stats.cacheWrite)],\n [\"hit\", percent(stats.hit)],\n [\"p50\", percent(stats.hitP50)],\n ],\n width,\n ),\n { text: \"\", tone: \"muted\" },\n ...providerLines(providerBreakdownOf(steps), width, 40, estimates),\n { text: \"\", tone: \"muted\" },\n // One model, so its latency is worth reading per provider: that is what\n // the model's own identity no longer separates.\n ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, \"provider\"), 14, estimates),\n { text: \"\", tone: \"muted\" },\n back,\n ]\n }\n if (row.kind === \"session\" || row.kind === \"turn\") {\n const rows = turns(db, { sessionID: row.value, limit: 80 })\n return [head, { text: \"\", tone: \"muted\" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: \"\", tone: \"muted\" }, back]\n }\n if (row.kind === \"provider\") {\n // A provider detail: every model it served, then its latency.\n const scoped: Filters = { ...filters, provider: row.value }\n // One read of the steps serves the reuse line and the latency block.\n const steps = stepRows(db, { range, filters: scoped })\n const stats = cacheStatsOf(db, { range, filters: scoped })\n return [\n head,\n ...kvGrid(\n [\n [\"steps\", formatCount(stats.steps)],\n [\"in\", formatTokens(stats.prompt - stats.cached)],\n [\"prompt\", formatTokens(stats.prompt)],\n [\"cached\", formatTokens(stats.cached)],\n [\"hit\", percent(stats.hit)],\n [\"p50\", percent(stats.hitP50)],\n ],\n width,\n ),\n { text: \"\", tone: \"muted\" },\n ...providerLines(providerBreakdownOf(steps), width, 40, estimates),\n { text: \"\", tone: \"muted\" },\n ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, \"model\"), 14, estimates),\n { text: \"\", tone: \"muted\" },\n back,\n ]\n }\n if (row.kind === \"period\") {\n // The bucket is one row of the period report: the providers must be the\n // ones of this bucket, not of the whole range the report was built from.\n const periods = periodsOf(stepRows(db, { range, filters }), request.granularity)\n const period = periods.find((entry) => entry.key === row.value)\n // The detail is the intersection of the bucket and the range the report\n // was built for; a period at the edge of a bounded range must not pull in\n // the steps that the range excluded.\n const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at)\n const to =\n period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY)\n const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters })\n return [\n head,\n { text: `${formatCount(period?.steps ?? 0)} steps`, tone: \"muted\" },\n { text: \"\", tone: \"muted\" },\n ...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),\n { text: \"\", tone: \"muted\" },\n back,\n ]\n }\n return [head, back]\n}\n\nfunction percent(value: number | undefined): string {\n return value === undefined ? \"–\" : `${(value * 100).toFixed(1)}%`\n}\n\n// ---------------------------------------------------------------------------\n// Sorting\n// ---------------------------------------------------------------------------\n\nfunction sortModels(rows: ReturnType<typeof models>, sort: string, desc: boolean, estimates = true): ReturnType<typeof models> {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (model: (typeof rows)[number]): number => {\n if (sort === \"cached\") return model.totals.cached\n if (sort === \"hit\") {\n const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite\n return prompt > 0 ? model.totals.cached / prompt : -1\n }\n if (sort === \"out\") return model.totals.output + model.totals.reasoning\n if (sort === \"cost\") return estimates ? spend(model.totals) : model.totals.cost\n return model.totals.steps\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortProviders(rows: readonly ProviderSummary[], sort: string, desc: boolean, estimates = true): ProviderSummary[] {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"cached\") return row.cache.cached\n if (sort === \"hit\") return row.cache.hit ?? -1\n if (sort === \"cost\") return estimates ? spend(row.usage) : row.usage.cost\n if (sort === \"share\") return row.share\n if (sort === \"tps\") return row.tps ?? -1\n return row.usage.steps\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortLatency(rows: readonly LatencyGroupRow[], sort: string, desc: boolean): LatencyGroupRow[] {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"tps\") return row.tps.p50 ?? -1\n if (sort === \"wall\") return row.wall.p50 ?? -1\n return row.count\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortSessions(rows: ReturnType<typeof sessions>, sort: string, desc: boolean, estimates = true): ReturnType<typeof sessions> {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"steps\") return row.steps\n if (sort === \"cached\") return row.cached\n if (sort === \"cost\") return estimates ? spend(row) : row.cost\n return row.lastAt ?? 0\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortTurns(rows: ReturnType<typeof turns>, sort: string, desc: boolean, estimates = true): ReturnType<typeof turns> {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"cost\") return estimates ? spend(row.totals) : row.totals.cost\n if (sort === \"tokens\") return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning\n return row.endAt ?? 0\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\n// ---------------------------------------------------------------------------\n// Small derived series\n// ---------------------------------------------------------------------------\n\n/** Token reuse per model, for the models view and the cache view. */\nexport function cacheByModel(pairs: readonly PairRow[]): Map<string, CacheStats> {\n const map = new Map<string, CacheStats>()\n for (const row of cacheStatsByModel(pairs)) {\n map.set(modelKey(row.modelID, row.variant), row.cache)\n }\n return map\n}\n\n/** The switch summary per `modelKey`, as the models view reads it. */\nexport function switchesByModel(rows: readonly SwitchRow[]): Map<string, SwitchRow> {\n return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]))\n}\n\n/** The cache table of the cache view: the models holding the most cache. */\nfunction topCacheModels(pairs: readonly PairRow[]): CacheModelRow[] {\n return cacheStatsByModel(pairs)\n .slice(0, 10)\n .map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }))\n}\n\n/**\n * Steps per bucket for the overview sparkline. The bucket size is chosen so a\n * range reads as roughly 48 bars, and always from a fixed ladder so the axis is\n * stable between refreshes.\n */\nfunction activityOf(\n db: Database,\n range: { from?: number | undefined; to?: number | undefined } | undefined,\n filters: Filters | undefined,\n now: number,\n): number[] {\n // The sparkline is part of the filtered overview: a session or model view\n // must not draw the activity of every other session. The range and filters\n // are the same ones the step aggregates use.\n const filter = buildWhere(range, filters, STEP_TIME)\n // All time has no lower bound: span the filtered window instead of starting\n // at the epoch, or the sparkline would be one bar of data and 46 of nothing.\n const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params) as {\n at: number | null\n } | null\n const from = range?.from ?? earliest?.at ?? 0\n const to = range?.to ?? now\n const span = Math.max(1, to - from)\n const ladder = [3_600_000, 3 * 3_600_000, 6 * 3_600_000, 12 * 3_600_000, 86_400_000, 3 * 86_400_000, 7 * 86_400_000, 30 * 86_400_000]\n const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1]!\n const rows = db\n .query(\n `SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps\n FROM steps ${filter.where}\n GROUP BY bucket ORDER BY bucket`,\n )\n .all(bucket, ...filter.params) as { bucket: number; steps: number }[]\n if (rows.length === 0) return []\n const first = Math.floor(from / bucket)\n const last = rows[rows.length - 1]!.bucket\n const series: number[] = []\n for (let index = first; index <= last; index += 1) {\n series.push(rows.find((row) => row.bucket === index)?.steps ?? 0)\n }\n return series\n}\n",
19
+ "import {\n DEFAULT_FIELDS,\n DEFAULT_LABELS,\n displayTotals,\n formatClock,\n formatCost,\n formatDuration,\n formatLine,\n formatMoney,\n formatSpend,\n formatTokens,\n type LineFields,\n type LineLabels,\n type TurnStats,\n type TurnTotalsView,\n} from \"./core\"\nimport type { LatencyReport, ModelUsage, Overview, Range, SessionUsage, TurnUsage } from \"./stats/queries\"\nimport type { CacheDropRow, TtlEvidenceRow } from \"./stats/aggregates\"\nimport type { DbInfo } from \"./stats/maintenance\"\nimport type {\n CacheStats,\n CoverageReport,\n ProviderRow,\n ProviderSummary,\n GapReport,\n LatencyGroupRow,\n PeriodGranularity,\n PeriodRow,\n SwitchRow,\n} from \"./stats/aggregates\"\nimport { modelKey } from \"./stats/queries\"\nimport { sanitizeText } from \"./text\"\nimport {\n DEFAULT_QUOTA_NAME,\n QUOTA_VIEW,\n formatCountdown,\n formatRenewal,\n formatRenewalCompact,\n forecastMonthly,\n quotaBar,\n quotaStatus,\n type GoMeter,\n type QuotaFetch,\n} from \"./quota\"\n\n/**\n * View models and formatting for the stats panel. Everything here is pure:\n * the panel component feeds query results in and renders the lines out, which\n * keeps the layout testable without a terminal. Lines may carry a `row`, the\n * identity the cursor selects and Enter drills into.\n */\n\nexport const PANEL_NAME = \"usage-insights\"\n\nexport const PANEL_VIEWS = [\"overview\", \"models\", \"providers\", \"cache\", \"periods\", \"latency\", \"sessions\", \"turns\", \"db\"] as const\n/**\n * The panel catalogue seen by the TUI and the Desktop. `go` is client-side\n * because the server part cannot reach the host's usage-limits endpoint; the\n * database-backed views stay in `PANEL_VIEWS`.\n */\nexport const CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW] as const\nexport type PanelView = (typeof PANEL_VIEWS)[number] | typeof QUOTA_VIEW\n\nexport const RANGE_KEYS = [\"session\", \"today\", \"7d\", \"30d\", \"all\"] as const\nexport type RangeKey = (typeof RANGE_KEYS)[number]\n\nexport const GRANULARITIES = [\"day\", \"week\", \"month\"] as const\nexport type Granularity = (typeof GRANULARITIES)[number]\n\nexport type PanelTone = \"base\" | \"muted\" | \"warning\" | \"accent\"\n\n/** What a selectable line stands for; Enter drills into it. */\nexport type PanelRow = {\n kind: \"model\" | \"session\" | \"period\" | \"provider\" | \"turn\" | \"prune\" | \"wipe\"\n value: string\n variant?: string | undefined\n}\n\nexport type PanelLine = {\n text: string\n tone?: PanelTone\n row?: PanelRow | undefined\n /** TUI-only key hint; the desktop GUI filters these lines out. */\n hint?: boolean | undefined\n}\n\n/** Sorting options per view; the first is the default. */\nexport const SORT_KEYS: Partial<Record<PanelView, readonly string[]>> = {\n models: [\"steps\", \"cached\", \"hit\", \"out\", \"cost\"],\n providers: [\"steps\", \"cached\", \"hit\", \"cost\", \"share\", \"tps\", \"ttft\"],\n latency: [\"n\", \"tps\", \"ttft\", \"wall\"],\n sessions: [\"last\", \"steps\", \"cached\", \"cost\"],\n turns: [\"time\", \"cost\", \"tokens\"],\n}\n\nexport function sortKeys(view: PanelView): readonly string[] {\n return SORT_KEYS[view] ?? []\n}\n\nexport function defaultSort(view: PanelView): string {\n return sortKeys(view)[0] ?? \"\"\n}\n\n/**\n * The Desktop view menu places Go immediately after Overview, because it is\n * live host state rather than a database report. The TUI keeps its numeric\n * key order (9 is db, 0 is go); only the Desktop dropdown uses this order.\n */\nexport function desktopViewOrder(views: readonly PanelView[]): readonly PanelView[] {\n const go = views.indexOf(QUOTA_VIEW)\n if (go === -1) return views\n const withoutGo = views.filter((view) => view !== QUOTA_VIEW)\n const overview = withoutGo.indexOf(\"overview\")\n const at = overview === -1 ? 0 : overview + 1\n return [...withoutGo.slice(0, at), QUOTA_VIEW, ...withoutGo.slice(at)]\n}\n\nexport function nextSort(view: PanelView, current: string, step: number): string {\n const keys = sortKeys(view)\n if (keys.length === 0) return current\n const index = keys.indexOf(current)\n if (index === -1) return keys[0]!\n return keys[(index + step + keys.length) % keys.length]!\n}\n\n/** The views and ranges, as the command and the panel header understand them. */\nexport function parseArgs(input: string | undefined, views: readonly PanelView[] = CLIENT_VIEWS): { view?: PanelView; range?: RangeKey } {\n const parsed: { view?: PanelView; range?: RangeKey } = {}\n for (const token of (input ?? \"\").split(/\\s+/)) {\n const value = token.trim().toLowerCase()\n if (value === \"\") continue\n if ((views as readonly string[]).includes(value)) parsed.view = value as PanelView\n else if ((RANGE_KEYS as readonly string[]).includes(value)) parsed.range = value as RangeKey\n }\n return parsed\n}\n\nexport function rangeFor(key: RangeKey, now: number, sessionStart?: number | undefined): Range | undefined {\n switch (key) {\n case \"session\":\n return sessionStart === undefined ? undefined : { from: sessionStart }\n case \"today\": {\n const start = new Date(now)\n start.setHours(0, 0, 0, 0)\n return { from: start.getTime() }\n }\n case \"7d\":\n return { from: now - 7 * 24 * 60 * 60 * 1000 }\n case \"30d\":\n return { from: now - 30 * 24 * 60 * 60 * 1000 }\n case \"all\":\n return undefined\n }\n}\n\nexport function rangeLabel(key: RangeKey): string {\n switch (key) {\n case \"session\":\n return \"this session\"\n case \"today\":\n return \"today\"\n case \"7d\":\n return \"7 days\"\n case \"30d\":\n return \"30 days\"\n case \"all\":\n return \"all time\"\n }\n}\n\nexport function nextIn<Value>(values: readonly Value[], current: Value, step: number): Value {\n const index = values.indexOf(current)\n if (index === -1) return values[0]!\n return values[(index + step + values.length) % values.length]!\n}\n\n/** Which turns the `turns` view lists: the open session, or every session. */\nexport type TurnsScope = \"session\" | \"all\"\n\n/**\n * Everything the panel remembers between openings. Stored through the host's\n * durable storage, so the panel reopens where the user left it.\n */\nexport type PanelSettings = {\n view: PanelView\n range: RangeKey\n sort: string\n sortDesc: boolean\n granularity: Granularity\n turnsScope: TurnsScope\n /** Empty string means \"no filter\". */\n modelID: string\n /** The provider the model ran through. */\n providerID: string\n}\n\nexport const DEFAULT_SETTINGS: PanelSettings = {\n view: \"overview\",\n range: \"all\",\n sort: \"\",\n sortDesc: true,\n granularity: \"day\",\n turnsScope: \"session\",\n modelID: \"\",\n providerID: \"\",\n}\n\n/** Merge persisted state with the defaults, dropping anything unrecognized. */\nexport function sanitizeSettings(\n raw: Partial<PanelSettings> | undefined,\n views: readonly PanelView[] = CLIENT_VIEWS,\n): PanelSettings {\n const settings = { ...DEFAULT_SETTINGS, ...(raw ?? {}) }\n return {\n view: (views as readonly string[]).includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,\n range: (RANGE_KEYS as readonly string[]).includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,\n sort: typeof settings.sort === \"string\" ? settings.sort : DEFAULT_SETTINGS.sort,\n sortDesc: settings.sortDesc === true,\n granularity: (GRANULARITIES as readonly string[]).includes(settings.granularity) ? settings.granularity : DEFAULT_SETTINGS.granularity,\n turnsScope: settings.turnsScope === \"all\" ? \"all\" : \"session\",\n modelID: typeof settings.modelID === \"string\" ? settings.modelID : \"\",\n providerID: typeof settings.providerID === \"string\" ? settings.providerID : \"\",\n }\n}\n\n// ---------------------------------------------------------------------------\n// Primitive formatting\n// ---------------------------------------------------------------------------\n\nexport function formatPercent(value: number | undefined, digits = 1): string {\n if (value === undefined || !Number.isFinite(value)) return \"–\"\n return `${(value * 100).toFixed(digits)}%`\n}\n\nexport function formatCount(value: number): string {\n return Number.isFinite(value) ? Math.round(value).toLocaleString(\"en-US\") : \"–\"\n}\n\nexport function formatMs(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value)) return \"–\"\n const ms = Math.max(0, value)\n if (ms < 1_000) return `${Math.round(ms)}ms`\n if (ms < 60_000) return `${(ms / 1_000).toFixed(1)}s`\n return formatDuration(ms)\n}\n\nexport function formatTps(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value) || value < 0) return \"–\"\n return `${value.toFixed(1)}/s`\n}\n\n/** A rate that has to fit a sidebar: whole numbers from 10 up. */\nexport function formatTpsCompact(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value) || value < 0) return \"–\"\n return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`\n}\n\n/**\n * A bare rate for a line that supplies its own `tps`/`rtps` label. Adding the\n * unit twice (`50/s tps`) is the easy mistake; this formatter exists so no\n * caller has to remember which one carries it.\n */\nexport function formatRateValue(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value) || value < 0) return \"–\"\n return value >= 10 ? String(Math.round(value)) : value.toFixed(1)\n}\n\n/** Idle gaps are read at a glance: seconds, minutes, hours, days. */\nexport function formatGap(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value)) return \"–\"\n const gap = Math.max(0, value)\n if (gap < 60_000) return `${Math.round(gap / 1_000)}s`\n if (gap < 3_600_000) return `${Math.round(gap / 60_000)}m`\n if (gap < 86_400_000) return `${(gap / 3_600_000).toFixed(1)}h`\n return `${(gap / 86_400_000).toFixed(1)}d`\n}\n\n/** Cut a value to the width, dropping control characters first. */\nexport function truncate(value: string, width: number): string {\n if (width <= 1) return \"\"\n const clean = sanitizeText(value)\n if (clean.length <= width) return clean\n return `${clean.slice(0, width - 1).trimEnd()}…`\n}\n\n/** Keep both ends of a long id: the family reads first, the `#variant` last. */\nexport function truncateMiddle(value: string, width: number): string {\n if (width <= 1) return \"\"\n const clean = sanitizeText(value)\n if (clean.length <= width) return clean\n const head = Math.ceil((width - 1) / 2)\n const tail = width - 1 - head\n return `${clean.slice(0, head)}…${clean.slice(clean.length - tail)}`\n}\n\n/**\n * A model cell keeps the variant visible: two rows of the same family must not\n * read alike after truncation.\n */\nexport function modelCell(modelID: string, variant: string | undefined, width: number): string {\n return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width)\n}\n\nexport function padCell(value: string, width: number, align: \"left\" | \"right\" = \"left\"): string {\n if (value.length >= width) return value\n const padding = \" \".repeat(width - value.length)\n return align === \"right\" ? `${padding}${value}` : `${value}${padding}`\n}\n\nexport function formatTableRow(cells: readonly string[], widths: readonly number[], aligns?: readonly (\"left\" | \"right\")[]): string {\n const parts: string[] = []\n for (let index = 0; index < cells.length; index += 1) {\n const width = widths[index] ?? 8\n const align = aligns?.[index] ?? \"left\"\n parts.push(padCell(truncate(cells[index] ?? \"\", width), width, align))\n }\n return parts.join(\" \")\n}\n\n/**\n * One column in a table that has to fit a panel width. `width` is the compact\n * width (and the fixed width when `max` is omitted); `max` is the widest it may\n * grow into leftover space; optional columns carry a priority and are added\n * only when they fit. `reserve` keeps the space an optional column would\n * otherwise take from the text column before it (a model name, a provider).\n */\nexport type TableColumnFit = {\n width: number\n max?: number | undefined\n priority?: number | undefined\n reserve?: number | undefined\n}\n\nexport type FittedWidth = {\n index: number\n width: number\n}\n\n/**\n * Fit a table's columns into the panel width. Required columns are kept,\n * optional ones are added in priority order while they fit, and the leftover\n * goes to the columns in display order, each up to its maximum. Dropped\n * columns are absent from the result, so a caller never renders a zero-width\n * cell. The growth order is the display order: the text column is first.\n */\nexport function fitTableColumns(columns: readonly TableColumnFit[], width: number): FittedWidth[] {\n const chosen = new Set<number>()\n for (let index = 0; index < columns.length; index += 1) {\n if (columns[index]!.priority === undefined) chosen.add(index)\n }\n if (chosen.size === 0) return []\n const total = (): number => {\n let sum = chosen.size - 1\n for (const index of chosen) sum += columns[index]!.width\n return sum\n }\n const optional = columns\n .map((column, index) => ({ column, index }))\n .filter((entry) => entry.column.priority !== undefined)\n .sort((left, right) => left.column.priority! - right.column.priority! || left.index - right.index)\n for (const { column, index } of optional) {\n if (total() + column.width + 1 + (column.reserve ?? 0) <= width) chosen.add(index)\n }\n // A panel narrower than the required set drops its trailing columns. Every\n // formatter orders the least important required column last for this case.\n while (chosen.size > 1 && total() > width) chosen.delete(Math.max(...chosen))\n const widths = new Map<number, number>()\n let room = width - total()\n for (let index = 0; index < columns.length && room > 0; index += 1) {\n if (!chosen.has(index)) continue\n const column = columns[index]!\n const grow = Math.min(room, (column.max ?? column.width) - column.width)\n if (grow <= 0) continue\n widths.set(index, column.width + grow)\n room -= grow\n }\n return [...chosen]\n .sort((left, right) => left - right)\n .map((index) => ({ index, width: widths.get(index) ?? columns[index]!.width }))\n}\n\n/** A fitted column ready to render: header, final width, alignment and cell. */\nexport type FittedTableColumn<Row> = {\n /** The column's position in the input, so callers can find a special one. */\n index: number\n header: string\n width: number\n align: \"left\" | \"right\"\n cell: (row: Row) => string\n}\n\nexport function fitTable<Row>(\n columns: readonly (TableColumnFit & {\n header: string\n align?: \"left\" | \"right\" | undefined\n cell: (row: Row) => string\n })[],\n width: number,\n): FittedTableColumn<Row>[] {\n return fitTableColumns(columns, width).map(({ index, width: fitted }) => {\n const column = columns[index]!\n return { index, header: column.header, width: fitted, align: column.align ?? \"left\", cell: column.cell }\n })\n}\n\n\nexport function count(n: number, singular: string, plural = `${singular}s`): string {\n return `${formatCount(n)} ${n === 1 ? singular : plural}`\n}\n\n/** Two label/value pairs per row, collapsed to one pair on narrow panels. */\nexport function kvGrid(pairs: readonly (readonly [string, string])[], width: number): PanelLine[] {\n const lines: PanelLine[] = []\n const label = 11\n const column = Math.floor(width / 2)\n // A pair that cannot fit on one line keeps its label and moves the value to\n // its own indented line. The coverage window is the long one: splitting it\n // preserves the whole range instead of cutting the end date.\n const pairLines = (pair: readonly [string, string]): string[] => {\n const text = `${padCell(pair[0], label)}${pair[1]}`\n if (text.length <= width) return [text]\n return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width))\n }\n for (let index = 0; index < pairs.length; index += 2) {\n const left = pairs[index]!\n const right = pairs[index + 1]\n if (right === undefined) {\n for (const text of pairLines(left)) lines.push({ text, tone: \"base\" })\n continue\n }\n const leftText = `${padCell(left[0], label)}${left[1]}`\n const rightText = `${padCell(right[0], label)}${right[1]}`\n // Both columns have to fit the requested width: the value on the right may\n // be wider than half the panel (the coverage window dates are), and a line\n // that overflows wraps in the terminal instead of ending.\n const gap = Math.max(2, column - leftText.length)\n if (leftText.length + gap + rightText.length <= width) {\n lines.push({ text: `${leftText}${\" \".repeat(gap)}${rightText}`, tone: \"base\" })\n } else {\n for (const text of pairLines(left)) lines.push({ text, tone: \"base\" })\n for (const text of pairLines(right)) lines.push({ text, tone: \"base\" })\n }\n }\n return lines\n}\n\nconst HEADER_TONE: PanelTone = \"accent\"\nconst SPARK = [\"▁\", \"▂\", \"▃\", \"▄\", \"▅\", \"▆\", \"▇\", \"█\"] as const\n\n/** Fold a series into at most `maxBars` summed buckets, so a sparkline stays a line. */\nexport function reduceSeries(values: readonly number[], maxBars = 48): number[] {\n if (values.length <= maxBars) return [...values]\n const group = Math.ceil(values.length / maxBars)\n const reduced: number[] = []\n for (let index = 0; index < values.length; index += group) {\n reduced.push(values.slice(index, index + group).reduce((sum, value) => sum + value, 0))\n }\n return reduced\n}\n\n/** Text sparkline: trends at a glance without a chart renderable. */\nexport function sparkline(values: readonly number[], maxBars = 48): string {\n if (values.length === 0) return \"\"\n const series = reduceSeries(values, maxBars)\n const max = Math.max(...series)\n if (max <= 0) return SPARK[0]!.repeat(series.length)\n return series.map((value) => SPARK[Math.min(SPARK.length - 1, Math.max(0, Math.round((value / max) * (SPARK.length - 1))))]!).join(\"\")\n}\n\n/**\n * The live line's buckets, so every aggregate the panel shows reconciles with\n * it: `in` is the uncached prompt (fresh input *and* cache writes), `prompt` is\n * what the provider saw, `out` is everything generated (visible *and*\n * reasoning). `write` and `reasoning` are the parts of `in` and `out`.\n */\nexport type UsageBuckets = {\n steps: number\n input: number\n prompt: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n listCost: number\n hit: number | undefined\n}\n\nexport function usageBuckets(usage: {\n steps: number\n input: number\n cached: number\n cacheWrite: number\n output: number\n reasoning: number\n cost: number\n listCost?: number | undefined\n}): UsageBuckets {\n const prompt = usage.input + usage.cached + usage.cacheWrite\n return {\n steps: usage.steps,\n input: prompt - usage.cached,\n prompt,\n cached: usage.cached,\n cacheWrite: usage.cacheWrite,\n output: usage.output + usage.reasoning,\n reasoning: usage.reasoning,\n cost: usage.cost,\n listCost: usage.listCost ?? 0,\n hit: prompt > 0 ? usage.cached / prompt : undefined,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Chrome shared by every view\n// ---------------------------------------------------------------------------\n\n/**\n * The view tabs. The active one is bracketed so a single tone still reads\n * clearly; on a narrow panel the names shorten instead of wrapping, and the\n * active view always keeps its full name.\n */\nexport function viewBar(view: PanelView, width = 200, views: readonly PanelView[] = CLIENT_VIEWS): PanelLine {\n // Ten client views, ten digits: `0` is the tenth.\n const key = (index: number) => String((index + 1) % 10)\n const full = views.map((name, index) => (name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`))\n const candidates = [full, views.map((name, index) => (name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`))]\n for (const parts of candidates) {\n const text = parts.join(\" \")\n if (text.length <= width) return { text, tone: \"muted\" }\n }\n const index = views.indexOf(view)\n return { text: `[${index === -1 ? \"?\" : key(index)} ${view}] · 1-9 0 or [ ] to switch`, tone: \"muted\" }\n}\n\nexport function keysFor(of: PanelView, range?: RangeKey): string {\n if (of === QUOTA_VIEW) return \"r refresh · t range · 0 view · ? help · the quotas come from OpenCode Go\"\n if (of === \"db\") return \"↑↓ pick a retention · enter prune · the last row wipes · e backfill · v vacuum · r refresh · 1-9 0 view · ? help\"\n if (of === \"periods\") return \"↑↓ move · enter drill · b bucket · t range · m/p filter · x clear · 1-9 0 view · ? help\"\n if (of === \"turns\") {\n return range === \"session\"\n ? \"↑↓ move · t range · m/p filter · x clear · 1-9 0 view · ? help\"\n : \"↑↓ move · a scope · t range · m/p filter · x clear · 1-9 0 view · ? help\"\n }\n return \"↑↓ move · enter drill · s sort · t range · m/p filter · x clear · 1-9 0 view · ? help\"\n}\n\nexport function filterSummary(filters: { modelID?: string | undefined; providerID?: string | undefined }): string | undefined {\n const parts: string[] = []\n if (filters.modelID !== undefined && filters.modelID !== \"\") parts.push(`model=${filters.modelID}`)\n if (filters.providerID !== undefined && filters.providerID !== \"\") parts.push(`provider=${filters.providerID}`)\n return parts.length > 0 ? parts.join(\" · \") : undefined\n}\n\nexport function granularityLabel(granularity: PeriodGranularity): string {\n return granularity === \"day\" ? \"per day\" : granularity === \"week\" ? \"per week\" : \"per month\"\n}\n\n/** Help overlay: the keys and the exact meaning of every number. */\nexport function helpLines(width: number): PanelLine[] {\n const lines: PanelLine[] = [\n { text: \"keys\", tone: HEADER_TONE },\n { text: \" ↑ ↓ j k move the cursor · enter drills in · backspace goes back\" },\n { text: \" 1-9 0 [ ] choose a view · cycle views (9 is db, 0 is go)\" },\n { text: \" t shift+t previous / next range\" },\n { text: \" s shift+s cycle sort column · reverse\" },\n { text: \" b periods bucket: day → week → month\" },\n { text: \" a turns scope: this session ↔ all sessions (time ranges)\" },\n { text: \" m p filter by model / provider (x clears)\" },\n { text: \" r re-read the database · f full screen · escape close\" },\n { text: \" e db: backfill list-price estimates for the $0 steps\" },\n { text: \"\" },\n { text: \"go quota · the host's OpenCode Go allowance\", tone: HEADER_TONE },\n { text: \" rolling the 5-hour window · weekly · monthly\" },\n { text: \" forecast the monthly percentage at its reset, from the\" },\n { text: \" cycle's average pace (not a sample history)\" },\n { text: \" renews the monthly reset reported by the host\" },\n { text: \" the plugin reads the host's local usage-limits endpoint;\" },\n { text: \" it never reads your API key and never talks to the Console.\" },\n { text: \"numbers · the same buckets as the live line\", tone: HEADER_TONE },\n { text: \" prompt everything the provider saw: cached + fresh + writes\" },\n { text: \" in the uncached part: fresh input + cache writes\" },\n { text: \" cached prompt read from the provider prompt cache\" },\n { text: \" write part of `in`: prompt written into that cache\" },\n { text: \" hit cached / prompt, weighted over the selection\" },\n { text: \" hit p50 median of the per-step hit: spots a split pattern\" },\n { text: \" out everything generated: visible output + reasoning\" },\n { text: \" reasoning part of `out`\" },\n { text: \" cost money, not tokens: a turn sums every step; $0 is left out\" },\n { text: \" other compaction/title usage: money with no assistant step;\" },\n { text: \" overview, periods and sessions include it; model rows do not\" },\n { text: \" ≈ list-price estimate for steps the host reported as $0;\" },\n { text: \" `$0.12 + ≈ $3.40` keeps charged and estimated money apart\" },\n { text: \" wall request → completed step · stream request → last chunk\" },\n { text: \" ttft request → first streamed token\" },\n { text: \" tps output+reasoning / first token → last chunk (OpenCode)\" },\n { text: \" rtps output+reasoning / request → last chunk (includes TTFT)\" },\n { text: \" turn 200 tps · 2.1s ttft · cost\" },\n { text: \" session 200 tps · 167 rtps · ttft p50 · cost\" },\n { text: \" switches how often a step's model or provider differs from the step\" },\n { text: \" before it in the same session (the models view's detail), with\" },\n { text: \" the cache a provider switch cost\" },\n { text: \"\" },\n { text: \"identity\", tone: HEADER_TONE },\n { text: \" provider the provider the model ran through, as OpenCode is configured\" },\n { text: \" (opencode, opencode-go, deepseek, …). A gateway may re-route\" },\n { text: \" a request, but the upstream that ran the inference is not\" },\n { text: \" observable, so the provider is the identity every view shows.\" },\n { text: \"\" },\n { text: \"database\", tone: HEADER_TONE },\n { text: \" the db view shows where the file lives, what it holds and how much\" },\n { text: \" of it is old: ↑↓ pick a retention or wipe, enter asks before it\" },\n { text: \" deletes, e backfills list estimates, v gives the space back\" },\n { text: \" local time · SQLite in the OpenCode state directory\" },\n ]\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n}\n\n// ---------------------------------------------------------------------------\n// OpenCode Go quota\n// ---------------------------------------------------------------------------\n\nfunction quotaMeterLine(label: string, meter: GoMeter, now: number): PanelLine {\n const state = meter.limited || meter.percent >= 100 ? \"rate-limited\" : `${Math.round(meter.percent)}% used`\n const countdown = formatCountdown(meter.resetsAt, now)\n return {\n text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} · ${countdown === \"due\" ? \"resets due\" : `resets in ${countdown}`}`,\n tone: meter.limited || meter.percent >= 100 ? \"warning\" : \"base\",\n }\n}\n\n/** The full `go` view: the three meters, the monthly forecast and renewal. */\nexport function goQuotaLines(\n state: QuotaFetch | undefined,\n options: { now: number; width: number; name?: string | undefined; loading?: boolean | undefined; error?: string | undefined },\n): PanelLine[] {\n const { now, width, loading, error } = options\n const name = options.name?.trim() || DEFAULT_QUOTA_NAME\n const lines: PanelLine[] = []\n const push = (text: string, tone: PanelTone = \"base\"): void => {\n lines.push({ text, tone })\n }\n\n if (state === undefined) {\n if (error !== undefined && error !== \"\") push(`Go quota unavailable: ${error}`, \"warning\")\n else if (loading === true) push(\"reading OpenCode Go quota…\", \"muted\")\n else push(\"OpenCode Go quota is unavailable\", \"muted\")\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n }\n\n if (state.kind === \"none\") {\n push(name, \"accent\")\n push(\n state.reason === \"console\"\n ? \"Connect OpenCode Console with /connect to see your Go allowance.\"\n : \"This workspace has no active OpenCode Go subscription.\",\n \"muted\",\n )\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n }\n\n const quota = state.quota\n const workspace = quota.workspace?.name ?? quota.workspace?.id ?? \"workspace\"\n const status = quotaStatus(quota)\n const forecast = forecastMonthly(quota.monthly, now)\n\n push(`${name} · ${workspace}`, \"accent\")\n push(`status ${status}`, status === \"active\" ? \"base\" : \"warning\")\n // The three meters keep their own line; the helper carries the tone.\n lines.push(quotaMeterLine(\"rolling\", quota.rolling, now))\n lines.push(quotaMeterLine(\"weekly\", quota.weekly, now))\n lines.push(quotaMeterLine(\"monthly\", quota.monthly, now))\n push(\"\")\n\n if (forecast.reached || quota.monthly.limited) {\n push(`forecast monthly limit reached · renews ${formatRenewal(quota.monthly.resetsAt)}`, \"warning\")\n } else if (now >= forecast.endAt) {\n push(\"forecast monthly reset due · refresh\", \"warning\")\n } else if (!forecast.available) {\n push(\"forecast too early in the cycle to project a monthly pace\", \"muted\")\n } else if (quota.monthly.percent === 0) {\n push(\"forecast no monthly usage yet this cycle\", \"muted\")\n } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {\n push(\n `forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} · ${formatDuration(\n forecast.exhaustAt - now,\n )} from now · ${forecast.ratePerDay.toFixed(1)}%/day`,\n \"warning\",\n )\n } else {\n const projected = Math.min(999, Math.round(forecast.projectedPercent))\n const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent))\n push(`forecast ~${projected}% at reset · ${headroom}% headroom · ${forecast.ratePerDay.toFixed(1)}%/day`)\n }\n\n const renewal = formatRenewal(quota.monthly.resetsAt)\n const countdown = formatCountdown(quota.monthly.resetsAt, now)\n push(`renews ${renewal} · ${countdown === \"due\" ? \"renewal due\" : `in ${countdown}`}`, \"muted\")\n if (quota.workspace?.usageURL !== undefined) push(`console ${quota.workspace.usageURL}`, \"muted\")\n const age = Math.max(0, now - quota.observedAt)\n push(`updated ${age < 1_000 ? \"just now\" : `${formatDuration(age)} ago`}`, \"muted\")\n if (loading === true) push(\"refreshing…\", \"muted\")\n if (error !== undefined && error !== \"\") push(`quota refresh failed: ${error}`, \"warning\")\n\n return lines.map((line) => ({ ...line, text: truncate(line.text, width) }))\n}\n\n/** The compact block the TUI sidebar and Desktop Turns panel show before the session summary. */\nexport function goSidebarLines(\n state: QuotaFetch | undefined,\n now: number,\n width: number,\n name = DEFAULT_QUOTA_NAME,\n): PanelLine[] {\n if (state?.kind !== \"ok\" || width <= 0) return []\n const quota = state.quota\n const status = quotaStatus(quota)\n const forecast = forecastMonthly(quota.monthly, now)\n const base = `5h ${Math.round(quota.rolling.percent)}% · week ${Math.round(\n quota.weekly.percent,\n )}% · month ${Math.round(quota.monthly.percent)}%`\n const baseTone: PanelTone = status !== \"active\" || quota.monthly.percent >= 80 ? \"warning\" : \"base\"\n let forecastText = \"forecast too early\"\n let forecastTone: PanelTone = \"muted\"\n if (forecast.reached || quota.monthly.limited) {\n forecastText = \"monthly limit reached\"\n forecastTone = \"warning\"\n } else if (forecast.willExhaust) {\n forecastText = \"limit before renewal\"\n forecastTone = \"warning\"\n } else if (forecast.available && quota.monthly.percent > 0) {\n forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`\n } else if (forecast.available && quota.monthly.percent === 0) {\n forecastText = \"forecast no usage yet\"\n }\n return [\n { text: truncate(name, width), tone: \"accent\" },\n { text: truncate(base, width), tone: baseTone },\n { text: truncate(forecastText, width), tone: forecastTone },\n { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: \"muted\" },\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Overview\n// ---------------------------------------------------------------------------\n\nfunction usagePairs(usage: Overview | SessionUsage | undefined, estimates = true): (readonly [string, string])[] {\n if (usage === undefined) return []\n const buckets = usageBuckets(usage)\n const pairs: (readonly [string, string])[] = [\n [\"steps\", formatCount(buckets.steps)],\n [\"in\", formatTokens(buckets.input)],\n [\"prompt\", formatTokens(buckets.prompt)],\n [\"cached\", formatTokens(buckets.cached)],\n [\"hit\", formatPercent(buckets.hit)],\n [\"out\", formatTokens(buckets.output)],\n [\"write\", formatTokens(buckets.cacheWrite)],\n ]\n if (buckets.reasoning > 0) pairs.push([\"reasoning\", formatTokens(buckets.reasoning)])\n // The selection's rates, the same numbers the sidebar's session block shows:\n // `tps` is OpenCode's decode rate, `rtps` the request rate (includes TTFT).\n if (\"tps\" in usage && usage.tps !== undefined) pairs.push([\"tps\", formatTps(usage.tps)])\n if (\"requestTps\" in usage && usage.requestTps !== undefined) pairs.push([\"rtps\", formatTps(usage.requestTps)])\n if (\"ttft\" in usage && usage.ttft !== undefined) pairs.push([\"ttft p50\", formatMs(usage.ttft)])\n pairs.push([\"cost\", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)])\n // The cost total includes compaction and title generations, which have no\n // step of their own. The row keeps that part visible instead of hiding it in\n // a total the step views cannot explain.\n const other = usage.otherCost ?? 0\n if (other > 0) pairs.push([\"other\", `${formatCost(other)} comp/title`])\n return pairs\n}\n\nexport function overviewLines(\n data: {\n usage: Overview\n session: Overview | undefined\n /** Child sessions of the open session, when it has any. */\n subagents?: readonly SessionUsage[] | undefined\n range: RangeKey\n activity?: readonly number[] | undefined\n coverage?: CoverageReport | undefined\n /** `false` hides list-price estimates. */\n estimates?: boolean | undefined\n },\n width: number,\n): PanelLine[] {\n const lines: PanelLine[] = []\n const estimates = data.estimates !== false\n lines.push({\n text: truncate(\n `${rangeLabel(data.range)} · ${count(data.usage.steps, \"step\")} · ${count(data.usage.sessions, \"session\")} · ${count(data.usage.prompts, \"prompt\")}`,\n width,\n ),\n tone: \"muted\",\n })\n lines.push(...kvGrid(buildOverviewPairs(data.usage, \"all\", estimates), width))\n if (data.activity !== undefined && data.activity.length > 1) {\n const suffix = ` ${count(data.activity.length, \"bucket\")}`\n const bars = Math.max(4, width - \"activity \".length - suffix.length)\n const series = reduceSeries(data.activity, bars)\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: \"muted\" })\n }\n if (data.session !== undefined) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"this session\", tone: HEADER_TONE })\n lines.push(...kvGrid(buildOverviewPairs(data.session, \"session\", estimates), width))\n if (data.subagents !== undefined && data.subagents.length > 0) {\n const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0)\n const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0)\n const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0)\n lines.push({\n text: truncate(\n ` subagents ${count(data.subagents.length, \"session\")} · ${count(steps, \"step\")} · ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,\n width,\n ),\n tone: \"muted\",\n })\n }\n }\n if (data.coverage !== undefined) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"data coverage\", tone: HEADER_TONE })\n lines.push(...kvGrid(coveragePairs(data.coverage), width))\n }\n return lines\n}\n\nfunction buildOverviewPairs(usage: Overview, scope: \"all\" | \"session\", estimates = true): (readonly [string, string])[] {\n const pairs = usagePairs(usage, estimates)\n if (scope === \"all\") {\n pairs.push([\"first\", usage.firstAt === undefined ? \"–\" : new Date(usage.firstAt).toLocaleString(\"en-GB\")])\n pairs.push([\"last\", usage.lastAt === undefined ? \"–\" : new Date(usage.lastAt).toLocaleString(\"en-GB\")])\n }\n return pairs\n}\n\nfunction coveragePairs(coverage: CoverageReport): (readonly [string, string])[] {\n const share = (missing: number) => (coverage.steps === 0 ? \"–\" : `${((missing / coverage.steps) * 100).toFixed(1)}%`)\n return [\n [\"models\", `${formatCount(coverage.models)} · unknown ${share(coverage.missingModel)}`],\n [\"providers\", formatCount(coverage.providers)],\n [\"unsettled\", `${formatCount(coverage.unsettled)} · no tps ${share(coverage.missingTps)}`],\n [\"no ttft\", share(coverage.missingFirstToken)],\n [\n \"window\",\n `${coverage.firstAt === undefined ? \"–\" : new Date(coverage.firstAt).toLocaleString(\"en-GB\")} → ${\n coverage.lastAt === undefined ? \"–\" : new Date(coverage.lastAt).toLocaleString(\"en-GB\")\n }`,\n ],\n ]\n}\n\n// ---------------------------------------------------------------------------\n// Models\n// ---------------------------------------------------------------------------\n\nexport type ModelExtras = {\n /** Reuse stats per `modelKey`, computed from the step facts. */\n cache?: Map<string, CacheStats> | undefined\n /** Switches per `modelKey`, computed from the consecutive step pairs. */\n switches?: Map<string, SwitchRow> | undefined\n}\n\ntype ModelRowView = {\n modelID: string\n variant: string | undefined\n steps: string\n prompt: string\n cached: string\n hit: string\n output: string\n cost: string\n providers: string\n detail: string\n}\n\n/**\n * Usage per model with the cache it actually got, the providers it ran through\n * and how often its identity changed. One line per model; `providers` keeps the\n * per-provider detail.\n */\nexport function modelsLines(rows: readonly ModelUsage[], width: number, extras?: ModelExtras, limit = 40, estimates = true): PanelLine[] {\n // The name cell needs the final column width; fitTable only measures the\n // specs, so the value is filled in after the fit and before any row renders.\n let modelWidth = 14\n const columns = fitTable<ModelRowView>(\n [\n { header: \"model\", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => row.steps },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", cell: (row) => row.prompt },\n { header: \"cached\", width: 7, max: 10, align: \"right\", cell: (row) => row.cached },\n { header: \"hit\", width: 6, max: 7, priority: 2, reserve: 10, align: \"right\", cell: (row) => row.hit },\n { header: \"out\", width: 7, max: 9, priority: 3, reserve: 10, align: \"right\", cell: (row) => row.output },\n { header: \"cost\", width: 8, max: 9, priority: 1, align: \"right\", cell: (row) => row.cost },\n { header: \"providers\", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers },\n ],\n width,\n )\n modelWidth = columns.find((column) => column.index === 0)?.width ?? 0\n if (columns.length === 0) return [{ text: truncate(\"no room for a table at this width\", width), tone: \"muted\" }]\n const lines: PanelLine[] = [\n {\n text: formatTableRow(\n columns.map((column) => column.header),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: HEADER_TONE,\n },\n ]\n\n for (const model of rows.slice(0, limit)) {\n const key = modelKey(model.modelID, model.variant)\n const buckets = usageBuckets(model.totals)\n // The same model can come from more than one provider, so the column names\n // them; the detail line below carries the reuse and the change count.\n const providers = unique(model.providers.map((provider) => provider.providerID))\n const cache = extras?.cache?.get(key)\n const switches = extras?.switches?.get(key)\n const details: string[] = []\n if (cache !== undefined) details.push(`p50 hit ${formatPercent(cache.hitP50)}`)\n if (switches !== undefined && switches.changes > 0) {\n // The dimensions overlap — a single switch can change both — so the\n // provider count is given as the part of the total that can cost a cache.\n const scope = switches.providerChanges > 0 ? ` (${formatCount(switches.providerChanges)} provider)` : \"\"\n details.push(`${count(switches.changes, \"switch\", \"switches\")}${scope}`)\n if (switches.cacheLost > 0) details.push(`${formatTokens(switches.cacheLost)} lost on a switch`)\n }\n const view: ModelRowView = {\n modelID: model.modelID,\n variant: model.variant,\n steps: formatCount(buckets.steps),\n prompt: formatTokens(buckets.prompt),\n cached: formatTokens(buckets.cached),\n hit: formatPercent(cache?.hit ?? buckets.hit),\n output: formatTokens(buckets.output),\n cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),\n providers: providers.join(\", \"),\n detail: details.join(\" · \"),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(view)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: \"base\",\n row: { kind: \"model\", value: model.modelID, ...(model.variant !== undefined ? { variant: model.variant } : {}) },\n })\n if (view.detail !== \"\") {\n lines.push({ text: truncate(`${\" \".repeat(modelWidth + 1)}${view.detail}`, width), tone: \"muted\" })\n }\n }\n if (rows.length > limit) lines.push({ text: truncate(`… ${count(rows.length - limit, \"more model\")} · narrow the range or filter`, width), tone: \"muted\" })\n if (rows.length === 0) lines.push({ text: truncate(\"no usage recorded for this range\", width), tone: \"muted\" })\n return lines\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)]\n}\n\n// ---------------------------------------------------------------------------\n// Providers (model × provider)\n// ---------------------------------------------------------------------------\n\n/**\n * A table column. Header, fitting spec, alignment and cell come from the same\n * definition, so dropping a column can never shift the others. The cell gets\n * the final width so a name can be shortened in the middle.\n */\ntype TableSpec<Row> = TableColumnFit & {\n header: string\n align?: \"left\" | \"right\" | undefined\n cell: (row: Row, width: number) => string\n}\n\nfunction renderTable<Row>(\n rows: readonly Row[],\n columns: readonly TableSpec<Row>[],\n width: number,\n options: { limit: number; empty: string; row?: (row: Row) => PanelRow | undefined; tone?: (row: Row) => PanelTone },\n): PanelLine[] {\n const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {\n const column = columns[index]!\n const align: \"left\" | \"right\" = column.align ?? \"left\"\n return { ...column, width: fitted, align }\n })\n if (chosen.length === 0) return [{ text: truncate(options.empty, width), tone: \"muted\" }]\n const widths = chosen.map((column) => column.width)\n const aligns = chosen.map((column) => column.align)\n const lines: PanelLine[] = [\n { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE },\n ]\n if (rows.length === 0) lines.push({ text: truncate(options.empty, width), tone: \"muted\" })\n for (const row of rows.slice(0, options.limit)) {\n const identity = options.row?.(row)\n lines.push({\n text: formatTableRow(\n chosen.map((column) => column.cell(row, column.width)),\n widths,\n aligns,\n ),\n tone: options.tone?.(row) ?? \"base\",\n ...(identity === undefined ? {} : { row: identity }),\n })\n }\n if (rows.length > options.limit) {\n lines.push({ text: truncate(`… ${count(rows.length - options.limit, \"more row\")}`, width), tone: \"muted\" })\n }\n return lines\n}\n\n/** One row per provider, over every model it served. */\nexport function providerSummaryLines(rows: readonly ProviderSummary[], width: number, limit = 40, estimates = true): PanelLine[] {\n const lines = renderTable(\n rows,\n [\n { header: \"provider\", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? \"– (unknown)\", column) },\n { header: \"models\", width: 6, align: \"right\", priority: 4, cell: (row) => formatCount(row.models.length) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => formatCount(row.usage.steps) },\n { header: \"share\", width: 6, align: \"right\", priority: 3, cell: (row) => formatPercent(row.share, 0) },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.prompt) },\n { header: \"cached\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.cached) },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 2, cell: (row) => formatPercent(row.cache.hit) },\n { header: \"tps p50\", width: 8, align: \"right\", priority: 5, cell: (row) => formatTps(row.tps) },\n { header: \"ttft p50\", width: 8, max: 9, align: \"right\", priority: 6, cell: (row) => formatMs(row.ttft) },\n { header: \"wall\", width: 7, align: \"right\", priority: 7, cell: (row) => formatMs(row.wall) },\n { header: \"cost\", width: 8, max: 9, align: \"right\", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) },\n ],\n width,\n {\n limit,\n empty: \"no usage recorded for this range\",\n // A step recorded without a provider is not a row to drill into.\n row: (row) => (row.provider === undefined ? undefined : { kind: \"provider\", value: row.provider }),\n tone: (row) => (row.provider === undefined ? \"muted\" : \"base\"),\n },\n )\n return lines\n}\n\n/** One row per model × provider: the providers each model ran through. */\nexport function providerLines(rows: readonly ProviderRow[], width: number, limit = 40, estimates = true): PanelLine[] {\n return renderTable(\n rows,\n [\n { header: \"model\", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },\n { header: \"provider\", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? \"– (unknown)\", column) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => formatCount(row.usage.steps) },\n { header: \"share\", width: 6, align: \"right\", priority: 5, cell: (row) => formatPercent(row.share, 0) },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },\n { header: \"cached\", width: 7, max: 10, align: \"right\", priority: 3, cell: (row) => formatTokens(row.cache.cached) },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 4, cell: (row) => formatPercent(row.cache.hit) },\n { header: \"tps p50\", width: 8, align: \"right\", priority: 6, cell: (row) => formatTps(row.tps) },\n { header: \"ttft p50\", width: 8, max: 9, align: \"right\", priority: 7, cell: (row) => formatMs(row.ttft) },\n { header: \"wall\", width: 7, align: \"right\", priority: 8, cell: (row) => formatMs(row.wall) },\n { header: \"cost\", width: 8, max: 9, align: \"right\", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) },\n ],\n width,\n {\n limit,\n empty: \"no usage recorded for this range\",\n row: (row) => ({ kind: \"model\", value: row.modelID, ...(row.variant !== undefined ? { variant: row.variant } : {}) }),\n tone: (row) => (row.provider === undefined ? \"muted\" : \"base\"),\n },\n )\n}\n\n// ---------------------------------------------------------------------------\n// Cache\n// ---------------------------------------------------------------------------\n\n/** One model's reuse row, shared by the models and cache views. */\nexport type CacheModelRow = {\n usage: { modelID: string; variant: string | undefined }\n cache: CacheStats\n}\n\nexport function cacheLines(\n data: {\n drops: readonly CacheDropRow[]\n evidence: readonly TtlEvidenceRow[]\n gap?: GapReport | undefined\n models?: readonly CacheModelRow[] | undefined\n },\n width: number,\n): PanelLine[] {\n const lines: PanelLine[] = []\n const push = (text: string, tone: PanelTone = \"base\"): void => {\n lines.push({ text: truncate(text, width), tone })\n }\n const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0)\n push(`reuse losses ${count(data.drops.length, \"event\")} · ${formatTokens(total)} tokens`, total > 0 ? \"warning\" : \"base\")\n for (const reason of [\"expired\", \"compaction\", \"unknown\"] as const) {\n const group = data.drops.filter((drop) => drop.reason === reason)\n if (group.length === 0) continue\n const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0)\n push(` ${padCell(reason, 11)}${formatCount(group.length)} · ${formatTokens(tokens)}`, reason === \"expired\" ? \"warning\" : \"muted\")\n }\n if (data.drops.length === 0) push(\" none: prompt cache held through every gap\", \"muted\")\n\n if (data.models !== undefined && data.models.length > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"reuse by model\", HEADER_TONE)\n // The model name keeps the variant visible; the width has to be known\n // before a cell is built, so it is filled in after the fit.\n let modelWidth = 12\n const reuse = fitTable<CacheModelRow>(\n [\n { header: \"model\", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => formatCount(row.cache.steps) },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.prompt) },\n { header: \"cached\", width: 7, max: 10, align: \"right\", cell: (row) => formatTokens(row.cache.cached) },\n { header: \"write\", width: 6, max: 8, align: \"right\", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 2, cell: (row) => formatPercent(row.cache.hit) },\n { header: \"hit p50\", width: 7, max: 9, align: \"right\", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) },\n ],\n width,\n )\n modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0\n if (reuse.length > 0) {\n lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: \"muted\" })\n for (const row of data.models.slice(0, 10)) {\n lines.push({\n text: formatTableRow(\n reuse.map((column) => column.cell(row)),\n reuse.map((column) => column.width),\n reuse.map((column) => column.align),\n ),\n tone: \"base\",\n row: { kind: \"model\", value: row.usage.modelID, ...(row.usage.variant !== undefined ? { variant: row.usage.variant } : {}) },\n })\n }\n }\n }\n\n if (data.gap !== undefined && data.gap.samples > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"cache survival against idle time\", HEADER_TONE)\n const buckets = data.gap.buckets\n const survival = fitTable<(typeof buckets)[number]>(\n [\n { header: \"gap\", width: 8, max: 12, cell: (bucket) => bucket.label },\n { header: \"pairs\", width: 6, align: \"right\", cell: (bucket) => formatCount(bucket.samples) },\n { header: \"kept\", width: 7, align: \"right\", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },\n { header: \"drops\", width: 7, align: \"right\", cell: (bucket) => formatCount(bucket.drops) },\n { header: \"lost\", width: 8, align: \"right\", cell: (bucket) => formatTokens(bucket.lostTokens) },\n ],\n width,\n )\n if (survival.length > 0) {\n lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: \"muted\" })\n for (const bucket of buckets) {\n if (bucket.samples === 0) continue\n lines.push({\n text: formatTableRow(\n survival.map((column) => column.cell(bucket)),\n survival.map((column) => column.width),\n survival.map((column) => column.align),\n ),\n tone: bucket.drops > 0 ? \"warning\" : \"base\",\n })\n }\n }\n if (data.gap.providers.length > 1) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"reuse kept, by provider\", HEADER_TONE)\n const providers = data.gap.providers\n const reuse = fitTable<(typeof providers)[number]>(\n [\n { header: \"provider\", width: 12, max: 30, cell: (row) => row.provider },\n { header: \"pairs\", width: 6, align: \"right\", cell: (row) => formatCount(row.samples) },\n { header: \"kept\", width: 7, align: \"right\", cell: (row) => formatPercent(row.retainedRatio, 0) },\n { header: \"lost\", width: 8, align: \"right\", cell: (row) => formatTokens(row.lostTokens) },\n ],\n width,\n )\n if (reuse.length > 0) {\n lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: \"muted\" })\n for (const row of providers.slice(0, 8)) {\n lines.push({\n text: formatTableRow(\n reuse.map((column) => column.cell(row)),\n reuse.map((column) => column.width),\n reuse.map((column) => column.align),\n ),\n tone: \"base\",\n })\n }\n }\n }\n }\n\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"observed cache TTL bounds\", HEADER_TONE)\n if (data.evidence.length === 0) {\n push(\" no comparable step pairs yet\", \"muted\")\n } else {\n const evidence = fitTable<TtlEvidenceRow>(\n [\n { header: \"model\", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },\n { header: \"hits up to\", width: 10, align: \"right\", cell: (row) => formatGap(row.maxHitGapMs) },\n { header: \"drops from\", width: 10, align: \"right\", cell: (row) => formatGap(row.minDropGapMs) },\n { header: \"samples\", width: 7, align: \"right\", priority: 1, cell: (row) => formatCount(row.samples) },\n ],\n width,\n )\n if (evidence.length > 0) {\n lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: \"muted\" })\n for (const row of data.evidence.slice(0, 10)) {\n lines.push({\n text: formatTableRow(\n evidence.map((column) => column.cell(row)),\n evidence.map((column) => column.width),\n evidence.map((column) => column.align),\n ),\n tone: \"base\",\n })\n }\n }\n }\n\n if (data.drops.length > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n push(\"recent losses\", HEADER_TONE)\n const losses = fitTable<CacheDropRow>(\n [\n { header: \"when\", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString(\"en-GB\") },\n { header: \"provider/model\", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? \"\"}/${drop.modelID ?? \"\"}` },\n { header: \"tokens\", width: 7, align: \"right\", cell: (drop) => `−${formatTokens(drop.tokens)}` },\n { header: \"idle\", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle · ${drop.reason}` },\n ],\n width,\n )\n if (losses.length > 0) {\n lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: \"muted\" })\n for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {\n lines.push({\n text: formatTableRow(\n losses.map((column) => column.cell(drop)),\n losses.map((column) => column.width),\n losses.map((column) => column.align),\n ),\n tone: drop.reason === \"expired\" ? \"warning\" : \"base\",\n })\n }\n }\n }\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Periods\n// ---------------------------------------------------------------------------\n\ntype PeriodView = {\n label: string\n steps: string\n sessions: string\n prompt: string\n cached: string\n hit: string\n output: string\n cost: string\n}\n\nexport function periodLines(\n rows: readonly PeriodRow[],\n width: number,\n granularity: PeriodGranularity,\n limit = 40,\n estimates = true,\n totalSessions?: number,\n): PanelLine[] {\n const lines: PanelLine[] = []\n const totals = rows.reduce(\n (sum, row) => {\n sum.steps += row.usage.steps\n sum.sessions += row.sessions\n sum.input += row.usage.input\n sum.cached += row.usage.cached\n sum.cacheWrite += row.usage.cacheWrite\n sum.output += row.usage.output\n sum.reasoning += row.usage.reasoning\n sum.cost += row.usage.cost\n sum.listCost += row.usage.listCost\n return sum\n },\n { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 },\n )\n const overall = usageBuckets(totals)\n lines.push({\n text: truncate(\n `${granularityLabel(granularity)} · ${count(rows.length, \"period\")} · ${count(totals.steps, \"step\")} · hit ${formatPercent(overall.hit)}`,\n width,\n ),\n tone: \"muted\",\n })\n if (rows.length > 1) {\n const bars = Math.max(4, width - 8)\n lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: \"muted\" })\n lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: \"muted\" })\n lines.push({\n text: truncate(\n `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 10_000)), bars)}`,\n width,\n ),\n tone: \"muted\",\n })\n }\n const columns = fitTable<PeriodView>(\n [\n { header: \"period\", width: 10, max: 24, cell: (row) => row.label },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => row.steps },\n { header: \"sess\", width: 6, align: \"right\", priority: 5, cell: (row) => row.sessions },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", priority: 1, cell: (row) => row.prompt },\n { header: \"cached\", width: 7, max: 10, align: \"right\", priority: 2, cell: (row) => row.cached },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 3, cell: (row) => row.hit },\n { header: \"out\", width: 7, max: 9, align: \"right\", priority: 4, cell: (row) => row.output },\n { header: \"cost\", width: 8, max: 9, align: \"right\", cell: (row) => row.cost },\n ],\n width,\n )\n if (columns.length === 0) return [...lines, { text: truncate(\"no room for a table at this width\", width), tone: \"muted\" }]\n const header = formatTableRow(\n columns.map((column) => column.header),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n )\n lines.push({ text: header, tone: HEADER_TONE })\n\n const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit)\n for (const row of newest) {\n const buckets = usageBuckets(row.usage)\n const view: PeriodView = {\n label: row.label,\n steps: formatCount(row.steps),\n sessions: formatCount(row.sessions),\n prompt: formatTokens(buckets.prompt),\n cached: formatTokens(buckets.cached),\n hit: formatPercent(buckets.hit, 0),\n output: formatTokens(buckets.output),\n cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(view)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: \"base\",\n row: { kind: \"period\", value: row.key },\n })\n }\n lines.push({ text: \"\", tone: \"muted\" })\n const total: PeriodView = {\n label: \"total\",\n steps: formatCount(totals.steps),\n // A session active in several periods is one session, not one per period:\n // the total row uses the range's distinct count when given.\n sessions: formatCount(totalSessions ?? totals.sessions),\n prompt: formatTokens(overall.prompt),\n cached: formatTokens(overall.cached),\n hit: formatPercent(overall.hit, 0),\n output: formatTokens(overall.output),\n cost: formatSpend(overall.cost, estimates ? overall.listCost : 0),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(total)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: HEADER_TONE,\n })\n if (rows.length === 0) lines.push({ text: truncate(\"no usage recorded for this range\", width), tone: \"muted\" })\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Latency\n// ---------------------------------------------------------------------------\n\n/** One metric line for a panel too narrow for the fixed percentile table. */\nfunction latencyMetric(label: string, values: readonly string[], width: number): string {\n const prefix = padCell(label, 11)\n let text = `${prefix}${values[0] ?? \"–\"}`\n for (let index = 1; index < values.length; index += 1) {\n const next = `${text} · ${values[index]!}`\n if (next.length > width) break\n text = next\n }\n return text\n}\n\nexport function latencyLines(report: LatencyReport, width: number, groups?: readonly LatencyGroupRow[] | undefined, limit = 12, estimates = true): PanelLine[] {\n const lines: PanelLine[] = []\n if (width >= 68) {\n lines.push({\n text: formatTableRow(\n [\"wall\", \"p50\", formatMs(report.wall.p50), \"p90\", formatMs(report.wall.p90), \"p99\", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`],\n [10, 4, 9, 4, 9, 4, 9, 12],\n ),\n tone: \"base\",\n })\n lines.push({\n text: formatTableRow([\"stream\", \"p50\", formatMs(report.stream.p50), \"p90\", formatMs(report.stream.p90), \"p99\", formatMs(report.stream.p99)], [10, 4, 9, 4, 9, 4, 9]),\n tone: \"base\",\n })\n lines.push({\n text: formatTableRow([\"ttft\", \"p50\", formatMs(report.ttft.p50), \"p90\", formatMs(report.ttft.p90), \"p99\", formatMs(report.ttft.p99)], [10, 4, 9, 4, 9, 4, 9]),\n tone: \"base\",\n })\n lines.push({\n text: formatTableRow([\"tps\", \"p50\", formatTps(report.tps.p50), \"p90\", formatTps(report.tps.p90), \"p99\", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),\n tone: \"base\",\n })\n lines.push({\n text: formatTableRow([\"rtps\", \"p50\", formatTps(report.requestTps.p50), \"p90\", formatTps(report.requestTps.p90), \"p99\", formatTps(report.requestTps.p99)], [10, 4, 9, 4, 9, 4, 9]),\n tone: \"base\",\n })\n } else {\n // The percentile table needs 68 columns. Below that each metric keeps p50\n // and adds p90/p99 while they fit, instead of overflowing.\n lines.push({\n text: latencyMetric(\"wall\", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),\n tone: \"base\",\n })\n lines.push({\n text: latencyMetric(\"stream\", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),\n tone: \"base\",\n })\n lines.push({\n text: latencyMetric(\"ttft\", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),\n tone: \"base\",\n })\n lines.push({\n text: latencyMetric(\"tps\", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),\n tone: \"base\",\n })\n lines.push({\n text: latencyMetric(\"rtps\", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),\n tone: \"base\",\n })\n }\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({\n text: truncate(\"wall = request to completed · stream = request to last chunk\", width),\n tone: \"muted\",\n })\n lines.push({\n text: truncate(\"ttft = request to first token · tps = first token to last chunk · rtps = request to last chunk\", width),\n tone: \"muted\",\n })\n if (report.wall.count === 0) lines.push({ text: truncate(\"no completed steps for this range\", width), tone: \"muted\" })\n\n if (groups !== undefined && groups.length > 0) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"by group\", tone: HEADER_TONE })\n const columns = fitTable<LatencyGroupRow>(\n [\n { header: \"group\", width: 8, max: 32, cell: (row) => row.label },\n { header: \"n\", width: 4, align: \"right\", cell: (row) => formatCount(row.count) },\n { header: \"wall p50\", width: 8, align: \"right\", cell: (row) => formatMs(row.wall.p50) },\n { header: \"wall p90\", width: 8, max: 9, align: \"right\", priority: 1, cell: (row) => formatMs(row.wall.p90) },\n { header: \"stream\", width: 6, max: 9, align: \"right\", priority: 2, cell: (row) => formatMs(row.stream.p50) },\n { header: \"tps p50\", width: 8, max: 9, align: \"right\", cell: (row) => formatTps(row.tps.p50) },\n { header: \"tps p90\", width: 8, max: 9, align: \"right\", priority: 4, cell: (row) => formatTps(row.tps.p90) },\n { header: \"ttft p50\", width: 8, max: 9, align: \"right\", priority: 3, cell: (row) => formatMs(row.ttft.p50) },\n { header: \"cost\", width: 8, max: 9, align: \"right\", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) },\n ],\n width,\n )\n if (columns.length > 0) {\n lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: \"muted\" })\n for (const row of groups.slice(0, limit)) {\n const thin = row.count < 5\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(row)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: thin ? \"muted\" : \"base\",\n row: { kind: \"model\", value: row.key },\n })\n }\n }\n lines.push({ text: truncate(\"n < 5 is dimmed: too few samples to compare\", width), tone: \"muted\" })\n }\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\ntype SessionView = {\n title: string\n steps: string\n prompt: string\n cached: string\n hit: string\n output: string\n cost: string\n}\n\nexport function sessionsLines(\n rows: readonly SessionUsage[],\n width: number,\n options?: {\n limit?: number | undefined\n estimates?: boolean | undefined\n rollup?: { subagentSteps: number; subagentCost: number; subagentListCost?: number | undefined } | undefined\n },\n): PanelLine[] {\n const limit = options?.limit ?? 20\n const estimates = options?.estimates !== false\n const columns = fitTable<SessionView>(\n [\n { header: \"title\", width: 10, max: 48, cell: (row) => row.title },\n { header: \"steps\", width: 6, align: \"right\", cell: (row) => row.steps },\n { header: \"prompt\", width: 7, max: 10, align: \"right\", priority: 1, cell: (row) => row.prompt },\n { header: \"cached\", width: 7, max: 10, align: \"right\", priority: 2, cell: (row) => row.cached },\n { header: \"hit\", width: 6, max: 7, align: \"right\", priority: 3, cell: (row) => row.hit },\n { header: \"out\", width: 7, max: 9, align: \"right\", priority: 4, cell: (row) => row.output },\n // The cost is the one column a narrow panel must keep: the list is a\n // spend report before it is a token report.\n { header: \"cost\", width: 8, max: 9, align: \"right\", cell: (row) => row.cost },\n ],\n width,\n )\n const lines: PanelLine[] = [\n {\n text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),\n tone: HEADER_TONE,\n },\n ]\n const byID = new Map(rows.map((row) => [row.sessionID, row]))\n const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID))\n const children = rows.filter((row) => row.parentID !== undefined && byID.has(row.parentID))\n const orderedAll = [...ordered, ...children]\n\n for (const row of orderedAll.slice(0, limit)) {\n const child = row.parentID !== undefined && byID.has(row.parentID)\n const buckets = usageBuckets(row)\n const view: SessionView = {\n title: `${child ? \"↳ \" : \"\"}${row.title ?? row.sessionID}`,\n steps: formatCount(buckets.steps),\n prompt: formatTokens(buckets.prompt),\n cached: formatTokens(buckets.cached),\n hit: formatPercent(buckets.hit, 0),\n output: formatTokens(buckets.output),\n cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),\n }\n lines.push({\n text: formatTableRow(\n columns.map((column) => column.cell(view)),\n columns.map((column) => column.width),\n columns.map((column) => column.align),\n ),\n tone: child ? \"muted\" : \"base\",\n row: { kind: \"session\", value: row.sessionID },\n })\n const details = [\n row.directory ?? \"\",\n row.models.length > 1 ? count(row.models.length, \"model\") : \"\",\n (row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost!)}` : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" · \")\n lines.push({ text: truncate(`${\" \".repeat(child ? 2 : 0)} ${details}`, width), tone: \"muted\" })\n }\n if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {\n const share = rows.reduce((sum, row) => sum + row.steps, 0)\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({\n text: truncate(\n `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) · ${formatSpend(\n options.rollup.subagentCost,\n estimates ? (options.rollup.subagentListCost ?? 0) : 0,\n )}`,\n width,\n ),\n tone: \"muted\",\n })\n }\n if (rows.length > limit) lines.push({ text: truncate(`… ${count(rows.length - limit, \"more session\")} · narrow the range`, width), tone: \"muted\" })\n if (rows.length === 0) lines.push({ text: truncate(\"no sessions recorded for this range\", width), tone: \"muted\" })\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Database\n// ---------------------------------------------------------------------------\n\n/** The database view: where it lives, what it holds, and the two cleanups. */\nexport function dbLines(data: { info: DbInfo; busy?: boolean | undefined; now: number; estimates?: boolean | undefined }, width: number): PanelLine[] {\n const lines: PanelLine[] = []\n const size = (bytes: number) => `${(bytes / 1_048_576).toFixed(1)} MB`\n lines.push({ text: truncate(data.info.path, width), tone: \"base\" })\n lines.push({\n text: truncate(\n `${size(data.info.bytes)}${data.info.walBytes === undefined ? \"\" : ` + ${size(data.info.walBytes)} wal`} · schema v${data.info.schemaVersion}`,\n width,\n ),\n tone: \"muted\",\n })\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"what it holds\", tone: HEADER_TONE })\n for (const table of data.info.tables) {\n lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? \"muted\" : \"base\" })\n }\n lines.push({\n text: truncate(\n ` window ${data.info.firstAt === undefined ? \"–\" : new Date(data.info.firstAt).toLocaleDateString(\"en-GB\")} → ${\n data.info.lastAt === undefined ? \"–\" : new Date(data.info.lastAt).toLocaleDateString(\"en-GB\")\n }`,\n width,\n ),\n tone: \"muted\",\n })\n\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: \"clean up\", tone: HEADER_TONE })\n // The retention rows and the wipe row are the only selectable lines here, so\n // the hint says how to pick one and what Enter does: a retention row is a\n // cutoff, not a count, and the last row is everything. Only the TUI renders\n // this line; the desktop panel has buttons instead.\n lines.push({\n text: truncate(\n ` ↑↓ pick a retention · enter prunes from its cutoff · the wipe row deletes everything (asks first)${\n data.estimates === false ? \"\" : \" · e backfills list estimates\"\n } · v gives the space back`,\n width,\n ),\n tone: \"muted\",\n hint: true,\n })\n if (data.estimates !== false) {\n lines.push({\n text: truncate(\n data.info.schemaVersion < 10\n ? \" list estimates the recorder must upgrade this database first\"\n : data.info.unpriced === 0\n ? \" list estimates every $0 step has a price\"\n : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price`,\n width,\n ),\n tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? \"base\" : \"muted\",\n })\n }\n const widths = [9, 11, 10]\n lines.push({ text: formatTableRow([\"keep\", \"prunes\", \"older than\"], widths, [\"left\", \"right\", \"left\"]), tone: \"muted\" })\n for (const option of data.info.removable) {\n const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString(\"en-GB\")\n lines.push({\n text: formatTableRow([`${option.days} days`, `${formatCount(option.steps)} steps`, before], widths, [\"left\", \"right\", \"left\"]),\n tone: option.steps === 0 ? \"muted\" : \"base\",\n row: { kind: \"prune\", value: String(option.days) },\n })\n }\n const steps = data.info.tables.find((table) => table.name === \"steps\")?.rows ?? 0\n const sessions = data.info.tables.find((table) => table.name === \"sessions\")?.rows ?? 0\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({\n text: truncate(` wipe everything · ${formatCount(steps)} steps · ${formatCount(sessions)} sessions · cannot be undone`, width),\n tone: steps === 0 && sessions === 0 ? \"muted\" : \"warning\",\n row: { kind: \"wipe\", value: \"all\" },\n })\n if (data.busy === true) {\n lines.push({ text: \"\", tone: \"muted\" })\n lines.push({ text: truncate(\"the recorder is writing: try the vacuum again in a moment\", width), tone: \"warning\" })\n }\n return lines\n}\n\n// ---------------------------------------------------------------------------\n// Turns\n// ---------------------------------------------------------------------------\n\nexport type LineFormatOptions = {\n labels?: Partial<LineLabels> | undefined\n fields?: Partial<LineFields> | undefined\n turnTotals?: TurnTotalsView | undefined\n /** `false` hides list-price estimates everywhere this line is rendered. */\n estimates?: boolean | undefined\n}\n\n/** The line's own view of a recorded turn, so both render identically. */\nexport function turnStats(turn: TurnUsage): TurnStats {\n return {\n endAt: turn.endAt,\n startAt: turn.promptAt ?? turn.endAt,\n promptAt: turn.promptAt,\n promptGapMs: turn.promptGapMs,\n providerID: turn.providerID,\n modelID: turn.modelID,\n variant: turn.variant,\n providerChanged: turn.providerChanged,\n modelChanged: turn.modelChanged,\n totals: turn.totals,\n latest: turn.latest,\n session: undefined,\n drops: turn.drops.map((drop) => ({ messageID: drop.messageID, tokens: drop.tokens, prevCached: 0, gapMs: drop.gapMs })),\n cacheDropTokens: turn.drops.reduce((sum, drop) => sum + drop.tokens, 0),\n cacheExpired: turn.drops.length > 0,\n steps: turn.steps,\n }\n}\n\n/**\n * A budget form of the turn line for a panel too narrow for the live line.\n * It always keeps the money and the identity, then adds the token volumes\n * while they fit. `turnsLines` uses the full line whenever it fits, so this\n * only changes the rows that would otherwise have their tail cut off.\n */\nexport function compactTurnLine(stats: TurnStats, width: number, options?: LineFormatOptions): string {\n const labels = { ...DEFAULT_LABELS, ...options?.labels }\n const fields = { ...DEFAULT_FIELDS, ...options?.fields }\n const estimates = options?.estimates !== false\n const headParts: string[] = []\n if (fields.clock && stats.endAt !== undefined) headParts.push(formatClock(stats.endAt))\n if (stats.providerID !== undefined) {\n let identity = stats.providerID\n if (fields.model && stats.modelID !== undefined) identity += `/${stats.modelID}`\n if (fields.variant && stats.variant) identity += ` ${stats.variant}`\n headParts.push(identity)\n }\n let head = headParts.join(\" \")\n const totals = options?.turnTotals === \"sum\" ? stats.totals : stats.latest\n const display = displayTotals(totals)\n const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined\n const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim()\n const warning =\n fields.cacheExpiry && stats.cacheExpired\n ? `⚠ ${labels.cacheExpired} (−${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` ×${stats.drops.length}` : \"\"})`\n : undefined\n // Money and the cache warning are the facts that must survive; the tokens\n // are added only while the line still fits.\n let suffix = [warning, cost].filter((part): part is string => part !== undefined).join(\" · \")\n if (suffix !== \"\" && suffix.length + 3 > width) suffix = cost ?? suffix\n head = truncate(head, Math.max(0, width - (suffix === \"\" ? 0 : suffix.length + 3)))\n if (!fields.turn || stats.totals.steps === 0) return [head, suffix].filter((part) => part !== \"\").join(\" · \")\n const input =\n display.prompt === display.input\n ? `${labels.input} ${formatTokens(display.input)}`\n : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`\n const volumes = [\n input,\n `${labels.cached} ${formatTokens(display.cached)}`,\n `${labels.output} ${formatTokens(display.output)}`,\n ...(fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []),\n ]\n let numbers = \"\"\n for (const volume of volumes) {\n const next = numbers === \"\" ? volume : `${numbers}, ${volume}`\n if ([head, next, suffix].filter((part) => part !== \"\").join(\" · \").length > width) break\n numbers = next\n }\n return [head, numbers, suffix].filter((part) => part !== \"\").join(\" · \")\n}\n\n/**\n * Per-prompt history: one line per finished turn, rendered by the same\n * formatter as the live line (without the session segment, which would repeat\n * the same totals on every row). A narrow panel uses `compactTurnLine` rather\n * than cutting the money off the end of the line.\n */\nexport function turnsLines(rows: readonly TurnUsage[], width: number, options?: LineFormatOptions & { sessionTitles?: Map<string, string> | undefined }): PanelLine[] {\n const lines: PanelLine[] = []\n const warning = rows.filter((turn) => turn.drops.length > 0).length\n lines.push({\n text: truncate(`${count(rows.length, \"turn\")} · newest first${warning > 0 ? ` · ${count(warning, \"turn\")} with a cache loss` : \"\"}`, width),\n tone: \"muted\",\n })\n const showSession = options?.sessionTitles !== undefined\n for (const turn of rows) {\n const stats = turnStats(turn)\n const line = formatLine(stats, {\n ...options,\n fields: { ...options?.fields, session: false },\n })\n const title = showSession ? `${truncate(options!.sessionTitles!.get(turn.sessionID) ?? turn.sessionID, 18)} ` : \"\"\n const available = Math.max(0, width - title.length)\n const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`\n lines.push({\n text: truncate(text, width),\n tone: turn.drops.length > 0 || turn.providerChanged ? \"warning\" : \"base\",\n row: { kind: \"turn\", value: turn.sessionID },\n })\n }\n if (rows.length === 0) lines.push({ text: truncate(\"no finished turns for this range\", width), tone: \"muted\" })\n return lines\n}\n\n/**\n * The accumulated usage of one session, as compact lines for the sidebar. The\n * buckets are the live line's, so the sidebar, the line and the panel agree.\n */\nexport function sessionSummaryLines(usage: Overview, budget = 34, estimates = true): PanelLine[] {\n const buckets = usageBuckets(usage)\n const steps = formatCount(buckets.steps)\n const input = formatTokens(buckets.input)\n const cached = formatTokens(buckets.cached)\n const out = formatTokens(buckets.output)\n const hit = formatPercent(buckets.hit)\n const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`\n const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`\n const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`\n const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)\n // The same order as a turn's three lines: how much was sent (`in`, `cached`),\n // how much came back (`out`), then `hit`, both rates and the cost last. The\n // medians and the cost get a line of their own so the rates never force the\n // money off the block.\n const first = [\n ` ${steps} steps · in ${input}`,\n ` ${steps} steps`,\n ].find((text) => text.length <= budget)\n const second = [\n ` cached ${cached} · out ${out}`,\n ` cached ${cached}`,\n ].find((text) => text.length <= budget)\n const rates = [tps, rtps].filter((part): part is string => part !== undefined)\n const rateLine = [\n ` hit ${hit}${rates.length > 0 ? ` · ${rates.join(\" · \")}` : \"\"}`,\n ` hit ${hit}${rates[0] !== undefined ? ` · ${rates[0]}` : \"\"}`,\n ` hit ${hit}`,\n ].find((text) => text.length <= budget)\n const tail = [\n ttft === undefined ? undefined : ` ${ttft} · ${cost}`,\n ` ${cost}`,\n ]\n .filter((text): text is string => text !== undefined)\n .find((text) => text.length <= budget)\n return [\n { text: truncate(\"session\", budget), tone: HEADER_TONE },\n { text: truncate(first ?? ` ${steps} steps`, budget), tone: \"muted\" },\n { text: truncate(second ?? ` cached ${cached}`, budget), tone: \"base\" },\n { text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: \"base\" },\n { text: truncate(tail ?? ` ${cost}`, budget), tone: \"base\" },\n { text: \"\", tone: \"muted\" },\n ]\n}\n\n/**\n * The sidebar history: a compact block per turn — when and through which\n * provider and how long it took, then the prompt volumes, then the cache hit,\n * the rate and the cost.\n *\n * The model gets a line of its own at both ends of the block and on every turn\n * that changed it. The ends matter because the reader cannot tell whether a\n * block is the whole history or a window of a long session: the newest turn\n * names the model in use now, the oldest names the one the window started with,\n * and everything between them is read against the nearest line below it.\n */\nexport function sidebarLines(rows: readonly TurnUsage[], options?: LineFormatOptions & { budget?: number | undefined }): PanelLine[] {\n const budget = options?.budget ?? 34\n const labels = { input: options?.labels?.input ?? \"in\", output: options?.labels?.output ?? \"out\" }\n const lines: PanelLine[] = []\n for (const [index, turn] of rows.entries()) {\n const clock = turn.endAt !== undefined ? formatClock(turn.endAt).slice(0, 5) : \"--:--\"\n const provider = turn.providerID ?? \"unknown\"\n const display = displayTotals(turn.latest)\n const input = formatTokens(display.input)\n const prompt = formatTokens(display.prompt)\n const output = formatTokens(display.output)\n const cost =\n options?.estimates === false\n ? formatCost(turn.totals.cost)\n : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost)\n // The cache hit of the turn, on the same step the numbers come from. One\n // decimal, with a trailing `.0` dropped: the sidebar has no room to spare.\n const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\\.0%$/, \"%\")\n const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`\n const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`\n const rate = [tps, ttft].filter((part): part is string => part !== undefined).join(\" · \")\n const suffix = turn.drops.length > 0 ? \" · ⚠\" : \"\"\n // Three compact lines: when and through what, the prompt volumes with the\n // cache hit, then the rates and the money. `rtps` is a session aggregate,\n // not a turn fact; the turn shows `tps` and the TTFT that separates it from\n // `rtps`. The duration is dropped before the provider when the sidebar is\n // too narrow for both.\n const header = `${clock} ${provider}`\n const timed = turn.durationMs === undefined ? undefined : `${header} · ${formatMs(turn.durationMs)}`\n const join = (...parts: Array<string | undefined>): string =>\n parts.filter((part): part is string => part !== undefined && part !== \"\").join(\" · \")\n const volumes = [\n ` ${labels.input} ${input} (${prompt}) · ${labels.output} ${output} · hit ${hit}`,\n ` ${labels.input} ${input} · ${labels.output} ${output} · hit ${hit}`,\n ` ${labels.input} ${input} · ${labels.output} ${output}`,\n ` ${labels.input} ${input}`,\n ]\n const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1]!\n // When the hit did not fit on the volumes line, the facts line carries it\n // and loses the TTFT before it loses the money.\n const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`\n const facts = [\n ` ${join(hitPart, rate, `${cost}${suffix}`)}`,\n ` ${join(hitPart, tps, `${cost}${suffix}`)}`,\n ` ${join(tps, `${cost}${suffix}`)}`,\n ` ${join(tps)}`,\n ` ${join(hitPart, `${cost}${suffix}`)}`,\n ` ${join(`${cost}${suffix}`)}`,\n ]\n lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? \"warning\" : \"base\" })\n // The model appears at both ends of the block (the newest turn is the state\n // now, the oldest anchors the window) and on every turn that changed it: the\n // provider alone cannot say which model actually ran.\n const edge = index === 0 || index === rows.length - 1\n if (edge || turn.modelChanged || turn.providerChanged) {\n const model = turn.modelID === undefined ? \"unknown\" : `${turn.modelID}${turn.variant === undefined ? \"\" : ` ${turn.variant}`}`\n lines.push({ text: truncate(` ${model}`, budget), tone: \"muted\" })\n }\n lines.push({ text: truncate(volume, budget), tone: \"muted\" })\n lines.push({\n text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1]!, budget),\n tone: turn.drops.length > 0 ? \"warning\" : \"muted\",\n })\n }\n if (rows.length === 0) lines.push({ text: \"no finished turns yet\", tone: \"muted\" })\n return lines\n}\n",
20
+ "import type { Database } from \"bun:sqlite\"\nimport { formatTokens } from \"./core\"\nimport { clampPanelWidth } from \"./limits\"\nimport {\n cacheDropsOf,\n cachePairs,\n cacheStatsByModel,\n cacheStatsOf,\n coverageOf,\n providerBreakdownOf,\n providerSummaryOf,\n gapReportOf,\n latencyGroupsOf,\n latencyOf,\n periodEnd,\n periodsOf,\n stepRows,\n switchesOf,\n timingRows,\n ttlEvidenceOf,\n type CacheStats,\n type ProviderRow,\n type PairRow,\n type ProviderSummary,\n type Dimension,\n type LatencyGroupRow,\n type SwitchRow,\n} from \"./stats/aggregates\"\nimport {\n buildWhere,\n childSessionIDs,\n modelKey,\n models,\n otherUsageRows,\n overview,\n sessionUsageOf,\n sessions,\n spend,\n STEP_TIME,\n turns,\n type Filters,\n} from \"./stats/queries\"\nimport type { DbInfo } from \"./stats/maintenance\"\nimport {\n cacheLines,\n dbLines,\n formatCount,\n kvGrid,\n latencyLines,\n modelsLines,\n overviewLines,\n periodLines,\n providerSummaryLines,\n providerLines,\n sessionsLines,\n truncate,\n turnsLines,\n type CacheModelRow,\n type Granularity,\n type LineFormatOptions,\n type PanelLine,\n type PanelRow,\n type PanelView,\n type RangeKey,\n} from \"./panel-data\"\n\n/**\n * The panel's data assembly: read the database, run the queries the active view\n * needs and hand plain lines to the renderer. Kept out of the component so\n * every view can be asserted from an in-memory database, exactly as the CLI\n * report renders it.\n */\n\nexport type TurnsScope = \"session\" | \"all\"\n\n/** Everything the panel shows, in one request object. */\nexport type PanelRequest = {\n db: Database\n view: PanelView\n range: RangeKey\n filters: Filters\n granularity: Granularity\n turnsScope: TurnsScope\n sort: string\n sortDesc: boolean\n sessionID: string\n sessionStart: number | undefined\n now: number\n format?: LineFormatOptions | undefined\n /** Drill-down target: when set, the panel shows this detail instead. */\n detail?: PanelRow | undefined\n /** The database view's own state: where the file is and what it holds. */\n database?: DbInfo | undefined\n /** Set when the last vacuum could not take the write lock. */\n busy?: boolean | undefined\n /** `false` hides list-price estimates in every view. */\n estimates?: boolean | undefined\n width: number\n}\n\n/** Sorting options per view; the first is the default. */\nexport function detailLabel(row: PanelRow): string {\n switch (row.kind) {\n case \"model\":\n return `model ${row.variant !== undefined ? `${row.value} ${row.variant}` : row.value}`\n case \"session\":\n case \"turn\":\n return `session ${row.value}`\n case \"period\":\n return `period ${row.value}`\n case \"provider\":\n return `provider ${row.value}`\n case \"prune\":\n return `prune older than ${row.value} days`\n case \"wipe\":\n return \"wipe all recorded usage\"\n }\n}\n\n/** Build the panel lines for the request. Never throws: a failure is a line. */\nexport function buildPanel(request: PanelRequest): PanelLine[] {\n // The service clamps before it asks, but this function is also the report's\n // and the tests' entry point: keep the formatters and the final guard on one\n // width whatever the caller used.\n const width = clampPanelWidth(request.width)\n try {\n // The view formatters fit their tables, but a note or a detail line can\n // still be wider than a very narrow panel. This is the last line of\n // defence: nothing reaches a renderer wider than the width it asked for.\n return build({ ...request, width }).map((line) =>\n line.text.length <= width ? line : { ...line, text: truncate(line.text, width) },\n )\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return [{ text: truncate(`stats query failed: ${message}`, width), tone: \"warning\" }]\n }\n}\n\nfunction build(request: PanelRequest): PanelLine[] {\n const { db, view, now, sessionStart, width } = request\n const estimates = request.estimates !== false\n // The `session` range is the session itself, not \"everything recorded after it\n // started\": siblings and subagents run in that window too.\n const scoped = request.range === \"session\" && request.sessionID !== \"\"\n const range = scoped ? undefined : request.range === \"session\" ? (sessionStart === undefined ? undefined : { from: sessionStart }) : rangeForRequest(request.range, now)\n const filters: Filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters\n if (request.detail !== undefined) return buildDetail(request, range, filters, estimates)\n\n switch (view) {\n case \"overview\": {\n const usage = overview(db, range, filters)\n const sessionUsage =\n request.sessionID === \"\" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID })\n // Subagents are their own sessions; showing them apart explains why the\n // line's `sess` segment (one session) is smaller than the whole family.\n // The model/provider filters apply to them too, or the rollup would\n // disagree with the session block above it. The session filter does not:\n // these are other sessions.\n const childIDs = request.sessionID === \"\" ? [] : childSessionIDs(db, request.sessionID)\n const childFilters: Filters = { ...request.filters, sessionID: undefined }\n const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs, childFilters)\n return overviewLines(\n {\n usage,\n session: sessionUsage,\n ...(children.length > 0 ? { subagents: children } : {}),\n range: request.range,\n activity: activityOf(db, range, filters, now),\n coverage: coverageOf(db, { range, filters }),\n estimates,\n },\n width,\n )\n }\n case \"models\": {\n const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates)\n // One read of the pairs serves the reuse table and the switch counts.\n const pairs = cachePairs(db, { range, filters })\n const switches = switchesOf(pairs)\n return modelsLines(\n rows,\n width,\n {\n cache: cacheByModel(pairs),\n switches: switchesByModel(switches.rows),\n },\n 40,\n estimates,\n )\n }\n case \"providers\":\n return providerSummaryLines(\n sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates),\n width,\n 40,\n estimates,\n )\n case \"cache\": {\n // One read of the pairs serves the losses, the TTL bounds and the\n // survival buckets: they are three views of the same comparison.\n const pairs = cachePairs(db, { range, filters })\n return cacheLines(\n {\n drops: cacheDropsOf(db, pairs),\n evidence: ttlEvidenceOf(pairs),\n gap: gapReportOf(pairs),\n models: topCacheModels(pairs),\n },\n width,\n )\n }\n case \"periods\": {\n const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters))\n // Summing the per-period distinct session counts counts a session once\n // per period; the total row uses the range's own distinct count.\n const sessions = overview(db, range, filters).sessions\n return periodLines(rows, width, request.granularity, 40, estimates, sessions)\n }\n case \"latency\": {\n // One read of the timings serves the overall block and the group table.\n const timings = timingRows(db, { range, filters })\n const by: Dimension = filters.modelID !== undefined ? \"provider\" : \"model\"\n return latencyLines(\n latencyOf(timings),\n width,\n sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc),\n 14,\n estimates,\n )\n }\n case \"sessions\": {\n const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates)\n const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID))\n return sessionsLines(rows, width, {\n limit: 20,\n estimates,\n rollup: {\n subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),\n subagentCost: child.reduce((sum, row) => sum + row.cost, 0),\n subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0),\n },\n })\n }\n case \"db\":\n // The path and the file's size are the panel's, not the database's: a\n // builder without them says so instead of inventing a location.\n return request.database === undefined\n ? [{ text: \"the database location is unavailable to this panel\", tone: \"warning\" }]\n : dbLines({ info: request.database, busy: request.busy, now, estimates }, width)\n case \"go\":\n // Quotas are live host state, not database rows. The TUI and Desktop\n // render this view from their own client; a direct RPC caller gets an\n // explanation instead of an empty table.\n return [\n {\n text: \"OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.\",\n tone: \"muted\",\n },\n ]\n case \"turns\": {\n // The this-session range is one session; the scope control cannot widen\n // it, even when a persisted setting still says \"all sessions\".\n const scope: TurnsScope = scoped ? \"session\" : request.turnsScope\n const sessionID = scope === \"session\" ? request.sessionID : undefined\n const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates)\n const titles =\n scope === \"all\"\n ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID]))\n : undefined\n return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles })\n }\n }\n}\n\nfunction rangeForRequest(key: RangeKey, now: number): { from?: number | undefined; to?: number | undefined } | undefined {\n switch (key) {\n case \"today\": {\n const start = new Date(now)\n start.setHours(0, 0, 0, 0)\n return { from: start.getTime() }\n }\n case \"7d\":\n return { from: now - 7 * 24 * 60 * 60 * 1000 }\n case \"30d\":\n return { from: now - 30 * 24 * 60 * 60 * 1000 }\n default:\n return undefined\n }\n}\n\n// ---------------------------------------------------------------------------\n// Detail screens\n// ---------------------------------------------------------------------------\n\nfunction buildDetail(\n request: PanelRequest,\n range: { from?: number | undefined; to?: number | undefined } | undefined,\n filters: Filters,\n estimates: boolean,\n): PanelLine[] {\n const row = request.detail!\n const db = request.db\n const width = request.width\n const head: PanelLine = { text: detailLabel(row), tone: \"accent\" }\n const back: PanelLine = { text: \"backspace returns · the header shows where you came from\", tone: \"muted\" }\n\n if (row.kind === \"model\") {\n // The identity is the model *and* its variant: the variant is a different\n // model for the provider, so it gets its own detail.\n const scoped: Filters = { ...filters, modelKey: modelKey(row.value, row.variant) }\n const stats = cacheStatsOf(db, { range, filters: scoped })\n // One read of the steps serves the provider breakdown and the latency.\n const steps = stepRows(db, { range, filters: scoped })\n return [\n head,\n // One pair per line at a narrow width, two when they fit: the stats head\n // used to be a single 87-column line that a 68-column panel cut.\n ...kvGrid(\n [\n [\"steps\", formatCount(stats.steps)],\n [\"in\", formatTokens(stats.prompt - stats.cached)],\n [\"prompt\", formatTokens(stats.prompt)],\n [\"cached\", formatTokens(stats.cached)],\n [\"write\", formatTokens(stats.cacheWrite)],\n [\"hit\", percent(stats.hit)],\n [\"p50\", percent(stats.hitP50)],\n ],\n width,\n ),\n { text: \"\", tone: \"muted\" },\n ...providerLines(providerBreakdownOf(steps), width, 40, estimates),\n { text: \"\", tone: \"muted\" },\n // One model, so its latency is worth reading per provider: that is what\n // the model's own identity no longer separates.\n ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, \"provider\"), 14, estimates),\n { text: \"\", tone: \"muted\" },\n back,\n ]\n }\n if (row.kind === \"session\" || row.kind === \"turn\") {\n const rows = turns(db, { sessionID: row.value, limit: 80 })\n return [head, { text: \"\", tone: \"muted\" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: \"\", tone: \"muted\" }, back]\n }\n if (row.kind === \"provider\") {\n // A provider detail: every model it served, then its latency.\n const scoped: Filters = { ...filters, provider: row.value }\n // One read of the steps serves the reuse line and the latency block.\n const steps = stepRows(db, { range, filters: scoped })\n const stats = cacheStatsOf(db, { range, filters: scoped })\n return [\n head,\n ...kvGrid(\n [\n [\"steps\", formatCount(stats.steps)],\n [\"in\", formatTokens(stats.prompt - stats.cached)],\n [\"prompt\", formatTokens(stats.prompt)],\n [\"cached\", formatTokens(stats.cached)],\n [\"hit\", percent(stats.hit)],\n [\"p50\", percent(stats.hitP50)],\n ],\n width,\n ),\n { text: \"\", tone: \"muted\" },\n ...providerLines(providerBreakdownOf(steps), width, 40, estimates),\n { text: \"\", tone: \"muted\" },\n ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, \"model\"), 14, estimates),\n { text: \"\", tone: \"muted\" },\n back,\n ]\n }\n if (row.kind === \"period\") {\n // The bucket is one row of the period report: the providers must be the\n // ones of this bucket, not of the whole range the report was built from.\n const periods = periodsOf(stepRows(db, { range, filters }), request.granularity)\n const period = periods.find((entry) => entry.key === row.value)\n // The detail is the intersection of the bucket and the range the report\n // was built for; a period at the edge of a bounded range must not pull in\n // the steps that the range excluded.\n const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at)\n const to =\n period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY)\n const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters })\n return [\n head,\n { text: `${formatCount(period?.steps ?? 0)} steps`, tone: \"muted\" },\n { text: \"\", tone: \"muted\" },\n ...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),\n { text: \"\", tone: \"muted\" },\n back,\n ]\n }\n return [head, back]\n}\n\nfunction percent(value: number | undefined): string {\n return value === undefined ? \"–\" : `${(value * 100).toFixed(1)}%`\n}\n\n// ---------------------------------------------------------------------------\n// Sorting\n// ---------------------------------------------------------------------------\n\nfunction sortModels(rows: ReturnType<typeof models>, sort: string, desc: boolean, estimates = true): ReturnType<typeof models> {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (model: (typeof rows)[number]): number => {\n if (sort === \"cached\") return model.totals.cached\n if (sort === \"hit\") {\n const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite\n return prompt > 0 ? model.totals.cached / prompt : -1\n }\n if (sort === \"out\") return model.totals.output + model.totals.reasoning\n if (sort === \"cost\") return estimates ? spend(model.totals) : model.totals.cost\n return model.totals.steps\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortProviders(rows: readonly ProviderSummary[], sort: string, desc: boolean, estimates = true): ProviderSummary[] {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"cached\") return row.cache.cached\n if (sort === \"hit\") return row.cache.hit ?? -1\n if (sort === \"cost\") return estimates ? spend(row.usage) : row.usage.cost\n if (sort === \"share\") return row.share\n if (sort === \"tps\") return row.tps ?? -1\n if (sort === \"ttft\") return row.ttft ?? -1\n return row.usage.steps\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortLatency(rows: readonly LatencyGroupRow[], sort: string, desc: boolean): LatencyGroupRow[] {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"tps\") return row.tps.p50 ?? -1\n if (sort === \"ttft\") return row.ttft.p50 ?? -1\n if (sort === \"wall\") return row.wall.p50 ?? -1\n return row.count\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortSessions(rows: ReturnType<typeof sessions>, sort: string, desc: boolean, estimates = true): ReturnType<typeof sessions> {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"steps\") return row.steps\n if (sort === \"cached\") return row.cached\n if (sort === \"cost\") return estimates ? spend(row) : row.cost\n return row.lastAt ?? 0\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\nfunction sortTurns(rows: ReturnType<typeof turns>, sort: string, desc: boolean, estimates = true): ReturnType<typeof turns> {\n // `desc` is the user-facing direction: descending means the larger value\n // comes first. The comparator reads `pick(right) - pick(left)`, so the\n // multiplier must be +1 for descending, not -1.\n const sign = desc ? 1 : -1\n const pick = (row: (typeof rows)[number]): number => {\n if (sort === \"cost\") return estimates ? spend(row.totals) : row.totals.cost\n if (sort === \"tokens\") return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning\n return row.endAt ?? 0\n }\n return [...rows].sort((left, right) => sign * (pick(right) - pick(left)))\n}\n\n// ---------------------------------------------------------------------------\n// Small derived series\n// ---------------------------------------------------------------------------\n\n/** Token reuse per model, for the models view and the cache view. */\nexport function cacheByModel(pairs: readonly PairRow[]): Map<string, CacheStats> {\n const map = new Map<string, CacheStats>()\n for (const row of cacheStatsByModel(pairs)) {\n map.set(modelKey(row.modelID, row.variant), row.cache)\n }\n return map\n}\n\n/** The switch summary per `modelKey`, as the models view reads it. */\nexport function switchesByModel(rows: readonly SwitchRow[]): Map<string, SwitchRow> {\n return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]))\n}\n\n/** The cache table of the cache view: the models holding the most cache. */\nfunction topCacheModels(pairs: readonly PairRow[]): CacheModelRow[] {\n return cacheStatsByModel(pairs)\n .slice(0, 10)\n .map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }))\n}\n\n/**\n * Steps per bucket for the overview sparkline. The bucket size is chosen so a\n * range reads as roughly 48 bars, and always from a fixed ladder so the axis is\n * stable between refreshes.\n */\nfunction activityOf(\n db: Database,\n range: { from?: number | undefined; to?: number | undefined } | undefined,\n filters: Filters | undefined,\n now: number,\n): number[] {\n // The sparkline is part of the filtered overview: a session or model view\n // must not draw the activity of every other session. The range and filters\n // are the same ones the step aggregates use.\n const filter = buildWhere(range, filters, STEP_TIME)\n // All time has no lower bound: span the filtered window instead of starting\n // at the epoch, or the sparkline would be one bar of data and 46 of nothing.\n const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params) as {\n at: number | null\n } | null\n const from = range?.from ?? earliest?.at ?? 0\n const to = range?.to ?? now\n const span = Math.max(1, to - from)\n const ladder = [3_600_000, 3 * 3_600_000, 6 * 3_600_000, 12 * 3_600_000, 86_400_000, 3 * 86_400_000, 7 * 86_400_000, 30 * 86_400_000]\n const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1]!\n const rows = db\n .query(\n `SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps\n FROM steps ${filter.where}\n GROUP BY bucket ORDER BY bucket`,\n )\n .all(bucket, ...filter.params) as { bucket: number; steps: number }[]\n if (rows.length === 0) return []\n const first = Math.floor(from / bucket)\n const last = rows[rows.length - 1]!.bucket\n const series: number[] = []\n for (let index = first; index <= last; index += 1) {\n series.push(rows.find((row) => row.bucket === index)?.steps ?? 0)\n }\n return series\n}\n",
16
21
  "/**\n * List-price arithmetic for models the host reported as costing nothing.\n *\n * Prices come from the running OpenCode catalog (`ModelInfo.cost`) and are\n * expressed in USD per 1,000,000 tokens. This module mirrors the host's own\n * fallback exactly, so an estimate for a step reproduces what OpenCode would\n * have recorded before a provider started reporting `cost: 0`.\n *\n * Everything here takes plain objects: no host imports, so the rule can be\n * tested and reused by the recorder, the TUI line and the maintenance action.\n */\n\nexport type CostLike = {\n tier?: { type?: string | undefined; size?: number | undefined } | undefined\n input?: number | undefined\n output?: number | undefined\n cache?: { read?: number | undefined; write?: number | undefined } | undefined\n}\n\n/** The part of `ModelInfo` pricing needs, structurally. */\nexport type ModelInfoLike = {\n providerID?: string | undefined\n modelID?: string | undefined\n id?: string | undefined\n cost?: readonly CostLike[] | undefined\n}\n\nexport type PriceTier = {\n /** Present only on a context-tiered price; an untiered price has no tier. */\n tier?: { type?: string | undefined; size: number } | undefined\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n}\n\nexport type ModelPrice = {\n tiers: PriceTier[]\n}\n\n/** `providerID/modelID` to its prices. */\nexport type PriceTable = Map<string, ModelPrice>\n\nexport type PriceRef = {\n providerID?: string | undefined\n modelID?: string | undefined\n}\n\nexport type PriceTokens = {\n input?: number | undefined\n output?: number | undefined\n reasoning?: number | undefined\n cacheRead?: number | undefined\n cacheWrite?: number | undefined\n}\n\n/** The estimate callback the recorder and the live line share. */\nexport type PriceFn = (ref: PriceRef, tokens: PriceTokens) => number | undefined\n\nfunction money(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : 0\n}\n\nfunction tokens(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, value) : 0\n}\n\n/** Build the price table from the catalog the host exposes. */\nexport function priceTable(models: readonly ModelInfoLike[] | undefined): PriceTable {\n const table: PriceTable = new Map()\n if (!Array.isArray(models)) return table\n\n for (const model of models) {\n if (model === null || model === undefined) continue\n const providerID = model.providerID\n const modelID = model.modelID ?? model.id\n if (typeof providerID !== \"string\" || providerID === \"\") continue\n if (typeof modelID !== \"string\" || modelID === \"\") continue\n if (!Array.isArray(model.cost) || model.cost.length === 0) continue\n\n const tiers: PriceTier[] = []\n for (const cost of model.cost) {\n if (cost === null || cost === undefined) continue\n let tier: PriceTier[\"tier\"]\n if (cost.tier !== undefined) {\n const size = cost.tier.size\n // A tier without a usable size is not a base price: the host finds no\n // applicable entry for it and records zero. Treating it as the untiered\n // fallback would invent a price. Only an entry with no `tier` at all is\n // the base price. A negative size is kept: the host compares against it\n // like any other number, so mirroring the comparison is the honest\n // behaviour even though a real catalog never produces one.\n if (typeof size !== \"number\" || !Number.isFinite(size)) continue\n tier = { ...(cost.tier.type !== undefined ? { type: cost.tier.type } : {}), size }\n }\n tiers.push({\n ...(tier !== undefined ? { tier } : {}),\n input: money(cost.input),\n output: money(cost.output),\n cacheRead: money(cost.cache?.read),\n cacheWrite: money(cost.cache?.write),\n })\n }\n if (tiers.length > 0) table.set(`${providerID}/${modelID}`, { tiers })\n }\n return table\n}\n\nexport function priceOf(table: PriceTable, ref: PriceRef): ModelPrice | undefined {\n if (ref.providerID === undefined || ref.providerID === \"\") return undefined\n if (ref.modelID === undefined || ref.modelID === \"\") return undefined\n return table.get(`${ref.providerID}/${ref.modelID}`)\n}\n\n/**\n * The list price of one step, or undefined when there is nothing to show.\n *\n * The rule is the host's `cost` fallback: the prompt is fresh input plus cache\n * reads and writes; the tier that applies is the largest context tier the\n * prompt is strictly above; otherwise the untiered price. A known model whose\n * applicable prices are all zero returns `0` (free, not an estimate); an\n * unknown model or no applicable tier returns `undefined`.\n */\nexport function costOf(table: PriceTable, ref: PriceRef, usage: PriceTokens): number | undefined {\n const price = priceOf(table, ref)\n if (price === undefined) return undefined\n\n const input = tokens(usage.input)\n const output = tokens(usage.output)\n const reasoning = tokens(usage.reasoning)\n const cacheRead = tokens(usage.cacheRead)\n const cacheWrite = tokens(usage.cacheWrite)\n const prompt = input + cacheRead + cacheWrite\n\n const selected =\n price.tiers\n .filter((tier) => tier.tier?.type === \"context\" && prompt > tier.tier.size)\n .sort((left, right) => (right.tier?.size ?? 0) - (left.tier?.size ?? 0))[0] ??\n price.tiers.find((tier) => tier.tier === undefined)\n if (selected === undefined) return undefined\n\n // A model known to be free is not an unknown price: storing 0 keeps it out\n // of the backfill's \"needs an estimate\" set without inventing money.\n if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0) return 0\n\n const billed =\n input * selected.input +\n (output + reasoning) * selected.output +\n cacheRead * selected.cacheRead +\n cacheWrite * selected.cacheWrite\n if (!Number.isFinite(billed) || billed <= 0) return undefined\n return billed / 1_000_000\n}\n",
17
- "import type { Database } from \"bun:sqlite\"\nimport { statSync } from \"node:fs\"\nimport type { PriceRef, PriceTokens } from \"../pricing\"\nimport { TABLES, type TableName } from \"./db\"\n\n/**\n * Database maintenance: what the file holds, how much of it is worth keeping,\n * and the two operations that give the space back.\n *\n * Everything is explicit — nothing here runs on its own. The panel's `db` view\n * and `bun run report` are the only callers.\n */\n\nexport type TableSize = {\n name: string\n rows: number\n}\n\nexport type DbInfo = {\n path: string\n /** Size of the database file, in bytes. */\n bytes: number\n /** Size of its write-ahead log, when one exists. */\n walBytes: number | undefined\n schemaVersion: number\n tables: TableSize[]\n /** Oldest and newest recorded step, the window the views can answer for. */\n firstAt: number | undefined\n lastAt: number | undefined\n /** Steps a prune at each cutoff would remove, for the panel to offer choices. */\n removable: Array<{ days: number; steps: number }>\n /** Steps at $0 with a model identity and no list-price estimate yet. */\n unpriced: number\n}\n\nconst STEP_TIME = \"COALESCE(created_at, recorded_at)\"\nconst DAY = 24 * 60 * 60 * 1000\n\nfunction size(path: string): number {\n try {\n return statSync(path).size\n } catch {\n return 0\n }\n}\n\n/** True when the database carries a table, without throwing on an older file. */\nfunction hasTable(db: Database, name: string): boolean {\n try {\n return db.query(\"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\").get(name) !== null\n } catch {\n return false\n }\n}\n\nexport function dbInfo(db: Database, path: string, now = Date.now()): DbInfo {\n const tables: TableSize[] = TABLES.map((table) => ({\n name: table,\n // A reader can meet a database the recorder has not upgraded yet; a missing\n // table is zero rows, not a panel that cannot open.\n rows: hasTable(db, table) ? (db.query(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n : 0,\n }))\n const window = db.query(`SELECT MIN(${STEP_TIME}) AS first, MAX(${STEP_TIME}) AS last FROM steps`).get() as {\n first: number | null\n last: number | null\n }\n const version = db.query(\"SELECT value FROM meta WHERE key = 'schema_version'\").get() as { value: string } | null\n return {\n path,\n unpriced: hasListCost(db)\n ? (db.query(\n `SELECT COUNT(*) AS n FROM steps\n WHERE cost = 0 AND list_cost IS NULL\n AND provider_id IS NOT NULL AND provider_id <> ''\n AND model_id IS NOT NULL AND model_id <> ''\n AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`,\n ).get() as { n: number }).n\n : 0,\n bytes: size(path),\n walBytes: path === \":memory:\" ? undefined : size(`${path}-wal`) || undefined,\n schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),\n tables,\n firstAt: window.first ?? undefined,\n lastAt: window.last ?? undefined,\n removable: [30, 90, 365].map((days) => ({\n days,\n steps: (db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${STEP_TIME} < ?`).get(now - days * DAY) as { n: number }).n,\n })),\n }\n}\n\nexport type PruneResult = {\n steps: number\n prompts: number\n events: number\n /** Compaction/title usage records deleted with the steps they belong to. */\n usage: number\n}\n\nexport type WipeResult = PruneResult & {\n /** Session headings, which a wipe removes with the history they describe. */\n sessions: number\n}\n\n/**\n * Rows deleted per transaction. A single delete of a long history holds the\n * write lock for the whole scan — measured at 1.3 s for 123k steps — and the\n * recorder writes on the agent's event path, so it would wait that long. In\n * batches the lock is taken and released per batch and the recorder\n * interleaves. Each batch is atomic; the prune as a whole is not, which is\n * fine for \"delete what is older than this\": a prune that is interrupted\n * leaves fewer rows deleted, and the next one finishes the job.\n */\nconst PRUNE_BATCH = 5_000\n\nfunction deleteBatched(db: Database, table: \"steps\" | \"prompts\" | \"events\" | \"usage\", where: string, cutoff: number): number {\n // Table names and the WHERE clause are constants of this module: no value\n // from outside is ever interpolated into the statement.\n const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`)\n let removed = 0\n for (;;) {\n const changes = statement.run(cutoff).changes\n removed += changes\n if (changes < PRUNE_BATCH) break\n }\n return removed\n}\n\n/** Delete every row of `table`, one bounded batch at a time. */\nfunction deleteAllBatched(db: Database, table: TableName): number {\n const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} LIMIT ${PRUNE_BATCH})`)\n let removed = 0\n for (;;) {\n const changes = statement.run().changes\n removed += changes\n if (changes < PRUNE_BATCH) break\n }\n return removed\n}\n\n/**\n * Delete recorded usage older than `cutoff`. Steps, their prompts and the\n * compaction events that explain their cache losses go together: a compaction\n * that no step references answers nothing.\n */\nexport function pruneOlderThan(db: Database, cutoff: number): PruneResult {\n return {\n steps: deleteBatched(db, \"steps\", `${STEP_TIME} < ?`, cutoff),\n prompts: deleteBatched(db, \"prompts\", \"created_at IS NOT NULL AND created_at < ?\", cutoff),\n events: deleteBatched(db, \"events\", \"at IS NOT NULL AND at < ?\", cutoff),\n usage: hasTable(db, \"usage\") ? deleteBatched(db, \"usage\", \"at IS NOT NULL AND at < ?\", cutoff) : 0,\n }\n}\n\n/**\n * Delete every recorded row, keeping only the schema metadata. Sessions go\n * with the history they describe: a session with no step is a heading no view\n * can explain. Batched like a prune, so the recorder can interleave.\n */\nexport function wipeAll(db: Database): WipeResult {\n return {\n steps: deleteAllBatched(db, \"steps\"),\n prompts: deleteAllBatched(db, \"prompts\"),\n events: deleteAllBatched(db, \"events\"),\n usage: hasTable(db, \"usage\") ? deleteAllBatched(db, \"usage\") : 0,\n sessions: hasTable(db, \"sessions\") ? deleteAllBatched(db, \"sessions\") : 0,\n }\n}\n\n/** Everything the database occupies: the main file plus its write-ahead log. */\nfunction footprint(path: string): number {\n return size(path) + size(`${path}-wal`)\n}\n\n/** Reclaim the space a prune freed. Returns the bytes the database lost. */\nexport function vacuum(db: Database, path: string): { before: number; after: number; freed: number } {\n const before = footprint(path)\n // A checkpoint first: with WAL the freed pages live in the log until the\n // database is written back into the main file.\n db.exec(\"PRAGMA wal_checkpoint(TRUNCATE)\")\n db.exec(\"VACUUM\")\n const after = footprint(path)\n return { before, after, freed: Math.max(0, before - after) }\n}\n\n/** True when the database carries the list-price column. */\nexport function hasListCost(db: Database): boolean {\n try {\n return (db.query(\"PRAGMA table_info(steps)\").all() as { name: string }[]).some((column) => column.name === \"list_cost\")\n } catch {\n return false\n }\n}\n\nexport type BackfillResult = {\n /** Steps that matched the `cost = 0 AND list_cost IS NULL` condition. */\n candidates: number\n /** Steps a price was known for and written. */\n updated: number\n}\n\n/** Rows per write transaction: a long backfill must not hold the recorder up. */\nconst BACKFILL_BATCH = 1_000\n\n/**\n * Price historical steps the host recorded at $0. The price is today's catalog,\n * not the one in force when the step ran, so this is explicitly user-triggered.\n * A step whose model has no price is left NULL for a later run.\n */\nexport function backfillListCost(\n db: Database,\n price: (ref: PriceRef, tokens: PriceTokens) => number | undefined,\n): BackfillResult {\n if (!hasListCost(db)) return { candidates: 0, updated: 0 }\n const candidates = (db.query(\n `SELECT COUNT(*) AS n FROM steps\n WHERE cost = 0 AND list_cost IS NULL\n AND provider_id IS NOT NULL AND provider_id <> ''\n AND model_id IS NOT NULL AND model_id <> ''\n AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`,\n ).get() as { n: number }).n\n if (candidates === 0) return { candidates: 0, updated: 0 }\n\n const select = db.query(\n `SELECT rowid, provider_id, model_id,\n input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write\n FROM steps\n WHERE cost = 0 AND list_cost IS NULL AND rowid > ?\n AND provider_id IS NOT NULL AND provider_id <> ''\n AND model_id IS NOT NULL AND model_id <> ''\n AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0\n ORDER BY rowid\n LIMIT ?`,\n )\n const update = db.query(\"UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL\")\n let cursor = 0\n let updated = 0\n\n for (;;) {\n const rows = select.all(cursor, BACKFILL_BATCH) as Array<{\n rowid: number\n provider_id: string | null\n model_id: string | null\n input_tokens: number | null\n output_tokens: number | null\n reasoning_tokens: number | null\n cache_read: number | null\n cache_write: number | null\n }>\n if (rows.length === 0) break\n db.transaction(() => {\n for (const row of rows) {\n const estimate = price(\n { providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined },\n {\n input: row.input_tokens ?? 0,\n output: row.output_tokens ?? 0,\n reasoning: row.reasoning_tokens ?? 0,\n cacheRead: row.cache_read ?? 0,\n cacheWrite: row.cache_write ?? 0,\n },\n )\n if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0) continue\n if (update.run(estimate, row.rowid).changes > 0) updated += 1\n }\n })()\n cursor = rows[rows.length - 1]!.rowid\n if (rows.length < BACKFILL_BATCH) break\n }\n\n return { candidates, updated }\n}\n\nexport type { TableName }\n",
22
+ "import type { Database } from \"bun:sqlite\"\nimport { statSync } from \"node:fs\"\nimport type { PriceRef, PriceTokens } from \"../pricing\"\nimport { hasTable, TABLES, type TableName } from \"./db\"\n\n/**\n * Database maintenance: what the file holds, how much of it is worth keeping,\n * and the two operations that give the space back.\n *\n * Everything is explicit — nothing here runs on its own. The panel's `db` view\n * and `bun run report` are the only callers.\n */\n\nexport type TableSize = {\n name: string\n rows: number\n}\n\nexport type DbInfo = {\n path: string\n /** Size of the database file, in bytes. */\n bytes: number\n /** Size of its write-ahead log, when one exists. */\n walBytes: number | undefined\n schemaVersion: number\n tables: TableSize[]\n /** Oldest and newest recorded step, the window the views can answer for. */\n firstAt: number | undefined\n lastAt: number | undefined\n /** Steps a prune at each cutoff would remove, for the panel to offer choices. */\n removable: Array<{ days: number; steps: number }>\n /** Steps at $0 with a model identity and no list-price estimate yet. */\n unpriced: number\n}\n\nconst STEP_TIME = \"COALESCE(created_at, recorded_at)\"\nconst DAY = 24 * 60 * 60 * 1000\n\nfunction size(path: string): number {\n try {\n return statSync(path).size\n } catch {\n return 0\n }\n}\n\nexport function dbInfo(db: Database, path: string, now = Date.now()): DbInfo {\n const tables: TableSize[] = TABLES.map((table) => ({\n name: table,\n // A reader can meet a database the recorder has not upgraded yet; a missing\n // table is zero rows, not a panel that cannot open.\n rows: hasTable(db, table) ? (db.query(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n : 0,\n }))\n const window = db.query(`SELECT MIN(${STEP_TIME}) AS first, MAX(${STEP_TIME}) AS last FROM steps`).get() as {\n first: number | null\n last: number | null\n }\n const version = db.query(\"SELECT value FROM meta WHERE key = 'schema_version'\").get() as { value: string } | null\n return {\n path,\n unpriced: hasListCost(db)\n ? (db.query(\n `SELECT COUNT(*) AS n FROM steps\n WHERE cost = 0 AND list_cost IS NULL\n AND provider_id IS NOT NULL AND provider_id <> ''\n AND model_id IS NOT NULL AND model_id <> ''\n AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`,\n ).get() as { n: number }).n\n : 0,\n bytes: size(path),\n walBytes: path === \":memory:\" ? undefined : size(`${path}-wal`) || undefined,\n schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),\n tables,\n firstAt: window.first ?? undefined,\n lastAt: window.last ?? undefined,\n removable: [30, 90, 365].map((days) => ({\n days,\n steps: (db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${STEP_TIME} < ?`).get(now - days * DAY) as { n: number }).n,\n })),\n }\n}\n\nexport type PruneResult = {\n steps: number\n prompts: number\n compactions: number\n /** Compaction/title usage records deleted with the steps they belong to. */\n usage: number\n}\n\nexport type WipeResult = PruneResult & {\n /** Session headings, which a wipe removes with the history they describe. */\n sessions: number\n}\n\n/**\n * Rows deleted per transaction. A single delete of a long history holds the\n * write lock for the whole scan — measured at 1.3 s for 123k steps — and the\n * recorder writes on the agent's event path, so it would wait that long. In\n * batches the lock is taken and released per batch and the recorder\n * interleaves. Each batch is atomic; the prune as a whole is not, which is\n * fine for \"delete what is older than this\": a prune that is interrupted\n * leaves fewer rows deleted, and the next one finishes the job.\n */\nconst PRUNE_BATCH = 5_000\n\nfunction deleteBatched(db: Database, table: TableName, where: string, cutoff: number): number {\n // Table names and the WHERE clause are constants of this module: no value\n // from outside is ever interpolated into the statement.\n const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`)\n let removed = 0\n for (;;) {\n const changes = statement.run(cutoff).changes\n removed += changes\n if (changes < PRUNE_BATCH) break\n }\n return removed\n}\n\n/** Delete every row of `table`, one bounded batch at a time. */\nfunction deleteAllBatched(db: Database, table: TableName): number {\n const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} LIMIT ${PRUNE_BATCH})`)\n let removed = 0\n for (;;) {\n const changes = statement.run().changes\n removed += changes\n if (changes < PRUNE_BATCH) break\n }\n return removed\n}\n\n/**\n * Delete recorded usage older than `cutoff`. Steps, their prompts and the\n * compaction events that explain their cache losses go together: a compaction\n * that no step references answers nothing.\n */\nexport function pruneOlderThan(db: Database, cutoff: number): PruneResult {\n return {\n steps: deleteBatched(db, \"steps\", `${STEP_TIME} < ?`, cutoff),\n prompts: deleteBatched(db, \"prompts\", \"created_at IS NOT NULL AND created_at < ?\", cutoff),\n compactions: deleteBatched(db, \"compactions\", \"at IS NOT NULL AND at < ?\", cutoff),\n usage: hasTable(db, \"usage\") ? deleteBatched(db, \"usage\", \"at IS NOT NULL AND at < ?\", cutoff) : 0,\n }\n}\n\n/**\n * Delete every recorded row, keeping only the schema metadata. Sessions go\n * with the history they describe: a session with no step is a heading no view\n * can explain. Batched like a prune, so the recorder can interleave.\n */\nexport function wipeAll(db: Database): WipeResult {\n return {\n steps: deleteAllBatched(db, \"steps\"),\n prompts: deleteAllBatched(db, \"prompts\"),\n compactions: deleteAllBatched(db, \"compactions\"),\n usage: hasTable(db, \"usage\") ? deleteAllBatched(db, \"usage\") : 0,\n sessions: hasTable(db, \"sessions\") ? deleteAllBatched(db, \"sessions\") : 0,\n }\n}\n\n/** Everything the database occupies: the main file plus its write-ahead log. */\nfunction footprint(path: string): number {\n return size(path) + size(`${path}-wal`)\n}\n\n/** Reclaim the space a prune freed. Returns the bytes the database lost. */\nexport function vacuum(db: Database, path: string): { before: number; after: number; freed: number } {\n const before = footprint(path)\n // A checkpoint first: with WAL the freed pages live in the log until the\n // database is written back into the main file.\n db.exec(\"PRAGMA wal_checkpoint(TRUNCATE)\")\n db.exec(\"VACUUM\")\n const after = footprint(path)\n return { before, after, freed: Math.max(0, before - after) }\n}\n\n/** True when the database carries the list-price column. */\nexport function hasListCost(db: Database): boolean {\n try {\n return (db.query(\"PRAGMA table_info(steps)\").all() as { name: string }[]).some((column) => column.name === \"list_cost\")\n } catch {\n return false\n }\n}\n\nexport type BackfillResult = {\n /** Steps that matched the `cost = 0 AND list_cost IS NULL` condition. */\n candidates: number\n /** Steps a price was known for and written. */\n updated: number\n}\n\n/** Rows per write transaction: a long backfill must not hold the recorder up. */\nconst BACKFILL_BATCH = 1_000\n\n/** The rows a list-price backfill can price: $0, no estimate, real usage. */\nconst UNPRICED_WHERE = `cost = 0 AND list_cost IS NULL\n AND provider_id IS NOT NULL AND provider_id <> ''\n AND model_id IS NOT NULL AND model_id <> ''\n AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`\n\ntype BackfillStep = {\n rowid: number\n provider_id: string | null\n model_id: string | null\n input_tokens: number | null\n output_tokens: number | null\n reasoning_tokens: number | null\n cache_read: number | null\n cache_write: number | null\n}\n\nfunction priceStep(step: BackfillStep, price: (ref: PriceRef, tokens: PriceTokens) => number | undefined): number | undefined {\n const estimate = price(\n { providerID: step.provider_id ?? undefined, modelID: step.model_id ?? undefined },\n {\n input: step.input_tokens ?? 0,\n output: step.output_tokens ?? 0,\n reasoning: step.reasoning_tokens ?? 0,\n cacheRead: step.cache_read ?? 0,\n cacheWrite: step.cache_write ?? 0,\n },\n )\n return estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined\n}\n\n/** Price one batch inside its own transaction and return how many rows changed. */\nfunction backfillBatch(\n db: Database,\n rows: readonly BackfillStep[],\n price: (ref: PriceRef, tokens: PriceTokens) => number | undefined,\n update: (estimate: number, rowid: number) => number,\n): number {\n let updated = 0\n db.transaction(() => {\n for (const row of rows) {\n const estimate = priceStep(row, price)\n if (estimate !== undefined && update(estimate, row.rowid) > 0) updated += 1\n }\n })()\n return updated\n}\n\n/**\n * Price historical steps the host recorded at $0. The price is today's catalog,\n * not the one in force when the step ran, so this is explicitly user-triggered.\n * A step whose model has no price is left NULL for a later run.\n */\nexport function backfillListCost(\n db: Database,\n price: (ref: PriceRef, tokens: PriceTokens) => number | undefined,\n): BackfillResult {\n if (!hasListCost(db)) return { candidates: 0, updated: 0 }\n const candidates = (db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${UNPRICED_WHERE}`).get() as { n: number }).n\n if (candidates === 0) return { candidates: 0, updated: 0 }\n\n const select = db.query(\n `SELECT rowid, provider_id, model_id,\n input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write\n FROM steps\n WHERE ${UNPRICED_WHERE} AND rowid > ?\n ORDER BY rowid\n LIMIT ?`,\n )\n const update = db.query(\"UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL\")\n let cursor = 0\n let updated = 0\n\n for (;;) {\n const rows = select.all(cursor, BACKFILL_BATCH) as BackfillStep[]\n if (rows.length === 0) break\n updated += backfillBatch(db, rows, price, (estimate, rowid) => update.run(estimate, rowid).changes)\n cursor = rows[rows.length - 1]!.rowid\n if (rows.length < BACKFILL_BATCH) break\n }\n\n return { candidates, updated }\n}\n\nexport type { TableName }\n",
18
23
  "import type { Database } from \"bun:sqlite\"\nimport { openStatsDbReadOnly } from \"./stats/db\"\nimport { createService, ServiceError, type ServiceOptions } from \"./service\"\nimport type {\n BackfillInput,\n PanelInput,\n PruneInput,\n TurnsInput,\n VacuumInput,\n WipeInput,\n} from \"./rpc\"\nimport type { ModelPrice, PriceTable } from \"./pricing\"\n\n/**\n * The database worker. It owns the read-only SQLite connection and runs the\n * panel queries, the turn history and the optional maintenance writes away\n * from the server's event loop. The server speaks to it through\n * `stats-client.ts`; the protocol is private to the plugin.\n */\n\ntype WorkerInit = {\n type: \"init\"\n dbPath: string\n options: Omit<ServiceOptions, \"path\" | \"priceTable\">\n}\n\ntype WorkerRequest = {\n id: number\n method: \"panel\" | \"turns\" | \"listCost\" | \"filters\" | \"dbInfo\" | \"prune\" | \"wipe\" | \"vacuum\" | \"backfill\"\n input: unknown\n /** Serialized catalog for a backfill; undefined for every other method. */\n prices?: [string, ModelPrice][] | undefined\n}\n\ntype WorkerMessage = WorkerInit | WorkerRequest\n\ntype WorkerResponse =\n | { type: \"ready\" }\n | { type: \"error\"; error: { code: string; message: string } }\n | { id: number; ok: true; result: unknown }\n | { id: number; ok: false; error: { code: string; message: string } }\n\ntype WorkerScope = {\n onmessage: ((event: MessageEvent<WorkerMessage>) => void) | null\n postMessage: (message: WorkerResponse) => void\n}\n\nconst scope = globalThis as unknown as WorkerScope\n\nlet dbPath: string | undefined\nlet readDb: Database | undefined\nlet service: ReturnType<typeof createService> | undefined\n\nfunction read(): Database {\n if (readDb === undefined) {\n if (dbPath === undefined) throw new ServiceError(\"unavailable\", \"the usage database is not configured\")\n readDb = openStatsDbReadOnly(dbPath)\n }\n return readDb\n}\n\nfunction closeRead(): void {\n readDb?.close()\n readDb = undefined\n}\n\nfunction reopen(): void {\n try {\n read()\n } catch {\n // A missing database is reported by the next read; nothing to do here.\n }\n}\n\nfunction serializedPrices(entries: [string, ModelPrice][] | undefined): PriceTable | undefined {\n if (entries === undefined) return undefined\n return new Map(entries)\n}\n\nfunction run(request: WorkerRequest): unknown {\n if (service === undefined) throw new ServiceError(\"unavailable\", \"the usage worker is not initialized\")\n const maintenance = request.method === \"prune\" || request.method === \"wipe\" || request.method === \"vacuum\" || request.method === \"backfill\"\n if (maintenance) closeRead()\n try {\n switch (request.method) {\n case \"panel\":\n return service.panel(request.input as PanelInput)\n case \"turns\":\n return service.turnHistory(request.input as TurnsInput)\n case \"listCost\":\n return service.listCost(request.input as { sessionID: string })\n case \"filters\":\n return service.filters()\n case \"dbInfo\":\n return service.dbInfo()\n case \"prune\":\n return service.prune(request.input as PruneInput)\n case \"wipe\":\n return service.wipe(request.input as WipeInput)\n case \"vacuum\":\n return service.compact(request.input as VacuumInput)\n case \"backfill\":\n return service.backfill(request.input as BackfillInput, serializedPrices(request.prices))\n }\n } finally {\n if (maintenance) reopen()\n }\n}\n\nfunction failure(error: unknown): { code: string; message: string } {\n if (error instanceof ServiceError) return { code: error.code, message: error.message }\n return { code: \"unavailable\", message: \"the usage database is unavailable\" }\n}\n\nscope.onmessage = (event) => {\n const message = event.data\n\n if (\"type\" in message && message.type === \"init\") {\n dbPath = message.dbPath\n service = createService(read, { ...message.options, path: message.dbPath })\n closeRead()\n try {\n read()\n scope.postMessage({ type: \"ready\" })\n } catch (error) {\n scope.postMessage({ type: \"error\", error: failure(error) })\n }\n return\n }\n\n const request = message as WorkerRequest\n try {\n const result = run(request)\n scope.postMessage({ id: request.id, ok: true, result })\n } catch (error) {\n scope.postMessage({ id: request.id, ok: false, error: failure(error) })\n }\n}\n"
19
24
  ],
20
- "mappings": ";;AAAA;AACA;AACA;;;ACFA;AACA;AACA;AAiBO,SAAS,aAAa,CAAC,MAA0C,QAAQ,KAAK,WAAmB,QAAQ,UAAkB;AAAA,EAChI,MAAM,OAAO,KAAK,YAAY,2BAA2B,UAAU;AAAA,EACnE,IAAI,aAAa,SAAS;AAAA,IACxB,OAAO,KAAK,IAAI,gBAAgB,KAAK,QAAQ,GAAG,WAAW,OAAO,GAAG,IAAI;AAAA,EAC3E;AAAA,EACA,IAAI,aAAa,UAAU;AAAA,IACzB,OAAO,KAAK,QAAQ,GAAG,WAAW,uBAAuB,IAAI;AAAA,EAC/D;AAAA,EACA,OAAO,KAAK,IAAI,kBAAkB,KAAK,QAAQ,GAAG,UAAU,OAAO,GAAG,IAAI;AAAA;AAOrE,SAAS,UAAU,CAAC,MAAc,OAAe,QAAQ,GAAW;AAAA,EACzE,IAAI,SAAS;AAAA,IAAK,OAAO;AAAA,EACzB,IAAI,KAAK,WAAW,IAAI,KAAK,KAAK,WAAW,KAAK;AAAA,IAAG,OAAO,KAAK,MAAM,KAAK,MAAM,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