opencode-usage-insights 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3697 @@
1
+ // @bun
2
+ // src/stats/db.ts
3
+ import { Database } from "bun:sqlite";
4
+ import { chmodSync, mkdirSync } from "fs";
5
+ import { dirname } from "path";
6
+
7
+ // src/stats/paths.ts
8
+ import { homedir } from "os";
9
+ import { join } from "path";
10
+ import { statSync } from "fs";
11
+ function defaultDbPath(env = process.env, platform = process.platform) {
12
+ const name = join("opencode", "opencode-usage-insights", "usage.db");
13
+ if (platform === "win32") {
14
+ return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
15
+ }
16
+ if (platform === "darwin") {
17
+ return join(homedir(), "Library", "Application Support", name);
18
+ }
19
+ return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
20
+ }
21
+ function expandHome(path, home = homedir()) {
22
+ if (path === "~")
23
+ return home;
24
+ if (path.startsWith("~/") || path.startsWith("~\\"))
25
+ return join(home, path.slice(2));
26
+ return path;
27
+ }
28
+ function resolveDbPath(configured, env = process.env, platform = process.platform) {
29
+ const home = env.HOME ?? env.USERPROFILE ?? homedir();
30
+ if (configured)
31
+ return expandHome(configured, home);
32
+ if (env.OPENCODE_USAGE_INSIGHTS_DB)
33
+ return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
34
+ return defaultDbPath(env, platform);
35
+ }
36
+ function ensureRegularFile(path) {
37
+ let stats;
38
+ try {
39
+ stats = statSync(path);
40
+ } catch {
41
+ return;
42
+ }
43
+ if (!stats.isFile())
44
+ throw new Error(`not a regular file: ${path}`);
45
+ }
46
+
47
+ // src/text.ts
48
+ var TEXT_LIMIT = 512;
49
+ function sanitizeText(value, limit = TEXT_LIMIT) {
50
+ if (limit <= 0)
51
+ return "";
52
+ let cleaned = "";
53
+ for (const character of value) {
54
+ const code = character.codePointAt(0) ?? 0;
55
+ if (code <= 31 || code === 127 || code >= 128 && code <= 159)
56
+ continue;
57
+ cleaned += character;
58
+ if (cleaned.length >= limit)
59
+ break;
60
+ }
61
+ return cleaned;
62
+ }
63
+ function sanitizeLabel(value, limit = TEXT_LIMIT) {
64
+ return sanitizeText(value, limit).trim();
65
+ }
66
+ var TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
67
+ function isToken(value, limit = 64) {
68
+ return value.length > 0 && value.length <= limit && TOKEN.test(value);
69
+ }
70
+
71
+ // src/stats/db.ts
72
+ var SCHEMA_VERSION = 11;
73
+ var LABEL_LIMIT = 4 * TEXT_LIMIT;
74
+ var SCHEMA = `
75
+ CREATE TABLE IF NOT EXISTS meta (
76
+ key TEXT PRIMARY KEY,
77
+ value TEXT NOT NULL
78
+ );
79
+
80
+ CREATE TABLE IF NOT EXISTS sessions (
81
+ session_id TEXT PRIMARY KEY,
82
+ parent_id TEXT,
83
+ directory TEXT,
84
+ title TEXT,
85
+ started_at INTEGER,
86
+ updated_at INTEGER
87
+ );
88
+
89
+ CREATE TABLE IF NOT EXISTS prompts (
90
+ session_id TEXT NOT NULL,
91
+ message_id TEXT NOT NULL,
92
+ created_at INTEGER,
93
+ PRIMARY KEY (session_id, message_id)
94
+ );
95
+ CREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);
96
+
97
+ CREATE TABLE IF NOT EXISTS steps (
98
+ message_id TEXT PRIMARY KEY,
99
+ session_id TEXT NOT NULL,
100
+ parent_id TEXT,
101
+ provider_id TEXT,
102
+ model_id TEXT,
103
+ variant TEXT,
104
+ input_tokens INTEGER NOT NULL DEFAULT 0,
105
+ output_tokens INTEGER NOT NULL DEFAULT 0,
106
+ reasoning_tokens INTEGER NOT NULL DEFAULT 0,
107
+ cache_read INTEGER NOT NULL DEFAULT 0,
108
+ cache_write INTEGER NOT NULL DEFAULT 0,
109
+ cost REAL NOT NULL DEFAULT 0,
110
+ list_cost REAL,
111
+ created_at INTEGER,
112
+ streamed_at INTEGER,
113
+ completed_at INTEGER,
114
+ finish TEXT,
115
+ recorded_at INTEGER NOT NULL
116
+ );
117
+ CREATE INDEX IF NOT EXISTS steps_session ON steps(session_id, created_at);
118
+ CREATE INDEX IF NOT EXISTS steps_model ON steps(provider_id, model_id, variant);
119
+ CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
120
+ -- Every range filter and every ordering compares the step's own clock, which
121
+ -- falls back to the recording time for a step that was already in flight when
122
+ -- the plugin loaded. The index has to cover that expression, or every ranged
123
+ -- view is a full table scan.
124
+ CREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));
125
+ CREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));
126
+
127
+ CREATE TABLE IF NOT EXISTS events (
128
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
129
+ session_id TEXT NOT NULL,
130
+ kind TEXT NOT NULL,
131
+ message_id TEXT,
132
+ at INTEGER,
133
+ data TEXT
134
+ );
135
+ CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
136
+ CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
137
+
138
+ -- Usage the host reports with no assistant step of its own: the compaction
139
+ -- summarisation and the session-title generation. The host publishes it as
140
+ -- session.usage.recorded with a source other than generate, and includes it in
141
+ -- the session's own cost/token totals. Primary key is the host event ID, so a
142
+ -- replayed event never counts twice.
143
+ CREATE TABLE IF NOT EXISTS usage (
144
+ id TEXT PRIMARY KEY,
145
+ session_id TEXT NOT NULL,
146
+ source TEXT NOT NULL,
147
+ at INTEGER,
148
+ cost REAL NOT NULL DEFAULT 0,
149
+ input_tokens INTEGER NOT NULL DEFAULT 0,
150
+ output_tokens INTEGER NOT NULL DEFAULT 0,
151
+ reasoning_tokens INTEGER NOT NULL DEFAULT 0,
152
+ cache_read INTEGER NOT NULL DEFAULT 0,
153
+ cache_write INTEGER NOT NULL DEFAULT 0
154
+ );
155
+ CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
156
+ CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
157
+ `;
158
+ var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
159
+ function jsonText(value) {
160
+ if (value === undefined || value === null)
161
+ return null;
162
+ if (typeof value === "string")
163
+ return value;
164
+ try {
165
+ return JSON.stringify(value);
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+ function finite(value) {
171
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
172
+ }
173
+ function tokenCount(value) {
174
+ return Math.max(0, Math.floor(finite(value)));
175
+ }
176
+ function timestamp(value) {
177
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
178
+ }
179
+ var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
180
+ var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
181
+ function dropUnused(db) {
182
+ const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
183
+ const tables = new Set(objects.filter((row) => row.type === "table").map((row) => row.name));
184
+ const indexes = new Set(objects.filter((row) => row.type === "index").map((row) => row.name));
185
+ if (tables.has("http_responses"))
186
+ db.exec("DROP TABLE http_responses");
187
+ if (indexes.has("steps_upstream"))
188
+ db.exec("DROP INDEX steps_upstream");
189
+ if (indexes.has("steps_router"))
190
+ db.exec("DROP INDEX steps_router");
191
+ const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
192
+ for (const name of REMOVED_COLUMNS) {
193
+ if (columns.has(name))
194
+ db.exec(`ALTER TABLE steps DROP COLUMN ${name}`);
195
+ }
196
+ if (tables.has("events")) {
197
+ const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(", ");
198
+ db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
199
+ }
200
+ }
201
+ function addMissing(db) {
202
+ const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
203
+ if (columns.size > 0 && !columns.has("list_cost")) {
204
+ db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
205
+ }
206
+ }
207
+ function dedupeEvents(db) {
208
+ const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
209
+ if (table === null)
210
+ return;
211
+ db.exec(`DELETE FROM events
212
+ WHERE kind = 'compaction' AND message_id IS NULL
213
+ AND rowid NOT IN (
214
+ SELECT MIN(rowid) FROM events
215
+ WHERE kind = 'compaction' AND message_id IS NULL
216
+ GROUP BY session_id, at, data
217
+ )`);
218
+ db.exec(`DELETE FROM events
219
+ WHERE message_id IS NOT NULL
220
+ AND rowid NOT IN (
221
+ SELECT MIN(rowid) FROM events
222
+ WHERE message_id IS NOT NULL
223
+ GROUP BY kind, message_id
224
+ )`);
225
+ }
226
+ function addEventKey(db) {
227
+ const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
228
+ if (table === null)
229
+ return;
230
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
231
+ }
232
+ function backfillCompactionUsage(db) {
233
+ const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
234
+ if (!tables.has("events") || !tables.has("usage"))
235
+ return;
236
+ db.exec(`INSERT OR IGNORE INTO usage (
237
+ id, session_id, source, at, cost,
238
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
239
+ )
240
+ SELECT 'compaction:' || rowid, session_id, 'compaction', at,
241
+ MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
242
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
243
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
244
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
245
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
246
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
247
+ FROM events
248
+ WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
249
+ AND json_valid(data)`);
250
+ }
251
+ function migrate(db) {
252
+ dropUnused(db);
253
+ addMissing(db);
254
+ dedupeEvents(db);
255
+ backfillCompactionUsage(db);
256
+ addEventKey(db);
257
+ }
258
+ var POSIX = process.platform !== "win32";
259
+ function hardenDirectory(path) {
260
+ if (!POSIX)
261
+ return;
262
+ try {
263
+ chmodSync(path, 448);
264
+ } catch {}
265
+ }
266
+ function hardenFiles(path) {
267
+ if (!POSIX || path === ":memory:")
268
+ return;
269
+ for (const file of [path, `${path}-wal`, `${path}-shm`]) {
270
+ try {
271
+ chmodSync(file, 384);
272
+ } catch {}
273
+ }
274
+ }
275
+ function prepareDirectory(path) {
276
+ if (path === ":memory:")
277
+ return;
278
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
279
+ hardenDirectory(dirname(path));
280
+ }
281
+ function openStatsDb(path) {
282
+ if (path !== ":memory:")
283
+ ensureRegularFile(path);
284
+ prepareDirectory(path);
285
+ const db = new Database(path, { create: true });
286
+ db.exec("PRAGMA journal_mode = WAL");
287
+ db.exec("PRAGMA busy_timeout = 5000");
288
+ db.exec("PRAGMA synchronous = NORMAL");
289
+ db.exec(SCHEMA);
290
+ migrate(db);
291
+ db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
292
+ hardenFiles(path);
293
+ return db;
294
+ }
295
+ function openStatsDbReadOnly(path) {
296
+ ensureRegularFile(path);
297
+ const db = new Database(path, { readonly: true });
298
+ try {
299
+ db.query("SELECT 1 FROM steps LIMIT 1").get();
300
+ } catch (error) {
301
+ db.close();
302
+ throw error;
303
+ }
304
+ return db;
305
+ }
306
+ function openStatsDbWrite(path) {
307
+ if (path !== ":memory:")
308
+ ensureRegularFile(path);
309
+ prepareDirectory(path);
310
+ const db = new Database(path, { create: true });
311
+ db.exec("PRAGMA busy_timeout = 250");
312
+ db.exec("PRAGMA synchronous = NORMAL");
313
+ hardenFiles(path);
314
+ return db;
315
+ }
316
+ function recordStep(db, record) {
317
+ const cost = Math.max(0, finite(record.cost));
318
+ const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
319
+ db.query(`INSERT INTO steps (
320
+ message_id, session_id, parent_id, provider_id, model_id, variant,
321
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
322
+ created_at, streamed_at, completed_at, finish, recorded_at
323
+ ) VALUES (
324
+ $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
325
+ $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
326
+ $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
327
+ )
328
+ ON CONFLICT(message_id) DO UPDATE SET
329
+ session_id = excluded.session_id,
330
+ parent_id = COALESCE(excluded.parent_id, steps.parent_id),
331
+ provider_id = COALESCE(excluded.provider_id, steps.provider_id),
332
+ model_id = COALESCE(excluded.model_id, steps.model_id),
333
+ variant = COALESCE(excluded.variant, steps.variant),
334
+ input_tokens = excluded.input_tokens,
335
+ output_tokens = excluded.output_tokens,
336
+ reasoning_tokens = excluded.reasoning_tokens,
337
+ cache_read = excluded.cache_read,
338
+ cache_write = excluded.cache_write,
339
+ cost = excluded.cost,
340
+ -- A step that starts being charged loses its estimate; an estimate is
341
+ -- kept when a replayed event arrives without a price table.
342
+ list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
343
+ created_at = COALESCE(excluded.created_at, steps.created_at),
344
+ streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
345
+ completed_at = COALESCE(excluded.completed_at, steps.completed_at),
346
+ finish = COALESCE(excluded.finish, steps.finish),
347
+ recorded_at = excluded.recorded_at`).run({
348
+ $messageID: record.messageID,
349
+ $sessionID: record.sessionID,
350
+ $parentID: record.parentID ?? null,
351
+ $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
352
+ $modelID: record.modelID ?? null,
353
+ $variant: record.variant ?? null,
354
+ $input: tokenCount(record.input),
355
+ $output: tokenCount(record.output),
356
+ $reasoning: tokenCount(record.reasoning),
357
+ $cacheRead: tokenCount(record.cacheRead),
358
+ $cacheWrite: tokenCount(record.cacheWrite),
359
+ $cost: cost,
360
+ $listCost: listCost,
361
+ $createdAt: timestamp(record.createdAt),
362
+ $streamedAt: timestamp(record.streamedAt),
363
+ $completedAt: timestamp(record.completedAt),
364
+ $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
365
+ $recordedAt: timestamp(record.recordedAt) ?? Date.now()
366
+ });
367
+ }
368
+ function recordUsage(db, record) {
369
+ if (typeof record.id !== "string" || record.id === "")
370
+ return;
371
+ if (typeof record.sessionID !== "string" || record.sessionID === "")
372
+ return;
373
+ db.query(`INSERT INTO usage (
374
+ id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
375
+ ) VALUES (
376
+ $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
377
+ ) ON CONFLICT(id) DO NOTHING`).run({
378
+ $id: record.id,
379
+ $sessionID: record.sessionID,
380
+ $source: sanitizeLabel(record.source, 64),
381
+ $at: timestamp(record.at) ?? Date.now(),
382
+ $cost: Math.max(0, finite(record.cost)),
383
+ $input: tokenCount(record.input),
384
+ $output: tokenCount(record.output),
385
+ $reasoning: tokenCount(record.reasoning),
386
+ $cacheRead: tokenCount(record.cacheRead),
387
+ $cacheWrite: tokenCount(record.cacheWrite)
388
+ });
389
+ }
390
+ function recordPrompt(db, record) {
391
+ db.query(`INSERT INTO prompts (session_id, message_id, created_at)
392
+ VALUES ($sessionID, $messageID, $createdAt)
393
+ ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
394
+ $sessionID: record.sessionID,
395
+ $messageID: record.messageID,
396
+ $createdAt: timestamp(record.createdAt)
397
+ });
398
+ }
399
+ function recordEvent(db, record) {
400
+ db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
401
+ VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
402
+ $sessionID: record.sessionID,
403
+ $kind: sanitizeLabel(record.kind, 64),
404
+ $messageID: record.messageID ?? null,
405
+ $at: timestamp(record.at) ?? Date.now(),
406
+ $data: jsonText(record.data)
407
+ });
408
+ }
409
+ function upsertSession(db, record) {
410
+ db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at, updated_at)
411
+ VALUES ($sessionID, $parentID, $directory, $title, $startedAt, $updatedAt)
412
+ ON CONFLICT(session_id) DO UPDATE SET
413
+ parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
414
+ directory = COALESCE(excluded.directory, sessions.directory),
415
+ title = COALESCE(excluded.title, sessions.title),
416
+ started_at = COALESCE(sessions.started_at, excluded.started_at),
417
+ updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`).run({
418
+ $sessionID: record.sessionID,
419
+ $parentID: record.parentID ?? null,
420
+ $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
421
+ $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
422
+ $startedAt: timestamp(record.startedAt),
423
+ $updatedAt: timestamp(record.updatedAt)
424
+ });
425
+ }
426
+
427
+ // src/service.ts
428
+ import { basename } from "path";
429
+
430
+ // src/limits.ts
431
+ var MAX_PANEL_WIDTH = 200;
432
+ var MAX_TURNS = 50;
433
+ function clampPanelWidth(value) {
434
+ if (!Number.isFinite(value))
435
+ return 20;
436
+ return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
437
+ }
438
+ function clampTurnsLimit(value) {
439
+ if (!Number.isFinite(value))
440
+ return 1;
441
+ return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
442
+ }
443
+
444
+ // src/core.ts
445
+ var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
446
+ function transcriptTail(messages, count) {
447
+ const segments = [];
448
+ let current = [];
449
+ for (let index = messages.length - 1;index >= 0; index -= 1) {
450
+ const message = messages[index];
451
+ if (message.type === "assistant") {
452
+ current.unshift(message);
453
+ continue;
454
+ }
455
+ if (!PROMPT_BOUNDARIES.has(message.type))
456
+ continue;
457
+ if (current.length === 0)
458
+ continue;
459
+ segments.unshift({ assistants: current, prompt: message });
460
+ if (segments.length >= count)
461
+ return segments;
462
+ current = [];
463
+ }
464
+ if (current.length > 0 && segments.length < count)
465
+ segments.unshift({ assistants: current, prompt: undefined });
466
+ return segments;
467
+ }
468
+ function countOf(value) {
469
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
470
+ }
471
+ function amountOf(value) {
472
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
473
+ }
474
+ function stampOf(value) {
475
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
476
+ }
477
+ function tokenCounts(message) {
478
+ const tokens = message.tokens;
479
+ return {
480
+ input: countOf(tokens?.input),
481
+ output: countOf(tokens?.output),
482
+ reasoning: countOf(tokens?.reasoning),
483
+ read: countOf(tokens?.cache?.read),
484
+ write: countOf(tokens?.cache?.write)
485
+ };
486
+ }
487
+ function totalize(steps) {
488
+ const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
489
+ for (const step of steps) {
490
+ const counts = tokenCounts(step);
491
+ totals.input += counts.input;
492
+ totals.cached += counts.read;
493
+ totals.output += counts.output;
494
+ totals.reasoning += counts.reasoning;
495
+ totals.cacheWrite += counts.write;
496
+ totals.cost += amountOf(step.cost);
497
+ totals.listCost += amountOf(step.listCost);
498
+ }
499
+ return totals;
500
+ }
501
+ function identityKey(model) {
502
+ if (!model)
503
+ return;
504
+ return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
505
+ }
506
+ function cacheRead(message) {
507
+ return countOf(message?.tokens?.cache?.read);
508
+ }
509
+ function stepCreated(message) {
510
+ return stampOf(message?.time?.created);
511
+ }
512
+ function stepEnd(message) {
513
+ const time = message?.time;
514
+ if (!time)
515
+ return;
516
+ return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
517
+ }
518
+ function cacheDrop(reference, current, scope = "provider") {
519
+ if (!reference)
520
+ return;
521
+ const before = reference.model;
522
+ const after = current.model;
523
+ if (!before || !after)
524
+ return;
525
+ if (scope === "provider" && before.providerID !== after.providerID)
526
+ return;
527
+ if (before.id !== after.id || (before.variant ?? "") !== (after.variant ?? "")) {
528
+ return;
529
+ }
530
+ const drop = cacheRead(reference) - cacheRead(current);
531
+ if (isNoiseDrop(after.providerID, drop))
532
+ return;
533
+ return drop > 0 ? drop : undefined;
534
+ }
535
+ function stepGap(reference, current) {
536
+ const ended = stepEnd(reference);
537
+ const started = stepCreated(current);
538
+ if (ended === undefined || started === undefined)
539
+ return;
540
+ return Math.max(0, started - ended);
541
+ }
542
+ function tokensPerSecond(produced, from, to) {
543
+ if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
544
+ return;
545
+ if (!Number.isFinite(produced) || produced <= 0)
546
+ return;
547
+ return produced / (to - from) * 1000;
548
+ }
549
+ var DROP_EXEMPT_PROVIDERS = new Set(["openai"]);
550
+ function isSettledStep(message) {
551
+ if (message.time?.completed !== undefined)
552
+ return true;
553
+ return message.finish !== undefined && message.finish !== null;
554
+ }
555
+ function computeTurn(messages, session) {
556
+ const segments = transcriptTail(messages, 2);
557
+ const last = segments[segments.length - 1];
558
+ if (!last)
559
+ return;
560
+ const previous = segments[segments.length - 2];
561
+ const lastStep = last.assistants[last.assistants.length - 1];
562
+ if (!lastStep)
563
+ return;
564
+ if (!isSettledStep(lastStep))
565
+ return;
566
+ const previousStep = previous?.assistants[previous.assistants.length - 1];
567
+ const settled = last.assistants.filter(isSettledStep);
568
+ const drops = [];
569
+ let reference = previousStep !== undefined && isSettledStep(previousStep) ? previousStep : undefined;
570
+ for (const step of settled) {
571
+ const drop = cacheDrop(reference, step);
572
+ if (drop !== undefined) {
573
+ drops.push({
574
+ messageID: step.id,
575
+ tokens: drop,
576
+ prevCached: cacheRead(reference),
577
+ gapMs: stepGap(reference, step)
578
+ });
579
+ }
580
+ reference = step;
581
+ }
582
+ const provider = lastStep.model?.providerID;
583
+ const previousProvider = previousStep?.model?.providerID;
584
+ const key = identityKey(lastStep.model);
585
+ const previousKey = identityKey(previousStep?.model);
586
+ return {
587
+ endAt: stepEnd(lastStep),
588
+ startAt: stepCreated(settled[0] ?? lastStep),
589
+ promptAt: stampOf(last.prompt?.time?.created),
590
+ promptGapMs: promptGap(last.prompt, previous?.prompt),
591
+ providerID: provider,
592
+ modelID: lastStep.model?.id,
593
+ variant: lastStep.model?.variant,
594
+ providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,
595
+ modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,
596
+ totals: totalize(settled),
597
+ latest: totalize([lastStep]),
598
+ session,
599
+ drops,
600
+ cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),
601
+ cacheExpired: drops.length > 0,
602
+ steps: settled.length
603
+ };
604
+ }
605
+ function promptGap(current, previous) {
606
+ const now = stampOf(current?.time?.created);
607
+ const before = stampOf(previous?.time?.created);
608
+ if (now === undefined || before === undefined)
609
+ return;
610
+ return Math.max(0, now - before);
611
+ }
612
+ function isNoiseDrop(providerID, drop) {
613
+ if (providerID === undefined)
614
+ return false;
615
+ return DROP_EXEMPT_PROVIDERS.has(providerID) && drop >= 1024 && drop <= 2048;
616
+ }
617
+ var DEFAULT_LABELS = {
618
+ delta: "\u0394",
619
+ turn: "",
620
+ session: "sess",
621
+ step: "step",
622
+ steps: "steps",
623
+ input: "in",
624
+ cached: "cached",
625
+ output: "out",
626
+ reasoning: "reason",
627
+ cost: "cost",
628
+ estimate: "\u2248",
629
+ cacheExpired: "cache expired",
630
+ providerChanged: "changed",
631
+ modelChanged: "model changed"
632
+ };
633
+ var DEFAULT_FIELDS = {
634
+ clock: true,
635
+ delta: true,
636
+ model: true,
637
+ variant: true,
638
+ turn: true,
639
+ session: true,
640
+ reasoning: false,
641
+ cost: true,
642
+ cacheExpiry: true
643
+ };
644
+ function formatClock(ms) {
645
+ if (!Number.isFinite(ms))
646
+ return "--:--";
647
+ const date = new Date(ms);
648
+ const pad = (value) => String(value).padStart(2, "0");
649
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
650
+ }
651
+ function formatDuration(ms) {
652
+ if (!Number.isFinite(ms))
653
+ return "\u2013";
654
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
655
+ const seconds = totalSeconds % 60;
656
+ const minutes = Math.floor(totalSeconds / 60) % 60;
657
+ const hours = Math.floor(totalSeconds / 3600) % 24;
658
+ const days = Math.floor(totalSeconds / 86400);
659
+ if (days > 0)
660
+ return `${days}d${hours}h`;
661
+ if (hours > 0)
662
+ return `${hours}h${String(minutes).padStart(2, "0")}m`;
663
+ if (minutes > 0)
664
+ return `${minutes}m${String(seconds).padStart(2, "0")}s`;
665
+ return `${seconds}s`;
666
+ }
667
+ function formatTokens(value) {
668
+ const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
669
+ if (n < 1000)
670
+ return String(n);
671
+ if (n < 999500) {
672
+ const k = n / 1000;
673
+ return `${trimZeros(k.toFixed(k < 10 ? 2 : 1))}k`;
674
+ }
675
+ if (n < 999500000) {
676
+ const m = n / 1e6;
677
+ return `${trimZeros(m.toFixed(m < 10 ? 2 : 1))}M`;
678
+ }
679
+ return `${Math.round(n / 1e6)}M`;
680
+ }
681
+ function trimZeros(value) {
682
+ return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
683
+ }
684
+ function formatCost(value) {
685
+ if (!Number.isFinite(value) || value <= 0)
686
+ return "$0";
687
+ if (value < 0.00005)
688
+ return "<$0.0001";
689
+ if (value < 1)
690
+ return `$${value.toFixed(4)}`;
691
+ return `$${value.toFixed(2)}`;
692
+ }
693
+ function formatMoney(charged, estimated, marker = "\u2248") {
694
+ const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
695
+ const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
696
+ if (paid !== undefined && estimate !== undefined)
697
+ return `${paid} + ${estimate}`;
698
+ return paid ?? estimate;
699
+ }
700
+ function formatSpend(charged, estimated, marker = "\u2248") {
701
+ const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
702
+ const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
703
+ if (estimate > 0)
704
+ return `${marker.trim()}${formatCost(paid + estimate)}`;
705
+ return formatCost(paid);
706
+ }
707
+ function displayTotals(totals) {
708
+ const prompt = totals.input + totals.cached + totals.cacheWrite;
709
+ return {
710
+ input: prompt - totals.cached,
711
+ cached: totals.cached,
712
+ cacheWrite: totals.cacheWrite,
713
+ output: totals.output + totals.reasoning,
714
+ reasoning: totals.reasoning,
715
+ cost: totals.cost,
716
+ listCost: totals.listCost,
717
+ steps: totals.steps,
718
+ prompt
719
+ };
720
+ }
721
+ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
722
+ const display = displayTotals(totals);
723
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
724
+ const parts = [
725
+ input,
726
+ `${labels.cached} ${formatTokens(display.cached)}`,
727
+ `${labels.output} ${formatTokens(display.output)}`
728
+ ];
729
+ if (fields.reasoning)
730
+ parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
731
+ const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
732
+ if (money !== undefined)
733
+ parts.push(`${labels.cost} ${money}`);
734
+ const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
735
+ const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
736
+ const numbers = parts.join(", ");
737
+ if (head === "")
738
+ return numbers;
739
+ return stepCount > 1 ? `${head} \xB7 ${numbers}` : `${head} ${numbers}`;
740
+ }
741
+ function formatLineSegments(stats, options) {
742
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
743
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
744
+ const turnTotals = options?.turnTotals ?? "latest";
745
+ const estimates = options?.estimates !== false;
746
+ const segments = [];
747
+ if (fields.clock && stats.endAt !== undefined) {
748
+ segments.push({ text: formatClock(stats.endAt), tone: "muted" });
749
+ }
750
+ if (fields.delta && stats.promptGapMs !== undefined) {
751
+ segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: "muted" });
752
+ }
753
+ if (stats.providerID !== undefined) {
754
+ let text = stats.providerID;
755
+ if (fields.model && stats.modelID !== undefined)
756
+ text += `/${stats.modelID}`;
757
+ if (fields.variant && stats.variant)
758
+ text += ` ${stats.variant}`;
759
+ segments.push({ text, tone: stats.providerChanged ? "warning" : "base" });
760
+ if (stats.providerChanged)
761
+ segments.push({ text: labels.providerChanged, tone: "warning" });
762
+ else if (stats.modelChanged)
763
+ segments.push({ text: labels.modelChanged, tone: "muted" });
764
+ }
765
+ if (fields.turn && stats.totals.steps > 0) {
766
+ const totals = turnTotals === "sum" ? stats.totals : stats.latest;
767
+ segments.push({
768
+ text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
769
+ tone: "base"
770
+ });
771
+ }
772
+ if (fields.session && stats.session) {
773
+ segments.push({
774
+ text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
775
+ tone: "muted"
776
+ });
777
+ }
778
+ if (fields.cacheExpiry && stats.cacheExpired) {
779
+ const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
780
+ segments.push({ text: `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${count})`, tone: "warning" });
781
+ }
782
+ return segments;
783
+ }
784
+ function formatLine(stats, options) {
785
+ return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
786
+ }
787
+
788
+ // src/stats/queries.ts
789
+ var COMPACTION_KIND = "compaction";
790
+ var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
791
+ function spend(usage) {
792
+ return usage.cost + usage.listCost;
793
+ }
794
+ function sessionListCost(db, sessionID) {
795
+ const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
796
+ return row?.listCost ?? 0;
797
+ }
798
+ var EMPTY_OTHER = { entries: 0, cost: 0 };
799
+ function hasUsageTable(db) {
800
+ try {
801
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'").get() !== null;
802
+ } catch {
803
+ return false;
804
+ }
805
+ }
806
+ function otherWhere(range, filters) {
807
+ if (filters?.modelID !== undefined && filters.modelID !== "")
808
+ return;
809
+ if (filters?.modelKey !== undefined && filters.modelKey !== "")
810
+ return;
811
+ if (filters?.provider !== undefined && filters.provider !== "")
812
+ return;
813
+ const span = rangeWhere(range, "at");
814
+ const clauses = span.where === "" ? [] : [span.where.slice("WHERE ".length)];
815
+ const params = [...span.params];
816
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
817
+ clauses.push("session_id = ?");
818
+ params.push(filters.sessionID);
819
+ }
820
+ return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
821
+ }
822
+ function otherUsage(db, range, filters) {
823
+ const filter = otherWhere(range, filters);
824
+ if (filter === undefined || !hasUsageTable(db))
825
+ return { ...EMPTY_OTHER };
826
+ try {
827
+ const row = db.query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`).get(...filter.params);
828
+ return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 };
829
+ } catch {
830
+ return { ...EMPTY_OTHER };
831
+ }
832
+ }
833
+ function otherUsageBySession(db, range, filters) {
834
+ const out = new Map;
835
+ const filter = otherWhere(range, filters);
836
+ if (filter === undefined || !hasUsageTable(db))
837
+ return out;
838
+ try {
839
+ const rows = db.query(`SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost
840
+ FROM usage ${filter.where}
841
+ GROUP BY session_id`).all(...filter.params);
842
+ for (const row of rows)
843
+ out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 });
844
+ } catch {}
845
+ return out;
846
+ }
847
+ function otherUsageRows(db, range, filters) {
848
+ const filter = otherWhere(range, filters);
849
+ if (filter === undefined || !hasUsageTable(db))
850
+ return [];
851
+ const where = filter.where === "" ? "WHERE at IS NOT NULL" : `${filter.where} AND at IS NOT NULL`;
852
+ try {
853
+ return db.query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`).all(...filter.params);
854
+ } catch {
855
+ return [];
856
+ }
857
+ }
858
+ var STEP_TIME = "COALESCE(created_at, recorded_at)";
859
+ var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
860
+ function modelKey(modelID, variant) {
861
+ return `${modelID}#${variant ?? ""}`;
862
+ }
863
+ function modelLabel(modelID, variant) {
864
+ return variant === undefined ? modelID : `${modelID} ${variant}`;
865
+ }
866
+ var USAGE_SELECT = `COUNT(*) AS steps,
867
+ COALESCE(SUM(input_tokens), 0) AS input,
868
+ COALESCE(SUM(cache_read), 0) AS cached,
869
+ COALESCE(SUM(cache_write), 0) AS cacheWrite,
870
+ COALESCE(SUM(output_tokens), 0) AS output,
871
+ COALESCE(SUM(reasoning_tokens), 0) AS reasoning,
872
+ COALESCE(SUM(cost), 0) AS cost,
873
+ COALESCE(SUM(list_cost), 0) AS listCost`;
874
+ function usageFrom(row) {
875
+ return {
876
+ steps: row.steps ?? 0,
877
+ input: row.input ?? 0,
878
+ cached: row.cached ?? 0,
879
+ cacheWrite: row.cacheWrite ?? 0,
880
+ output: row.output ?? 0,
881
+ reasoning: row.reasoning ?? 0,
882
+ cost: row.cost ?? 0,
883
+ listCost: row.listCost ?? 0
884
+ };
885
+ }
886
+ function rangeWhere(range, column = STEP_TIME) {
887
+ const clauses = [];
888
+ const params = [];
889
+ if (range?.from !== undefined) {
890
+ clauses.push(`${column} >= ?`);
891
+ params.push(range.from);
892
+ }
893
+ if (range?.to !== undefined) {
894
+ clauses.push(`${column} < ?`);
895
+ params.push(range.to);
896
+ }
897
+ return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
898
+ }
899
+ function buildWhere(range, filters, column = STEP_TIME) {
900
+ const rangeClause = rangeWhere(range, column);
901
+ const clauses = rangeClause.where === "" ? [] : [rangeClause.where.slice("WHERE ".length)];
902
+ const params = [...rangeClause.params];
903
+ if (filters?.modelID !== undefined && filters.modelID !== "") {
904
+ clauses.push("model_id = ?");
905
+ params.push(filters.modelID);
906
+ }
907
+ if (filters?.modelKey !== undefined && filters.modelKey !== "") {
908
+ clauses.push(`${MODEL_KEY_SQL} = ?`);
909
+ params.push(filters.modelKey);
910
+ }
911
+ if (filters?.provider !== undefined && filters.provider !== "") {
912
+ clauses.push("provider_id = ?");
913
+ params.push(filters.provider);
914
+ }
915
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
916
+ clauses.push("session_id = ?");
917
+ params.push(filters.sessionID);
918
+ }
919
+ return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
920
+ }
921
+ function cacheHitRatio(usage) {
922
+ const total = usage.cached + usage.input + usage.cacheWrite;
923
+ return total > 0 ? usage.cached / total : undefined;
924
+ }
925
+ function overview(db, range, filters) {
926
+ const steps = buildWhere(range, filters);
927
+ const row = db.query(`SELECT ${USAGE_SELECT},
928
+ COUNT(DISTINCT session_id) AS sessions,
929
+ MIN(${STEP_TIME}) AS firstAt,
930
+ MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
931
+ COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
932
+ COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
933
+ FROM steps ${steps.where}`).get(...steps.params);
934
+ const prompts = rangeWhere(range, "created_at");
935
+ const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
936
+ const promptParams = [...prompts.params];
937
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
938
+ promptClauses.push("session_id = ?");
939
+ promptParams.push(filters.sessionID);
940
+ }
941
+ const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
942
+ const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
943
+ const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
944
+ const other = otherUsage(db, range, filters);
945
+ return {
946
+ ...usage,
947
+ cost: usage.cost + other.cost,
948
+ sessions: row?.sessions ?? 0,
949
+ prompts: promptRow?.prompts ?? 0,
950
+ otherCost: other.cost,
951
+ firstAt: row?.firstAt ?? undefined,
952
+ lastAt: row?.lastAt ?? undefined,
953
+ cacheHitRatio: cacheHitRatio(usage),
954
+ tps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0)
955
+ };
956
+ }
957
+ function models(db, range, filters) {
958
+ const filter = buildWhere(range, filters);
959
+ const rows = db.query(`SELECT provider_id, model_id, variant,
960
+ ${USAGE_SELECT},
961
+ MIN(${STEP_TIME}) AS first_at,
962
+ MAX(COALESCE(completed_at, recorded_at)) AS last_at
963
+ FROM steps ${filter.where}
964
+ GROUP BY provider_id, model_id, variant
965
+ ORDER BY steps DESC, cached DESC`).all(...filter.params);
966
+ const models = new Map;
967
+ for (const row of rows) {
968
+ const modelID = row.model_id ?? "(unknown)";
969
+ const variant = row.variant ?? undefined;
970
+ const key = `${modelID}#${variant ?? ""}`;
971
+ let model = models.get(key);
972
+ if (!model) {
973
+ model = { modelID, variant, providers: [], totals: emptyUsage() };
974
+ models.set(key, model);
975
+ }
976
+ const usage = usageFrom(row);
977
+ model.providers.push({
978
+ ...usage,
979
+ providerID: row.provider_id ?? "(unknown)",
980
+ firstAt: row.first_at ?? undefined,
981
+ lastAt: row.last_at ?? undefined
982
+ });
983
+ addUsage(model.totals, usage);
984
+ }
985
+ return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
986
+ }
987
+ function emptyUsage() {
988
+ return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
989
+ }
990
+ function addUsage(target, source) {
991
+ target.steps += source.steps;
992
+ target.input += source.input;
993
+ target.cached += source.cached;
994
+ target.cacheWrite += source.cacheWrite;
995
+ target.output += source.output;
996
+ target.reasoning += source.reasoning;
997
+ target.cost += source.cost;
998
+ target.listCost += source.listCost;
999
+ }
1000
+ function billedTokens(usage) {
1001
+ return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning;
1002
+ }
1003
+ function percentile(values, p) {
1004
+ if (values.length === 0)
1005
+ return;
1006
+ const sorted = [...values].sort((a, b) => a - b);
1007
+ const rank = Math.ceil(p / 100 * sorted.length);
1008
+ const index = Math.min(sorted.length - 1, Math.max(0, rank - 1));
1009
+ return sorted[index];
1010
+ }
1011
+ function latencyStats(values) {
1012
+ return {
1013
+ count: values.length,
1014
+ p50: percentile(values, 50),
1015
+ p90: percentile(values, 90),
1016
+ p99: percentile(values, 99)
1017
+ };
1018
+ }
1019
+ function sessions(db, options) {
1020
+ if (options?.sessionIDs !== undefined && options.sessionIDs.length === 0)
1021
+ return [];
1022
+ const range = options?.range;
1023
+ const filter = buildWhere(range, options?.filters, "COALESCE(st.created_at, st.recorded_at)");
1024
+ const limit = options?.limit ?? 20;
1025
+ const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
1026
+ const params = [...filter.params];
1027
+ const promptRange = [];
1028
+ const promptParams = [];
1029
+ if (range?.from !== undefined) {
1030
+ promptRange.push("p.created_at >= ?");
1031
+ promptParams.push(range.from);
1032
+ }
1033
+ if (range?.to !== undefined) {
1034
+ promptRange.push("p.created_at < ?");
1035
+ promptParams.push(range.to);
1036
+ }
1037
+ const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(" AND ")}` : "";
1038
+ if (options?.sessionIDs !== undefined) {
1039
+ const ids = options.sessionIDs.slice(0, 500);
1040
+ clauses.push(`st.session_id IN (${ids.map(() => "?").join(", ")})`);
1041
+ params.push(...ids);
1042
+ }
1043
+ const rows = db.query(`SELECT st.session_id, s.title, s.directory, s.parent_id,
1044
+ GROUP_CONCAT(DISTINCT st.provider_id) AS providers,
1045
+ GROUP_CONCAT(DISTINCT st.model_id) AS models,
1046
+ (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,
1047
+ COUNT(*) AS steps,
1048
+ COALESCE(SUM(st.input_tokens), 0) AS input,
1049
+ COALESCE(SUM(st.cache_read), 0) AS cached,
1050
+ COALESCE(SUM(st.cache_write), 0) AS cacheWrite,
1051
+ COALESCE(SUM(st.output_tokens), 0) AS output,
1052
+ COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,
1053
+ COALESCE(SUM(st.cost), 0) AS cost,
1054
+ COALESCE(SUM(st.list_cost), 0) AS listCost,
1055
+ MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,
1056
+ MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at
1057
+ FROM steps st
1058
+ LEFT JOIN sessions s ON s.session_id = st.session_id
1059
+ ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
1060
+ GROUP BY st.session_id
1061
+ ORDER BY last_at DESC
1062
+ LIMIT ?`).all(...promptParams, ...params, limit);
1063
+ const other = otherUsageBySession(db, range, options?.filters);
1064
+ return rows.map((row) => {
1065
+ const usage = usageFrom(row);
1066
+ const extra = other.get(row.session_id)?.cost ?? 0;
1067
+ return {
1068
+ ...usage,
1069
+ cost: usage.cost + extra,
1070
+ sessionID: row.session_id,
1071
+ parentID: row.parent_id ?? undefined,
1072
+ title: row.title ?? undefined,
1073
+ directory: row.directory ?? undefined,
1074
+ providers: row.providers ? row.providers.split(",").filter(Boolean) : [],
1075
+ models: row.models ? row.models.split(",").filter(Boolean) : [],
1076
+ prompts: row.prompts ?? 0,
1077
+ otherCost: extra,
1078
+ firstAt: row.first_at ?? undefined,
1079
+ lastAt: row.last_at ?? undefined,
1080
+ cacheHitRatio: cacheHitRatio(usage)
1081
+ };
1082
+ });
1083
+ }
1084
+ function childSessionIDs(db, parentID) {
1085
+ return db.query("SELECT session_id FROM sessions WHERE parent_id = ? ORDER BY session_id").all(parentID).map((row) => row.session_id);
1086
+ }
1087
+ function sessionUsageOf(db, sessionIDs) {
1088
+ return sessions(db, { sessionIDs, limit: sessionIDs.length });
1089
+ }
1090
+ function turnFinished(finish) {
1091
+ return finish !== null && finish !== "" && finish !== "tool-calls";
1092
+ }
1093
+ function stepUsage(row) {
1094
+ return {
1095
+ steps: 1,
1096
+ input: row.input_tokens ?? 0,
1097
+ cached: row.cache_read ?? 0,
1098
+ cacheWrite: row.cache_write ?? 0,
1099
+ output: row.output_tokens ?? 0,
1100
+ reasoning: row.reasoning_tokens ?? 0,
1101
+ cost: row.cost ?? 0,
1102
+ listCost: row.list_cost ?? 0
1103
+ };
1104
+ }
1105
+ function stepMessage(row) {
1106
+ return {
1107
+ type: "assistant",
1108
+ id: row.message_id,
1109
+ time: { created: row.created_at ?? row.recorded_at, completed: row.completed_at ?? undefined },
1110
+ model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
1111
+ tokens: {
1112
+ input: row.input_tokens ?? 0,
1113
+ output: row.output_tokens ?? 0,
1114
+ reasoning: row.reasoning_tokens ?? 0,
1115
+ cache: { read: row.cache_read ?? 0, write: row.cache_write ?? 0 }
1116
+ },
1117
+ finish: row.finish ?? undefined
1118
+ };
1119
+ }
1120
+ function turns(db, options) {
1121
+ const requested = options?.limit ?? 50;
1122
+ const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50;
1123
+ const filter = buildWhere(options?.range, options?.filters);
1124
+ const baseClauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
1125
+ const baseParams = [...filter.params];
1126
+ if (options?.sessionID !== undefined) {
1127
+ baseClauses.push("session_id = ?");
1128
+ baseParams.push(options.sessionID);
1129
+ }
1130
+ function read(promptCount) {
1131
+ const clauses = [...baseClauses];
1132
+ const params = [...baseParams];
1133
+ const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount);
1134
+ if (floor !== undefined) {
1135
+ clauses.push(`${STEP_TIME} >= ?`);
1136
+ params.push(floor);
1137
+ }
1138
+ const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
1139
+ input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
1140
+ created_at, streamed_at, recorded_at, completed_at, finish
1141
+ FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
1142
+ ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
1143
+ const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
1144
+ const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
1145
+ const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
1146
+ const promptsBySession = new Map;
1147
+ for (const row of promptRows) {
1148
+ if (row.created_at === null)
1149
+ continue;
1150
+ const list = promptsBySession.get(row.session_id) ?? [];
1151
+ list.push(row.created_at);
1152
+ promptsBySession.set(row.session_id, list);
1153
+ }
1154
+ const result = [];
1155
+ let sessionID;
1156
+ let bucket = [];
1157
+ let promptIndex = -2;
1158
+ let promptAt;
1159
+ function close() {
1160
+ const last = bucket[bucket.length - 1];
1161
+ if (last === undefined || !turnFinished(last.finish)) {
1162
+ bucket = [];
1163
+ return;
1164
+ }
1165
+ const totals = emptyUsage();
1166
+ for (const row of bucket)
1167
+ addUsage(totals, stepUsage(row));
1168
+ const drops = [];
1169
+ let reference;
1170
+ for (const row of bucket) {
1171
+ const message = stepMessage(row);
1172
+ const drop = cacheDrop(reference, message);
1173
+ if (drop !== undefined) {
1174
+ drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
1175
+ }
1176
+ reference = message;
1177
+ }
1178
+ const providerID = last.provider_id ?? undefined;
1179
+ const modelID = last.model_id ?? undefined;
1180
+ const variant = last.variant ?? undefined;
1181
+ let produced = 0;
1182
+ let window = 0;
1183
+ for (const row of bucket) {
1184
+ if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
1185
+ continue;
1186
+ produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
1187
+ window += row.streamed_at - row.created_at;
1188
+ }
1189
+ const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
1190
+ const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
1191
+ const firstAt = bucket[0]?.created_at ?? promptAt;
1192
+ result.push({
1193
+ sessionID: last.session_id,
1194
+ promptAt,
1195
+ endAt,
1196
+ durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
1197
+ promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
1198
+ providerID,
1199
+ modelID,
1200
+ variant,
1201
+ providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
1202
+ modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
1203
+ steps: bucket.length,
1204
+ latest: stepUsage(last),
1205
+ totals,
1206
+ drops,
1207
+ finish: last.finish ?? undefined,
1208
+ tps: tokensPerSecond(produced, 0, window)
1209
+ });
1210
+ bucket = [];
1211
+ }
1212
+ for (const row of steps) {
1213
+ if (row.session_id !== sessionID) {
1214
+ close();
1215
+ sessionID = row.session_id;
1216
+ promptIndex = -2;
1217
+ promptAt = undefined;
1218
+ }
1219
+ const time = row.created_at ?? row.recorded_at;
1220
+ const prompts = promptsBySession.get(row.session_id) ?? [];
1221
+ let index = -1;
1222
+ for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
1223
+ if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
1224
+ index = candidate;
1225
+ break;
1226
+ }
1227
+ }
1228
+ if (index !== promptIndex) {
1229
+ close();
1230
+ promptIndex = index;
1231
+ promptAt = index >= 0 ? prompts[index] : undefined;
1232
+ }
1233
+ bucket.push(row);
1234
+ }
1235
+ close();
1236
+ const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
1237
+ return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
1238
+ }
1239
+ let promptCount = Math.max(1, limit + 1);
1240
+ for (;; ) {
1241
+ const { rows, complete } = read(promptCount);
1242
+ if (rows.length >= limit || complete)
1243
+ return rows.slice(0, limit);
1244
+ const next = promptCount * 2 + 1;
1245
+ if (!Number.isFinite(next) || next <= promptCount)
1246
+ return rows.slice(0, limit);
1247
+ promptCount = next;
1248
+ }
1249
+ }
1250
+ function promptFloor(db, sessionID, count) {
1251
+ const rows = db.query("SELECT created_at FROM prompts WHERE session_id = ? AND created_at IS NOT NULL ORDER BY created_at DESC LIMIT ?").all(sessionID, count);
1252
+ return rows.length === count ? rows[count - 1].created_at : undefined;
1253
+ }
1254
+ function filterOptions(db) {
1255
+ const pick = (column) => db.query(`SELECT ${column} AS value, COUNT(*) AS steps FROM steps WHERE ${column} IS NOT NULL GROUP BY ${column} ORDER BY steps DESC`).all().map((row) => ({ value: row.value, steps: row.steps }));
1256
+ return { models: pick("model_id"), providers: pick("provider_id") };
1257
+ }
1258
+
1259
+ // src/stats/aggregates.ts
1260
+ var STEP_AT = "COALESCE(created_at, recorded_at)";
1261
+ function normalize(rows, optional) {
1262
+ for (const row of rows) {
1263
+ for (const key of optional)
1264
+ if (row[key] === null)
1265
+ row[key] = undefined;
1266
+ }
1267
+ return rows;
1268
+ }
1269
+ function groupBy(items, key) {
1270
+ const groups = new Map;
1271
+ for (const item of items) {
1272
+ const group = key(item);
1273
+ const list = groups.get(group);
1274
+ if (list !== undefined)
1275
+ list.push(item);
1276
+ else
1277
+ groups.set(group, [item]);
1278
+ }
1279
+ return groups;
1280
+ }
1281
+ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,
1282
+ model_id AS modelID, variant,
1283
+ COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1284
+ COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1285
+ COALESCE(list_cost, 0) AS listCost,
1286
+ created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1287
+ var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
1288
+ var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1289
+ function stepRows(db, options) {
1290
+ const filter = buildWhere(options?.range, options?.filters);
1291
+ const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
1292
+ return normalize(rows, STEP_OPTIONAL);
1293
+ }
1294
+ function cachePairs(db, options) {
1295
+ const filter = buildWhere(options?.range, options?.filters);
1296
+ const rows = normalize(db.query(`SELECT ${PAIR_COLUMNS} FROM steps ${filter.where} ORDER BY session_id, ${STEP_AT}, message_id`).all(...filter.params), STEP_OPTIONAL);
1297
+ const from = options?.range?.from;
1298
+ if (from === undefined || rows.length === 0)
1299
+ return rows;
1300
+ const seek = db.query(`SELECT ${PAIR_COLUMNS} FROM steps
1301
+ WHERE session_id = ? AND COALESCE(created_at, recorded_at) < ?
1302
+ ORDER BY COALESCE(created_at, recorded_at) DESC, message_id DESC LIMIT 1`);
1303
+ for (const sessionID of new Set(rows.map((row) => row.sessionID))) {
1304
+ const boundary = seek.get(sessionID, from);
1305
+ if (boundary === null)
1306
+ continue;
1307
+ const step = normalize([boundary], STEP_OPTIONAL)[0];
1308
+ step.boundary = true;
1309
+ rows.push(step);
1310
+ }
1311
+ rows.sort((left, right) => {
1312
+ if (left.sessionID !== right.sessionID)
1313
+ return left.sessionID < right.sessionID ? -1 : 1;
1314
+ if (left.at !== right.at)
1315
+ return left.at - right.at;
1316
+ return left.messageID < right.messageID ? -1 : left.messageID > right.messageID ? 1 : 0;
1317
+ });
1318
+ return rows;
1319
+ }
1320
+ function message(step) {
1321
+ return {
1322
+ type: "assistant",
1323
+ id: step.messageID,
1324
+ ...step.modelID === undefined ? {} : { model: { providerID: step.providerID ?? "", id: step.modelID, ...step.variant === undefined ? {} : { variant: step.variant } } },
1325
+ tokens: { cache: { read: step.cached } },
1326
+ time: {
1327
+ ...step.createdAt === undefined ? {} : { created: step.createdAt },
1328
+ ...step.streamedAt === undefined ? {} : { streamed: step.streamedAt },
1329
+ ...step.completedAt === undefined ? {} : { completed: step.completedAt }
1330
+ }
1331
+ };
1332
+ }
1333
+ function pairsOf(rows) {
1334
+ const pairs = [];
1335
+ for (let index = 1;index < rows.length; index += 1) {
1336
+ const previous = rows[index - 1];
1337
+ const current = rows[index];
1338
+ if (previous.sessionID !== current.sessionID)
1339
+ continue;
1340
+ pairs.push({ previous, current });
1341
+ }
1342
+ return pairs;
1343
+ }
1344
+ function usageOf(steps) {
1345
+ const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
1346
+ for (const step of steps) {
1347
+ usage.steps += 1;
1348
+ usage.input += step.input;
1349
+ usage.cached += step.cached;
1350
+ usage.cacheWrite += step.cacheWrite;
1351
+ usage.output += step.output;
1352
+ usage.reasoning += step.reasoning;
1353
+ usage.cost += step.cost;
1354
+ usage.listCost += step.listCost;
1355
+ }
1356
+ return usage;
1357
+ }
1358
+ function coverageOf(db, options) {
1359
+ const filter = buildWhere(options?.range, options?.filters);
1360
+ const row = db.query(`SELECT COUNT(*) AS steps,
1361
+ COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,
1362
+ COUNT(DISTINCT provider_id) AS providers,
1363
+ COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1364
+ COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1365
+ 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,
1366
+ MIN(${STEP_AT}) AS firstAt,
1367
+ MAX(${STEP_AT}) AS lastAt
1368
+ FROM steps ${filter.where}`).get(...filter.params);
1369
+ return {
1370
+ steps: row.steps,
1371
+ models: row.models,
1372
+ providers: row.providers,
1373
+ missingModel: row.missingModel,
1374
+ unsettled: row.unsettled,
1375
+ missingTps: row.missingTps,
1376
+ firstAt: row.firstAt ?? undefined,
1377
+ lastAt: row.lastAt ?? undefined
1378
+ };
1379
+ }
1380
+ function groupedRows(db, options) {
1381
+ const filter = buildWhere(options?.range, options?.filters);
1382
+ const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
1383
+ return normalize(rows, STEP_OPTIONAL);
1384
+ }
1385
+ function timingOf(step) {
1386
+ const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
1387
+ const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
1388
+ return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
1389
+ }
1390
+ function timingRows(db, options) {
1391
+ return groupedRows(db, options);
1392
+ }
1393
+ function latencyOf(rows) {
1394
+ const wall = [];
1395
+ const stream = [];
1396
+ const tps = [];
1397
+ for (const step of rows) {
1398
+ const timing = timingOf(step);
1399
+ if (timing.wall !== undefined)
1400
+ wall.push(timing.wall);
1401
+ if (timing.stream !== undefined)
1402
+ stream.push(timing.stream);
1403
+ if (timing.tps !== undefined)
1404
+ tps.push(timing.tps);
1405
+ }
1406
+ return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
1407
+ }
1408
+ function latencyGroupsOf(rows, by) {
1409
+ const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
1410
+ const groups = [];
1411
+ for (const [group, steps] of groupBy(rows, key)) {
1412
+ const wall = [];
1413
+ const stream = [];
1414
+ const tps = [];
1415
+ for (const step of steps) {
1416
+ const timing = timingOf(step);
1417
+ if (timing.wall !== undefined)
1418
+ wall.push(timing.wall);
1419
+ if (timing.stream !== undefined)
1420
+ stream.push(timing.stream);
1421
+ if (timing.tps !== undefined)
1422
+ tps.push(timing.tps);
1423
+ }
1424
+ const [modelID, variant] = group.split("#");
1425
+ groups.push({
1426
+ key: group,
1427
+ label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
1428
+ count: steps.length,
1429
+ usage: usageOf(steps),
1430
+ wall: latencyStats(wall),
1431
+ stream: latencyStats(stream),
1432
+ tps: latencyStats(tps)
1433
+ });
1434
+ }
1435
+ return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
1436
+ }
1437
+ var EMPTY_CACHE = { steps: 0, input: 0, cached: 0, cacheWrite: 0, prompt: 0, hit: undefined, hitP50: undefined };
1438
+ function cacheStatsOfSteps(steps) {
1439
+ let input = 0;
1440
+ let cached = 0;
1441
+ let cacheWrite = 0;
1442
+ const ratios = [];
1443
+ for (const step of steps) {
1444
+ input += step.input;
1445
+ cached += step.cached;
1446
+ cacheWrite += step.cacheWrite;
1447
+ const prompt = step.input + step.cached + step.cacheWrite;
1448
+ if (prompt > 0)
1449
+ ratios.push(step.cached / prompt);
1450
+ }
1451
+ const prompt = input + cached + cacheWrite;
1452
+ return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) };
1453
+ }
1454
+ function cacheStatsOf(db, options) {
1455
+ const rows = stepRows(db, options);
1456
+ return rows.length === 0 ? EMPTY_CACHE : cacheStatsOfSteps(rows);
1457
+ }
1458
+ function cacheStatsByModel(rows) {
1459
+ const out = [];
1460
+ const inRange = rows.filter((row) => row.boundary !== true);
1461
+ for (const [, group] of groupBy(inRange, (row) => modelKey(row.modelID ?? "(unknown)", row.variant))) {
1462
+ out.push({ modelID: group[0].modelID ?? "(unknown)", variant: group[0].variant, cache: cacheStatsOfSteps(group) });
1463
+ }
1464
+ return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID));
1465
+ }
1466
+ function switchesOf(rows) {
1467
+ const perModel = new Map;
1468
+ const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 };
1469
+ for (const { previous, current } of pairsOf(rows)) {
1470
+ if (previous.modelID === undefined || current.modelID === undefined)
1471
+ continue;
1472
+ const key = modelKey(current.modelID, current.variant);
1473
+ const row = perModel.get(key) ?? {
1474
+ modelID: current.modelID,
1475
+ variant: current.variant,
1476
+ steps: 0,
1477
+ pairs: 0,
1478
+ changes: 0,
1479
+ modelChanges: 0,
1480
+ providerChanges: 0,
1481
+ cacheLost: 0,
1482
+ cacheLostEvents: 0
1483
+ };
1484
+ row.steps += 1;
1485
+ row.pairs += 1;
1486
+ totals.pairs += 1;
1487
+ const modelChanged = key !== modelKey(previous.modelID, previous.variant);
1488
+ const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID;
1489
+ if (modelChanged)
1490
+ row.modelChanges += 1;
1491
+ if (providerChanged)
1492
+ row.providerChanges += 1;
1493
+ if (modelChanged || providerChanged) {
1494
+ row.changes += 1;
1495
+ totals.changes += 1;
1496
+ const lost = cacheDrop(message(previous), message(current), "model");
1497
+ if (lost !== undefined) {
1498
+ row.cacheLost += lost;
1499
+ row.cacheLostEvents += 1;
1500
+ totals.cacheLost += lost;
1501
+ totals.cacheLostEvents += 1;
1502
+ }
1503
+ }
1504
+ perModel.set(key, row);
1505
+ }
1506
+ return {
1507
+ rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),
1508
+ totals
1509
+ };
1510
+ }
1511
+ var GAP_BUCKETS = [
1512
+ ["<1m", 0, 60000],
1513
+ ["1\u20135m", 60000, 5 * 60000],
1514
+ ["5\u201315m", 5 * 60000, 15 * 60000],
1515
+ ["15\u201360m", 15 * 60000, 60 * 60000],
1516
+ ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
1517
+ [">6h", 6 * 60 * 60000, undefined]
1518
+ ];
1519
+ function bucketFor(gapMs) {
1520
+ const index = GAP_BUCKETS.findIndex(([, from, to]) => gapMs >= from && (to === undefined || gapMs < to));
1521
+ return index === -1 ? GAP_BUCKETS.length - 1 : index;
1522
+ }
1523
+ function gapReportOf(rows) {
1524
+ const buckets = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }));
1525
+ const providers = new Map;
1526
+ let samples = 0;
1527
+ for (const { previous, current } of pairsOf(rows)) {
1528
+ if (previous.modelID === undefined || current.modelID === undefined)
1529
+ continue;
1530
+ if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant))
1531
+ continue;
1532
+ if ((previous.providerID ?? "") !== (current.providerID ?? ""))
1533
+ continue;
1534
+ const gap = stepGap(message(previous), message(current));
1535
+ if (gap === undefined)
1536
+ continue;
1537
+ const lost = cacheDrop(message(previous), message(current));
1538
+ const bucket = buckets[bucketFor(gap)];
1539
+ bucket.samples += 1;
1540
+ samples += 1;
1541
+ if (lost === undefined)
1542
+ bucket.retained += 1;
1543
+ else {
1544
+ bucket.drops += 1;
1545
+ bucket.lostTokens += lost;
1546
+ }
1547
+ const provider = current.providerID ?? previous.providerID ?? "(unknown)";
1548
+ const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined };
1549
+ row.samples += 1;
1550
+ if (lost === undefined)
1551
+ row.retained += 1;
1552
+ else {
1553
+ row.drops += 1;
1554
+ row.lostTokens += lost;
1555
+ }
1556
+ providers.set(provider, row);
1557
+ }
1558
+ for (const bucket of buckets)
1559
+ bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined;
1560
+ for (const row of providers.values())
1561
+ row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined;
1562
+ return {
1563
+ buckets,
1564
+ providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),
1565
+ samples
1566
+ };
1567
+ }
1568
+ function ttlEvidenceOf(rows) {
1569
+ const evidence = new Map;
1570
+ for (const { previous, current } of pairsOf(rows)) {
1571
+ if (previous.modelID === undefined || current.modelID === undefined)
1572
+ continue;
1573
+ const key = `${current.providerID ?? ""}/${current.modelID}`;
1574
+ const before = `${previous.providerID ?? ""}/${previous.modelID}#${previous.variant ?? ""}`;
1575
+ const after = `${current.providerID ?? ""}/${current.modelID}#${current.variant ?? ""}`;
1576
+ if (before !== after)
1577
+ continue;
1578
+ const row = evidence.get(key) ?? {
1579
+ providerID: current.providerID ?? "(unknown)",
1580
+ modelID: current.modelID,
1581
+ samples: 0,
1582
+ maxHitGapMs: undefined,
1583
+ minDropGapMs: undefined
1584
+ };
1585
+ row.samples += 1;
1586
+ const gapMs = stepGap(message(previous), message(current));
1587
+ if (gapMs !== undefined) {
1588
+ const lost = cacheDrop(message(previous), message(current));
1589
+ if (lost === undefined)
1590
+ row.maxHitGapMs = row.maxHitGapMs === undefined ? gapMs : Math.max(row.maxHitGapMs, gapMs);
1591
+ else
1592
+ row.minDropGapMs = row.minDropGapMs === undefined ? gapMs : Math.min(row.minDropGapMs, gapMs);
1593
+ }
1594
+ evidence.set(key, row);
1595
+ }
1596
+ return [...evidence.values()].sort((left, right) => right.samples - left.samples || `${left.providerID}/${left.modelID}`.localeCompare(`${right.providerID}/${right.modelID}`));
1597
+ }
1598
+ function cacheDropsOf(db, rows, options) {
1599
+ const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS;
1600
+ const losses = [];
1601
+ for (const { previous, current } of pairsOf(rows)) {
1602
+ const tokens = cacheDrop(message(previous), message(current), "model");
1603
+ if (tokens === undefined)
1604
+ continue;
1605
+ losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) });
1606
+ }
1607
+ if (losses.length === 0)
1608
+ return [];
1609
+ const compactions = new Map;
1610
+ const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
1611
+ const events = db.query(`SELECT session_id, at FROM events
1612
+ WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
1613
+ ORDER BY at`).all(...sessionIDs);
1614
+ for (const event of events) {
1615
+ const list = compactions.get(event.session_id);
1616
+ if (list !== undefined)
1617
+ list.push(event.at);
1618
+ else
1619
+ compactions.set(event.session_id, [event.at]);
1620
+ }
1621
+ return losses.map((loss) => {
1622
+ const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
1623
+ const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
1624
+ const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
1625
+ return {
1626
+ sessionID: loss.current.sessionID,
1627
+ messageID: loss.current.messageID,
1628
+ providerID: loss.current.providerID,
1629
+ modelID: loss.current.modelID,
1630
+ variant: loss.current.variant,
1631
+ at: loss.current.at,
1632
+ tokens: loss.tokens,
1633
+ gapMs: loss.gapMs,
1634
+ prevCached: loss.previous.cached,
1635
+ reason
1636
+ };
1637
+ }).sort((left, right) => left.at - right.at);
1638
+ }
1639
+ function groupValues(steps) {
1640
+ const wall = [];
1641
+ const tps = [];
1642
+ for (const step of steps) {
1643
+ const timing = timingOf(step);
1644
+ if (timing.wall !== undefined)
1645
+ wall.push(timing.wall);
1646
+ if (timing.tps !== undefined)
1647
+ tps.push(timing.tps);
1648
+ }
1649
+ return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
1650
+ }
1651
+ function providerOf(steps, models) {
1652
+ const values = groupValues(steps);
1653
+ let firstAt;
1654
+ let lastAt;
1655
+ for (const step of steps) {
1656
+ if (firstAt === undefined || step.at < firstAt)
1657
+ firstAt = step.at;
1658
+ if (lastAt === undefined || step.at > lastAt)
1659
+ lastAt = step.at;
1660
+ }
1661
+ return {
1662
+ provider: steps[0].providerID,
1663
+ models: models.split("\x00"),
1664
+ share: 0,
1665
+ usage: usageOf(steps),
1666
+ cache: values.cache,
1667
+ tps: values.tps,
1668
+ wall: values.wall,
1669
+ firstAt,
1670
+ lastAt
1671
+ };
1672
+ }
1673
+ var modelNames = (steps) => [...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("\x00");
1674
+ function providerSummaryOf(rows) {
1675
+ const out = [];
1676
+ for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
1677
+ const summary = providerOf(steps, modelNames(steps));
1678
+ out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length });
1679
+ }
1680
+ return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? "").localeCompare(right.provider ?? ""));
1681
+ }
1682
+ function providerBreakdownOf(rows) {
1683
+ const out = [];
1684
+ for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
1685
+ for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
1686
+ const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
1687
+ out.push({
1688
+ ...providerOf(steps, modelNames(steps)),
1689
+ modelID,
1690
+ variant: variant === "" ? undefined : variant,
1691
+ share: steps.length / modelRows.length
1692
+ });
1693
+ }
1694
+ }
1695
+ return out.sort((left, right) => right.usage.steps - left.usage.steps || right.cache.cached - left.cache.cached);
1696
+ }
1697
+ function isoWeek(date) {
1698
+ const monday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
1699
+ monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);
1700
+ const thursday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 3);
1701
+ const firstThursday = new Date(thursday.getFullYear(), 0, 4);
1702
+ firstThursday.setDate(firstThursday.getDate() - (firstThursday.getDay() + 6) % 7 + 3);
1703
+ const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000));
1704
+ return { year: thursday.getFullYear(), week, monday };
1705
+ }
1706
+ function periodEnd(at, granularity) {
1707
+ const date = new Date(at);
1708
+ if (granularity === "month")
1709
+ return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime();
1710
+ if (granularity === "week")
1711
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime();
1712
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
1713
+ }
1714
+ function periodStart(at, granularity) {
1715
+ const date = new Date(at);
1716
+ const pad = (value) => String(value).padStart(2, "0");
1717
+ if (granularity === "month") {
1718
+ const start = new Date(date.getFullYear(), date.getMonth(), 1);
1719
+ return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() };
1720
+ }
1721
+ if (granularity === "week") {
1722
+ const { year, week, monday } = isoWeek(date);
1723
+ return { key: `${year}-W${pad(week)}`, label: `${year}-W${pad(week)}`, start: monday.getTime() };
1724
+ }
1725
+ const start = new Date(date.getFullYear(), date.getMonth(), date.getDate());
1726
+ const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
1727
+ return { key, label: key, start: start.getTime() };
1728
+ }
1729
+ function periodsOf(rows, granularity, otherRows = []) {
1730
+ const byKey = new Map;
1731
+ for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {
1732
+ const period = periodStart(steps[0].at, granularity);
1733
+ byKey.set(key, {
1734
+ key,
1735
+ label: period.label,
1736
+ at: period.start,
1737
+ steps: steps.length,
1738
+ sessions: new Set(steps.map((step) => step.sessionID)).size,
1739
+ usage: usageOf(steps),
1740
+ cache: cacheStatsOfSteps(steps)
1741
+ });
1742
+ }
1743
+ for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {
1744
+ const cost = group.reduce((sum, row) => sum + row.cost, 0);
1745
+ const existing = byKey.get(key);
1746
+ if (existing !== undefined) {
1747
+ existing.usage.cost += cost;
1748
+ existing.otherCost = (existing.otherCost ?? 0) + cost;
1749
+ continue;
1750
+ }
1751
+ const period = periodStart(group[0].at, granularity);
1752
+ byKey.set(key, {
1753
+ key,
1754
+ label: period.label,
1755
+ at: period.start,
1756
+ steps: 0,
1757
+ sessions: new Set(group.map((row) => row.sessionID)).size,
1758
+ usage: { ...usageOf([]), cost },
1759
+ cache: cacheStatsOfSteps([]),
1760
+ otherCost: cost
1761
+ });
1762
+ }
1763
+ return [...byKey.values()].sort((left, right) => left.at - right.at);
1764
+ }
1765
+
1766
+ // src/quota.ts
1767
+ var QUOTA_VIEW = "go";
1768
+ var QUOTA_POLL_MS = 60000;
1769
+ var DEFAULT_QUOTA_NAME = "OpenCode Go";
1770
+ var DAY_MS = 24 * 60 * 60 * 1000;
1771
+ var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
1772
+ function quotaNameOf(explicit, providerName) {
1773
+ const custom = explicit?.trim();
1774
+ if (custom !== undefined && custom !== "")
1775
+ return custom;
1776
+ const provider = providerName?.trim();
1777
+ if (provider !== undefined && provider !== "")
1778
+ return provider;
1779
+ return DEFAULT_QUOTA_NAME;
1780
+ }
1781
+ function finite2(value) {
1782
+ return typeof value === "number" && Number.isFinite(value);
1783
+ }
1784
+ function clamp(value, minimum, maximum) {
1785
+ return Math.min(maximum, Math.max(minimum, value));
1786
+ }
1787
+ function previousCycleStart(endAt) {
1788
+ if (!finite2(endAt))
1789
+ return endAt;
1790
+ const end = new Date(endAt);
1791
+ const year = end.getUTCFullYear();
1792
+ const month = end.getUTCMonth();
1793
+ const day = end.getUTCDate();
1794
+ const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
1795
+ const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
1796
+ start.setUTCDate(Math.min(day, lastDay));
1797
+ return start.getTime();
1798
+ }
1799
+ function forecastMonthly(meter, now) {
1800
+ const endAt = finite2(meter.resetsAt) ? meter.resetsAt : now;
1801
+ const startAt = previousCycleStart(endAt);
1802
+ const total = Math.max(1, endAt - startAt);
1803
+ const elapsedMs = clamp(now - startAt, 0, total);
1804
+ const remainingMs = Math.max(0, endAt - now);
1805
+ const percent = clamp(finite2(meter.percent) ? meter.percent : 0, 0, 100);
1806
+ const reached = meter.limited === true || percent >= 100;
1807
+ const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
1808
+ const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
1809
+ const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
1810
+ const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
1811
+ const willExhaust = exhaustAt !== undefined;
1812
+ const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
1813
+ return {
1814
+ startAt,
1815
+ endAt,
1816
+ elapsedMs,
1817
+ remainingMs,
1818
+ ratePerDay,
1819
+ projectedPercent,
1820
+ ...exhaustAt !== undefined ? { exhaustAt } : {},
1821
+ reached,
1822
+ available,
1823
+ willExhaust
1824
+ };
1825
+ }
1826
+ function quotaBar(percent, width = 10) {
1827
+ const value = clamp(finite2(percent) ? percent : 0, 0, 100);
1828
+ const cells = Math.max(1, Math.round(width));
1829
+ const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
1830
+ return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
1831
+ }
1832
+ function formatRenewal(at, timeZone) {
1833
+ if (!finite2(at))
1834
+ return "\u2013";
1835
+ try {
1836
+ return new Intl.DateTimeFormat("en-GB", {
1837
+ day: "2-digit",
1838
+ month: "short",
1839
+ year: "numeric",
1840
+ hour: "2-digit",
1841
+ minute: "2-digit",
1842
+ hour12: false,
1843
+ ...timeZone !== undefined ? { timeZone } : {}
1844
+ }).format(new Date(at)).replace(/,/g, "");
1845
+ } catch {
1846
+ return "\u2013";
1847
+ }
1848
+ }
1849
+ function formatRenewalCompact(at, timeZone) {
1850
+ if (!finite2(at))
1851
+ return "\u2013";
1852
+ try {
1853
+ return new Intl.DateTimeFormat("en-GB", {
1854
+ day: "2-digit",
1855
+ month: "short",
1856
+ hour: "2-digit",
1857
+ minute: "2-digit",
1858
+ hour12: false,
1859
+ ...timeZone !== undefined ? { timeZone } : {}
1860
+ }).format(new Date(at)).replace(/,/g, "");
1861
+ } catch {
1862
+ return "\u2013";
1863
+ }
1864
+ }
1865
+ function formatCountdown(at, now) {
1866
+ const remaining = at - now;
1867
+ if (!finite2(remaining))
1868
+ return "\u2013";
1869
+ if (remaining <= 0)
1870
+ return "due";
1871
+ return formatDuration(remaining);
1872
+ }
1873
+ function quotaStatus(quota) {
1874
+ const limited = [];
1875
+ if (quota.rolling.limited || quota.rolling.percent >= 100)
1876
+ limited.push("5-hour");
1877
+ if (quota.weekly.limited || quota.weekly.percent >= 100)
1878
+ limited.push("weekly");
1879
+ if (quota.monthly.limited || quota.monthly.percent >= 100)
1880
+ limited.push("monthly");
1881
+ return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
1882
+ }
1883
+
1884
+ // src/panel-data.ts
1885
+ var PANEL_NAME = "usage-insights";
1886
+ var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
1887
+ var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
1888
+ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
1889
+ var GRANULARITIES = ["day", "week", "month"];
1890
+ var SORT_KEYS = {
1891
+ models: ["steps", "cached", "hit", "out", "cost"],
1892
+ providers: ["steps", "cached", "hit", "cost", "share", "tps"],
1893
+ latency: ["n", "tps", "wall"],
1894
+ sessions: ["last", "steps", "cached", "cost"],
1895
+ turns: ["time", "cost", "tokens"]
1896
+ };
1897
+ function sortKeys(view) {
1898
+ return SORT_KEYS[view] ?? [];
1899
+ }
1900
+ function defaultSort(view) {
1901
+ return sortKeys(view)[0] ?? "";
1902
+ }
1903
+ function nextSort(view, current, step) {
1904
+ const keys = sortKeys(view);
1905
+ if (keys.length === 0)
1906
+ return current;
1907
+ const index = keys.indexOf(current);
1908
+ if (index === -1)
1909
+ return keys[0];
1910
+ return keys[(index + step + keys.length) % keys.length];
1911
+ }
1912
+ function parseArgs(input, views = CLIENT_VIEWS) {
1913
+ const parsed = {};
1914
+ for (const token of (input ?? "").split(/\s+/)) {
1915
+ const value = token.trim().toLowerCase();
1916
+ if (value === "")
1917
+ continue;
1918
+ if (views.includes(value))
1919
+ parsed.view = value;
1920
+ else if (RANGE_KEYS.includes(value))
1921
+ parsed.range = value;
1922
+ }
1923
+ return parsed;
1924
+ }
1925
+ function rangeLabel(key) {
1926
+ switch (key) {
1927
+ case "session":
1928
+ return "this session";
1929
+ case "today":
1930
+ return "today";
1931
+ case "7d":
1932
+ return "7 days";
1933
+ case "30d":
1934
+ return "30 days";
1935
+ case "all":
1936
+ return "all time";
1937
+ }
1938
+ }
1939
+ function nextIn(values, current, step) {
1940
+ const index = values.indexOf(current);
1941
+ if (index === -1)
1942
+ return values[0];
1943
+ return values[(index + step + values.length) % values.length];
1944
+ }
1945
+ var DEFAULT_SETTINGS = {
1946
+ view: "overview",
1947
+ range: "all",
1948
+ sort: "",
1949
+ sortDesc: true,
1950
+ granularity: "day",
1951
+ turnsScope: "session",
1952
+ modelID: "",
1953
+ providerID: ""
1954
+ };
1955
+ function sanitizeSettings(raw, views = CLIENT_VIEWS) {
1956
+ const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
1957
+ return {
1958
+ view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1959
+ range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
1960
+ sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
1961
+ sortDesc: settings.sortDesc === true,
1962
+ granularity: GRANULARITIES.includes(settings.granularity) ? settings.granularity : DEFAULT_SETTINGS.granularity,
1963
+ turnsScope: settings.turnsScope === "all" ? "all" : "session",
1964
+ modelID: typeof settings.modelID === "string" ? settings.modelID : "",
1965
+ providerID: typeof settings.providerID === "string" ? settings.providerID : ""
1966
+ };
1967
+ }
1968
+ function formatPercent(value, digits = 1) {
1969
+ if (value === undefined || !Number.isFinite(value))
1970
+ return "\u2013";
1971
+ return `${(value * 100).toFixed(digits)}%`;
1972
+ }
1973
+ function formatCount(value) {
1974
+ return Number.isFinite(value) ? Math.round(value).toLocaleString("en-US") : "\u2013";
1975
+ }
1976
+ function formatMs(value) {
1977
+ if (value === undefined || !Number.isFinite(value))
1978
+ return "\u2013";
1979
+ const ms = Math.max(0, value);
1980
+ if (ms < 1000)
1981
+ return `${Math.round(ms)}ms`;
1982
+ if (ms < 60000)
1983
+ return `${(ms / 1000).toFixed(1)}s`;
1984
+ return formatDuration(ms);
1985
+ }
1986
+ function formatTps(value) {
1987
+ if (value === undefined || !Number.isFinite(value) || value < 0)
1988
+ return "\u2013";
1989
+ return `${value.toFixed(1)}/s`;
1990
+ }
1991
+ function formatTpsCompact(value) {
1992
+ if (value === undefined || !Number.isFinite(value) || value < 0)
1993
+ return "\u2013";
1994
+ return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
1995
+ }
1996
+ function formatGap(value) {
1997
+ if (value === undefined || !Number.isFinite(value))
1998
+ return "\u2013";
1999
+ const gap = Math.max(0, value);
2000
+ if (gap < 60000)
2001
+ return `${Math.round(gap / 1000)}s`;
2002
+ if (gap < 3600000)
2003
+ return `${Math.round(gap / 60000)}m`;
2004
+ if (gap < 86400000)
2005
+ return `${(gap / 3600000).toFixed(1)}h`;
2006
+ return `${(gap / 86400000).toFixed(1)}d`;
2007
+ }
2008
+ function truncate(value, width) {
2009
+ if (width <= 1)
2010
+ return "";
2011
+ const clean = sanitizeText(value);
2012
+ if (clean.length <= width)
2013
+ return clean;
2014
+ return `${clean.slice(0, width - 1).trimEnd()}\u2026`;
2015
+ }
2016
+ function truncateMiddle(value, width) {
2017
+ if (width <= 1)
2018
+ return "";
2019
+ const clean = sanitizeText(value);
2020
+ if (clean.length <= width)
2021
+ return clean;
2022
+ const head = Math.ceil((width - 1) / 2);
2023
+ const tail = width - 1 - head;
2024
+ return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
2025
+ }
2026
+ function tableWidths(width, layouts) {
2027
+ for (const layout of layouts) {
2028
+ const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
2029
+ if (total <= width)
2030
+ return [...layout];
2031
+ }
2032
+ const last = layouts[layouts.length - 1];
2033
+ return last === undefined ? [] : [...last];
2034
+ }
2035
+ function modelCell(modelID, variant, width) {
2036
+ return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
2037
+ }
2038
+ function padCell(value, width, align = "left") {
2039
+ if (value.length >= width)
2040
+ return value;
2041
+ const padding = " ".repeat(width - value.length);
2042
+ return align === "right" ? `${padding}${value}` : `${value}${padding}`;
2043
+ }
2044
+ function formatTableRow(cells, widths, aligns) {
2045
+ const parts = [];
2046
+ for (let index = 0;index < cells.length; index += 1) {
2047
+ const width = widths[index] ?? 8;
2048
+ const align = aligns?.[index] ?? "left";
2049
+ parts.push(padCell(truncate(cells[index] ?? "", width), width, align));
2050
+ }
2051
+ return parts.join(" ");
2052
+ }
2053
+ function count(n, singular, plural = `${singular}s`) {
2054
+ return `${formatCount(n)} ${n === 1 ? singular : plural}`;
2055
+ }
2056
+ function kvGrid(pairs, width) {
2057
+ const lines = [];
2058
+ const label = 11;
2059
+ const column = Math.floor(width / 2);
2060
+ for (let index = 0;index < pairs.length; index += 2) {
2061
+ const left = pairs[index];
2062
+ const right = pairs[index + 1];
2063
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
2064
+ if (right === undefined) {
2065
+ lines.push({ text: leftText, tone: "base" });
2066
+ continue;
2067
+ }
2068
+ const rightText = `${padCell(right[0], label)}${right[1]}`;
2069
+ const gap = Math.max(2, column - leftText.length);
2070
+ if (leftText.length + gap + rightText.length <= width) {
2071
+ lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
2072
+ } else {
2073
+ lines.push({ text: leftText, tone: "base" });
2074
+ lines.push({ text: rightText, tone: "base" });
2075
+ }
2076
+ }
2077
+ return lines;
2078
+ }
2079
+ var HEADER_TONE = "accent";
2080
+ var SPARK = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
2081
+ function reduceSeries(values, maxBars = 48) {
2082
+ if (values.length <= maxBars)
2083
+ return [...values];
2084
+ const group = Math.ceil(values.length / maxBars);
2085
+ const reduced = [];
2086
+ for (let index = 0;index < values.length; index += group) {
2087
+ reduced.push(values.slice(index, index + group).reduce((sum, value) => sum + value, 0));
2088
+ }
2089
+ return reduced;
2090
+ }
2091
+ function sparkline(values, maxBars = 48) {
2092
+ if (values.length === 0)
2093
+ return "";
2094
+ const series = reduceSeries(values, maxBars);
2095
+ const max = Math.max(...series);
2096
+ if (max <= 0)
2097
+ return SPARK[0].repeat(series.length);
2098
+ return series.map((value) => SPARK[Math.min(SPARK.length - 1, Math.max(0, Math.round(value / max * (SPARK.length - 1))))]).join("");
2099
+ }
2100
+ function usageBuckets(usage) {
2101
+ const prompt = usage.input + usage.cached + usage.cacheWrite;
2102
+ return {
2103
+ steps: usage.steps,
2104
+ input: prompt - usage.cached,
2105
+ prompt,
2106
+ cached: usage.cached,
2107
+ cacheWrite: usage.cacheWrite,
2108
+ output: usage.output + usage.reasoning,
2109
+ reasoning: usage.reasoning,
2110
+ cost: usage.cost,
2111
+ listCost: usage.listCost ?? 0,
2112
+ hit: prompt > 0 ? usage.cached / prompt : undefined
2113
+ };
2114
+ }
2115
+ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
2116
+ const key = (index) => String((index + 1) % 10);
2117
+ const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2118
+ const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2119
+ for (const parts of candidates) {
2120
+ const text = parts.join(" ");
2121
+ if (text.length <= width)
2122
+ return { text, tone: "muted" };
2123
+ }
2124
+ const index = views.indexOf(view);
2125
+ return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
2126
+ }
2127
+ function keysFor(of) {
2128
+ if (of === QUOTA_VIEW)
2129
+ return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
2130
+ if (of === "db")
2131
+ return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 0 view \xB7 ? help";
2132
+ if (of === "periods")
2133
+ return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2134
+ if (of === "turns")
2135
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2136
+ return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2137
+ }
2138
+ function filterSummary(filters) {
2139
+ const parts = [];
2140
+ if (filters.modelID !== undefined && filters.modelID !== "")
2141
+ parts.push(`model=${filters.modelID}`);
2142
+ if (filters.providerID !== undefined && filters.providerID !== "")
2143
+ parts.push(`provider=${filters.providerID}`);
2144
+ return parts.length > 0 ? parts.join(" \xB7 ") : undefined;
2145
+ }
2146
+ function granularityLabel(granularity) {
2147
+ return granularity === "day" ? "per day" : granularity === "week" ? "per week" : "per month";
2148
+ }
2149
+ function helpLines(width) {
2150
+ const lines = [
2151
+ { text: "keys", tone: HEADER_TONE },
2152
+ { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
2153
+ { text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
2154
+ { text: " t shift+t previous / next range" },
2155
+ { text: " s shift+s cycle sort column \xB7 reverse" },
2156
+ { text: " b periods bucket: day \u2192 week \u2192 month" },
2157
+ { text: " a turns scope: this session \u2194 all sessions" },
2158
+ { text: " m p filter by model / provider (x clears)" },
2159
+ { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
2160
+ { text: " e db: backfill list-price estimates for the $0 steps" },
2161
+ { text: "" },
2162
+ { text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
2163
+ { text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
2164
+ { text: " forecast the monthly percentage at its reset, from the" },
2165
+ { text: " cycle's average pace (not a sample history)" },
2166
+ { text: " renews the monthly reset reported by the host" },
2167
+ { text: " the plugin reads the host's local usage-limits endpoint;" },
2168
+ { text: " it never reads your API key and never talks to the Console." },
2169
+ { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
2170
+ { text: " prompt everything the provider saw: cached + fresh + writes" },
2171
+ { text: " in the uncached part: fresh input + cache writes" },
2172
+ { text: " cached prompt read from the provider prompt cache" },
2173
+ { text: " write part of `in`: prompt written into that cache" },
2174
+ { text: " hit cached / prompt, weighted over the selection" },
2175
+ { text: " hit p50 median of the per-step hit: spots a split pattern" },
2176
+ { text: " out everything generated: visible output + reasoning" },
2177
+ { text: " reasoning part of `out`" },
2178
+ { text: " cost money, not tokens: a turn sums every step; $0 is left out" },
2179
+ { text: " other compaction/title usage: money with no assistant step;" },
2180
+ { text: " overview, periods and sessions include it; model rows do not" },
2181
+ { text: " \u2248 list-price estimate for steps the host reported as $0;" },
2182
+ { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
2183
+ { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
2184
+ { text: " tps out / streaming seconds, shown as p50" },
2185
+ { text: " switches how often a step's model or provider differs from the step" },
2186
+ { text: " before it in the same session (the models view's detail), with" },
2187
+ { text: " the cache a provider switch cost" },
2188
+ { text: "" },
2189
+ { text: "identity", tone: HEADER_TONE },
2190
+ { text: " provider the provider the model ran through, as OpenCode is configured" },
2191
+ { text: " (opencode, opencode-go, deepseek, \u2026). A gateway may re-route" },
2192
+ { text: " a request, but the upstream that ran the inference is not" },
2193
+ { text: " observable, so the provider is the identity every view shows." },
2194
+ { text: "" },
2195
+ { text: "database", tone: HEADER_TONE },
2196
+ { text: " the db view shows where the file lives, what it holds and how much" },
2197
+ { text: " of it is old: \u2191\u2193 pick a retention or wipe, enter asks before it" },
2198
+ { text: " deletes, e backfills list estimates, v gives the space back" },
2199
+ { text: " local time \xB7 SQLite in the OpenCode state directory" }
2200
+ ];
2201
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2202
+ }
2203
+ function quotaMeterLine(label, meter, now) {
2204
+ const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
2205
+ const countdown = formatCountdown(meter.resetsAt, now);
2206
+ return {
2207
+ text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
2208
+ tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
2209
+ };
2210
+ }
2211
+ function goQuotaLines(state, options) {
2212
+ const { now, width, loading, error } = options;
2213
+ const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
2214
+ const lines = [];
2215
+ const push = (text, tone = "base") => {
2216
+ lines.push({ text, tone });
2217
+ };
2218
+ if (state === undefined) {
2219
+ if (error !== undefined && error !== "")
2220
+ push(`Go quota unavailable: ${error}`, "warning");
2221
+ else if (loading === true)
2222
+ push("reading OpenCode Go quota\u2026", "muted");
2223
+ else
2224
+ push("OpenCode Go quota is unavailable", "muted");
2225
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2226
+ }
2227
+ if (state.kind === "none") {
2228
+ push(name, "accent");
2229
+ push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
2230
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2231
+ }
2232
+ const quota = state.quota;
2233
+ const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
2234
+ const status = quotaStatus(quota);
2235
+ const forecast = forecastMonthly(quota.monthly, now);
2236
+ push(`${name} \xB7 ${workspace}`, "accent");
2237
+ push(`status ${status}`, status === "active" ? "base" : "warning");
2238
+ lines.push(quotaMeterLine("rolling", quota.rolling, now));
2239
+ lines.push(quotaMeterLine("weekly", quota.weekly, now));
2240
+ lines.push(quotaMeterLine("monthly", quota.monthly, now));
2241
+ push("");
2242
+ if (forecast.reached || quota.monthly.limited) {
2243
+ push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
2244
+ } else if (now >= forecast.endAt) {
2245
+ push("forecast monthly reset due \xB7 refresh", "warning");
2246
+ } else if (!forecast.available) {
2247
+ push("forecast too early in the cycle to project a monthly pace", "muted");
2248
+ } else if (quota.monthly.percent === 0) {
2249
+ push("forecast no monthly usage yet this cycle", "muted");
2250
+ } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
2251
+ push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
2252
+ } else {
2253
+ const projected = Math.min(999, Math.round(forecast.projectedPercent));
2254
+ const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
2255
+ push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
2256
+ }
2257
+ const renewal = formatRenewal(quota.monthly.resetsAt);
2258
+ const countdown = formatCountdown(quota.monthly.resetsAt, now);
2259
+ push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
2260
+ if (quota.workspace?.usageURL !== undefined)
2261
+ push(`console ${quota.workspace.usageURL}`, "muted");
2262
+ const age = Math.max(0, now - quota.observedAt);
2263
+ push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
2264
+ if (loading === true)
2265
+ push("refreshing\u2026", "muted");
2266
+ if (error !== undefined && error !== "")
2267
+ push(`quota refresh failed: ${error}`, "warning");
2268
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2269
+ }
2270
+ function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
2271
+ if (state?.kind !== "ok" || width <= 0)
2272
+ return [];
2273
+ const quota = state.quota;
2274
+ const status = quotaStatus(quota);
2275
+ const forecast = forecastMonthly(quota.monthly, now);
2276
+ const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
2277
+ const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
2278
+ let forecastText = "forecast too early";
2279
+ let forecastTone = "muted";
2280
+ if (forecast.reached || quota.monthly.limited) {
2281
+ forecastText = "monthly limit reached";
2282
+ forecastTone = "warning";
2283
+ } else if (forecast.willExhaust) {
2284
+ forecastText = "limit before renewal";
2285
+ forecastTone = "warning";
2286
+ } else if (forecast.available && quota.monthly.percent > 0) {
2287
+ forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
2288
+ } else if (forecast.available && quota.monthly.percent === 0) {
2289
+ forecastText = "forecast no usage yet";
2290
+ }
2291
+ return [
2292
+ { text: truncate(name, width), tone: "accent" },
2293
+ { text: truncate(base, width), tone: baseTone },
2294
+ { text: truncate(forecastText, width), tone: forecastTone },
2295
+ { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
2296
+ ];
2297
+ }
2298
+ function usagePairs(usage, estimates = true) {
2299
+ if (usage === undefined)
2300
+ return [];
2301
+ const buckets = usageBuckets(usage);
2302
+ const pairs = [
2303
+ ["steps", formatCount(buckets.steps)],
2304
+ ["in", formatTokens(buckets.input)],
2305
+ ["prompt", formatTokens(buckets.prompt)],
2306
+ ["cached", formatTokens(buckets.cached)],
2307
+ ["hit", formatPercent(buckets.hit)],
2308
+ ["out", formatTokens(buckets.output)],
2309
+ ["write", formatTokens(buckets.cacheWrite)]
2310
+ ];
2311
+ if (buckets.reasoning > 0)
2312
+ pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
2313
+ pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
2314
+ const other = usage.otherCost ?? 0;
2315
+ if (other > 0)
2316
+ pairs.push(["other", `${formatCost(other)} comp/title`]);
2317
+ if ("tps" in usage && usage.tps !== undefined)
2318
+ pairs.push(["tps", formatTps(usage.tps)]);
2319
+ return pairs;
2320
+ }
2321
+ function overviewLines(data, width) {
2322
+ const lines = [];
2323
+ const estimates = data.estimates !== false;
2324
+ lines.push({
2325
+ text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
2326
+ tone: "muted"
2327
+ });
2328
+ lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
2329
+ if (data.activity !== undefined && data.activity.length > 1) {
2330
+ const series = reduceSeries(data.activity);
2331
+ lines.push({ text: "", tone: "muted" });
2332
+ lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
2333
+ }
2334
+ if (data.session !== undefined) {
2335
+ lines.push({ text: "", tone: "muted" });
2336
+ lines.push({ text: "this session", tone: HEADER_TONE });
2337
+ lines.push(...kvGrid(buildOverviewPairs(data.session, "session", estimates), width));
2338
+ if (data.subagents !== undefined && data.subagents.length > 0) {
2339
+ const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0);
2340
+ const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
2341
+ const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
2342
+ lines.push({
2343
+ text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
2344
+ tone: "muted"
2345
+ });
2346
+ }
2347
+ }
2348
+ if (data.coverage !== undefined) {
2349
+ lines.push({ text: "", tone: "muted" });
2350
+ lines.push({ text: "data coverage", tone: HEADER_TONE });
2351
+ lines.push(...kvGrid(coveragePairs(data.coverage), width));
2352
+ }
2353
+ return lines;
2354
+ }
2355
+ function buildOverviewPairs(usage, scope, estimates = true) {
2356
+ const pairs = usagePairs(usage, estimates);
2357
+ if (scope === "all") {
2358
+ pairs.push(["first", usage.firstAt === undefined ? "\u2013" : new Date(usage.firstAt).toLocaleString("en-GB")]);
2359
+ pairs.push(["last", usage.lastAt === undefined ? "\u2013" : new Date(usage.lastAt).toLocaleString("en-GB")]);
2360
+ }
2361
+ return pairs;
2362
+ }
2363
+ function coveragePairs(coverage) {
2364
+ const share = (missing) => coverage.steps === 0 ? "\u2013" : `${(missing / coverage.steps * 100).toFixed(1)}%`;
2365
+ return [
2366
+ ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
2367
+ ["providers", formatCount(coverage.providers)],
2368
+ ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
2369
+ [
2370
+ "window",
2371
+ `${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
2372
+ ]
2373
+ ];
2374
+ }
2375
+ function modelColumns(width) {
2376
+ const layouts = [
2377
+ { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
2378
+ { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
2379
+ { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
2380
+ { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
2381
+ { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
2382
+ ];
2383
+ for (const layout of layouts) {
2384
+ const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
2385
+ if (total <= width)
2386
+ return layout;
2387
+ }
2388
+ return layouts[layouts.length - 1];
2389
+ }
2390
+ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2391
+ const columns = modelColumns(width);
2392
+ const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
2393
+ const aligns = ["left", "right", "right", "right"];
2394
+ const header = ["model", "steps", "prompt", "cached"];
2395
+ if (columns.hit > 0) {
2396
+ widths.push(columns.hit);
2397
+ aligns.push("right");
2398
+ header.push("hit");
2399
+ }
2400
+ widths.push(columns.out);
2401
+ aligns.push("right");
2402
+ header.push("out");
2403
+ if (columns.cost > 0) {
2404
+ widths.push(columns.cost);
2405
+ aligns.push("right");
2406
+ header.push("cost");
2407
+ }
2408
+ if (columns.spread > 0) {
2409
+ widths.push(columns.spread);
2410
+ aligns.push("left");
2411
+ header.push("providers");
2412
+ }
2413
+ const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
2414
+ for (const model of rows.slice(0, limit)) {
2415
+ const key = modelKey(model.modelID, model.variant);
2416
+ const name = modelCell(model.modelID, model.variant, columns.model);
2417
+ const buckets = usageBuckets(model.totals);
2418
+ const providers = unique(model.providers.map((provider) => provider.providerID));
2419
+ const cache = extras?.cache?.get(key);
2420
+ const switches = extras?.switches?.get(key);
2421
+ const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
2422
+ if (columns.hit > 0)
2423
+ cells.push(formatPercent(cache?.hit ?? buckets.hit));
2424
+ cells.push(formatTokens(buckets.output));
2425
+ if (columns.cost > 0)
2426
+ cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
2427
+ if (columns.spread > 0)
2428
+ cells.push(providers.join(", "));
2429
+ lines.push({
2430
+ text: formatTableRow(cells, widths, aligns),
2431
+ tone: "base",
2432
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
2433
+ });
2434
+ const details = [];
2435
+ if (cache !== undefined)
2436
+ details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
2437
+ if (switches !== undefined && switches.changes > 0) {
2438
+ const scope = switches.providerChanges > 0 ? ` (${formatCount(switches.providerChanges)} provider)` : "";
2439
+ details.push(`${count(switches.changes, "switch", "switches")}${scope}`);
2440
+ if (switches.cacheLost > 0)
2441
+ details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
2442
+ }
2443
+ if (details.length > 0) {
2444
+ lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
2445
+ }
2446
+ }
2447
+ if (rows.length > limit)
2448
+ lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
2449
+ if (rows.length === 0)
2450
+ lines.push({ text: "no usage recorded for this range", tone: "muted" });
2451
+ return lines;
2452
+ }
2453
+ function unique(values) {
2454
+ return [...new Set(values)];
2455
+ }
2456
+ var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
2457
+ function fitColumns(columns, width) {
2458
+ const chosen = [...columns];
2459
+ while (chosen.length > 1 && tableWidth(chosen) > width) {
2460
+ const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
2461
+ if (optional === -1)
2462
+ break;
2463
+ chosen.splice(chosen.length - 1 - optional, 1);
2464
+ }
2465
+ return chosen;
2466
+ }
2467
+ function renderTable(rows, columns, width, options) {
2468
+ const chosen = fitColumns(columns, width);
2469
+ const widths = chosen.map((column) => column.width);
2470
+ const aligns = chosen.map((column) => column.align ?? "left");
2471
+ const alignsTyped = aligns;
2472
+ const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
2473
+ if (rows.length === 0)
2474
+ lines.push({ text: options.empty, tone: "muted" });
2475
+ for (const row of rows.slice(0, options.limit)) {
2476
+ const identity = options.row?.(row);
2477
+ lines.push({
2478
+ text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
2479
+ tone: options.tone?.(row) ?? "base",
2480
+ ...identity === undefined ? {} : { row: identity }
2481
+ });
2482
+ }
2483
+ if (rows.length > options.limit)
2484
+ lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
2485
+ return lines;
2486
+ }
2487
+ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2488
+ const lines = renderTable(rows, [
2489
+ { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
2490
+ { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
2491
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2492
+ { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2493
+ { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2494
+ { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2495
+ { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2496
+ { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2497
+ { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2498
+ { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2499
+ ], width, {
2500
+ limit,
2501
+ empty: "no usage recorded for this range",
2502
+ row: (row) => row.provider === undefined ? undefined : { kind: "provider", value: row.provider },
2503
+ tone: (row) => row.provider === undefined ? "muted" : "base"
2504
+ });
2505
+ return lines;
2506
+ }
2507
+ function providerLines(rows, width, limit = 40, estimates = true) {
2508
+ return renderTable(rows, [
2509
+ { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
2510
+ { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
2511
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2512
+ { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2513
+ { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2514
+ { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2515
+ { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2516
+ { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2517
+ { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2518
+ { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2519
+ ], width, {
2520
+ limit,
2521
+ empty: "no usage recorded for this range",
2522
+ row: (row) => ({ kind: "model", value: row.modelID, ...row.variant !== undefined ? { variant: row.variant } : {} }),
2523
+ tone: (row) => row.provider === undefined ? "muted" : "base"
2524
+ });
2525
+ }
2526
+ function cacheLines(data, width) {
2527
+ const lines = [];
2528
+ const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
2529
+ lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
2530
+ for (const reason of ["expired", "compaction", "unknown"]) {
2531
+ const group = data.drops.filter((drop) => drop.reason === reason);
2532
+ if (group.length === 0)
2533
+ continue;
2534
+ const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
2535
+ lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
2536
+ }
2537
+ if (data.drops.length === 0)
2538
+ lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
2539
+ if (data.models !== undefined && data.models.length > 0) {
2540
+ lines.push({ text: "", tone: "muted" });
2541
+ lines.push({ text: "reuse by model", tone: HEADER_TONE });
2542
+ const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
2543
+ lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
2544
+ for (const row of data.models.slice(0, 10)) {
2545
+ const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
2546
+ lines.push({
2547
+ text: formatTableRow([name, formatCount(row.cache.steps), formatTokens(row.cache.prompt), formatTokens(row.cache.cached), formatTokens(row.cache.cacheWrite), formatPercent(row.cache.hit), formatPercent(row.cache.hitP50)], widths, ["left", "right", "right", "right", "right", "right", "right"]),
2548
+ tone: "base",
2549
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
2550
+ });
2551
+ }
2552
+ }
2553
+ if (data.gap !== undefined && data.gap.samples > 0) {
2554
+ lines.push({ text: "", tone: "muted" });
2555
+ lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
2556
+ const widths = [9, 8, 9, 9, 10];
2557
+ lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
2558
+ for (const bucket of data.gap.buckets) {
2559
+ if (bucket.samples === 0)
2560
+ continue;
2561
+ lines.push({
2562
+ text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
2563
+ tone: bucket.drops > 0 ? "warning" : "base"
2564
+ });
2565
+ }
2566
+ if (data.gap.providers.length > 1) {
2567
+ lines.push({ text: "", tone: "muted" });
2568
+ lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
2569
+ const providerWidths = [26, 8, 9, 9];
2570
+ lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
2571
+ for (const row of data.gap.providers.slice(0, 8)) {
2572
+ lines.push({
2573
+ text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
2574
+ tone: "base"
2575
+ });
2576
+ }
2577
+ }
2578
+ }
2579
+ lines.push({ text: "", tone: "muted" });
2580
+ lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
2581
+ if (data.evidence.length === 0) {
2582
+ lines.push({ text: " no comparable step pairs yet", tone: "muted" });
2583
+ } else {
2584
+ const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
2585
+ lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
2586
+ for (const row of data.evidence.slice(0, 10)) {
2587
+ lines.push({
2588
+ text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
2589
+ tone: "base"
2590
+ });
2591
+ }
2592
+ }
2593
+ if (data.drops.length > 0) {
2594
+ lines.push({ text: "", tone: "muted" });
2595
+ lines.push({ text: "recent losses", tone: HEADER_TONE });
2596
+ for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
2597
+ const when = new Date(drop.at).toLocaleTimeString("en-GB");
2598
+ lines.push({
2599
+ text: formatTableRow([when, `${drop.providerID ?? ""}/${drop.modelID ?? ""}`, `\u2212${formatTokens(drop.tokens)}`, `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}`], [10, Math.max(20, Math.floor(width * 0.42)), 10, 24], ["left", "left", "right", "left"]),
2600
+ tone: drop.reason === "expired" ? "warning" : "base"
2601
+ });
2602
+ }
2603
+ }
2604
+ return lines;
2605
+ }
2606
+ function periodLines(rows, width, granularity, limit = 40, estimates = true, totalSessions) {
2607
+ const lines = [];
2608
+ const totals = rows.reduce((sum, row) => {
2609
+ sum.steps += row.usage.steps;
2610
+ sum.sessions += row.sessions;
2611
+ sum.input += row.usage.input;
2612
+ sum.cached += row.usage.cached;
2613
+ sum.cacheWrite += row.usage.cacheWrite;
2614
+ sum.output += row.usage.output;
2615
+ sum.reasoning += row.usage.reasoning;
2616
+ sum.cost += row.usage.cost;
2617
+ sum.listCost += row.usage.listCost;
2618
+ return sum;
2619
+ }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
2620
+ const overall = usageBuckets(totals);
2621
+ lines.push({
2622
+ text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
2623
+ tone: "muted"
2624
+ });
2625
+ if (rows.length > 1) {
2626
+ lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
2627
+ lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
2628
+ lines.push({
2629
+ text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
2630
+ tone: "muted"
2631
+ });
2632
+ }
2633
+ const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
2634
+ const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
2635
+ const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
2636
+ const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
2637
+ lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
2638
+ const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
2639
+ for (const row of newest) {
2640
+ const buckets = usageBuckets(row.usage);
2641
+ const cells = [
2642
+ row.label,
2643
+ formatCount(row.steps),
2644
+ ...withSessions ? [formatCount(row.sessions)] : [],
2645
+ formatTokens(buckets.prompt),
2646
+ formatTokens(buckets.cached),
2647
+ formatPercent(buckets.hit, 0),
2648
+ formatTokens(buckets.output),
2649
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2650
+ ];
2651
+ lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
2652
+ }
2653
+ lines.push({ text: "", tone: "muted" });
2654
+ lines.push({
2655
+ text: formatTableRow([
2656
+ "total",
2657
+ formatCount(totals.steps),
2658
+ ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
2659
+ formatTokens(overall.prompt),
2660
+ formatTokens(overall.cached),
2661
+ formatPercent(overall.hit, 0),
2662
+ formatTokens(overall.output),
2663
+ formatSpend(overall.cost, estimates ? overall.listCost : 0)
2664
+ ], widths, aligns),
2665
+ tone: HEADER_TONE
2666
+ });
2667
+ if (rows.length === 0)
2668
+ lines.push({ text: "no usage recorded for this range", tone: "muted" });
2669
+ return lines;
2670
+ }
2671
+ function latencyLines(report, width, groups, limit = 12, estimates = true) {
2672
+ const lines = [];
2673
+ lines.push({
2674
+ text: formatTableRow(["wall", "p50", formatMs(report.wall.p50), "p90", formatMs(report.wall.p90), "p99", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`], [10, 4, 9, 4, 9, 4, 9, 12]),
2675
+ tone: "base"
2676
+ });
2677
+ lines.push({
2678
+ 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]),
2679
+ tone: "base"
2680
+ });
2681
+ lines.push({
2682
+ 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]),
2683
+ tone: "base"
2684
+ });
2685
+ lines.push({ text: "", tone: "muted" });
2686
+ lines.push({
2687
+ text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
2688
+ tone: "muted"
2689
+ });
2690
+ if (report.wall.count === 0)
2691
+ lines.push({ text: "no completed steps for this range", tone: "muted" });
2692
+ if (groups !== undefined && groups.length > 0) {
2693
+ lines.push({ text: "", tone: "muted" });
2694
+ lines.push({ text: "by group", tone: HEADER_TONE });
2695
+ const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
2696
+ const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
2697
+ lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
2698
+ for (const row of groups.slice(0, limit)) {
2699
+ const thin = row.count < 5;
2700
+ lines.push({
2701
+ text: formatTableRow([
2702
+ row.label,
2703
+ formatCount(row.count),
2704
+ formatMs(row.wall.p50),
2705
+ formatMs(row.wall.p90),
2706
+ formatMs(row.stream.p50),
2707
+ formatTps(row.tps.p50),
2708
+ formatTps(row.tps.p90),
2709
+ formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
2710
+ ], widths, aligns),
2711
+ tone: thin ? "muted" : "base",
2712
+ row: { kind: "model", value: row.key }
2713
+ });
2714
+ }
2715
+ lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
2716
+ }
2717
+ return lines;
2718
+ }
2719
+ function sessionsLines(rows, width, options) {
2720
+ const limit = options?.limit ?? 20;
2721
+ const estimates = options?.estimates !== false;
2722
+ const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
2723
+ const aligns = ["left", "right", "right", "right", "right", "right", "right"];
2724
+ const lines = [
2725
+ { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
2726
+ ];
2727
+ const byID = new Map(rows.map((row) => [row.sessionID, row]));
2728
+ const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
2729
+ const children = rows.filter((row) => row.parentID !== undefined && byID.has(row.parentID));
2730
+ const orderedAll = [...ordered, ...children];
2731
+ for (const row of orderedAll.slice(0, limit)) {
2732
+ const child = row.parentID !== undefined && byID.has(row.parentID);
2733
+ const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
2734
+ const buckets = usageBuckets(row);
2735
+ lines.push({
2736
+ text: formatTableRow([
2737
+ `${child ? "\u21B3 " : ""}${title}`,
2738
+ formatCount(buckets.steps),
2739
+ formatTokens(buckets.prompt),
2740
+ formatTokens(buckets.cached),
2741
+ formatPercent(buckets.hit, 0),
2742
+ formatTokens(buckets.output),
2743
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2744
+ ], widths, aligns),
2745
+ tone: child ? "muted" : "base",
2746
+ row: { kind: "session", value: row.sessionID }
2747
+ });
2748
+ const details = [
2749
+ row.directory ?? "",
2750
+ row.models.length > 1 ? count(row.models.length, "model") : "",
2751
+ (row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost)}` : ""
2752
+ ].filter((part) => part !== "").join(" \xB7 ");
2753
+ lines.push({ text: truncate(`${" ".repeat(child ? 2 : 0)} ${details}`, width), tone: "muted" });
2754
+ }
2755
+ if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {
2756
+ const share = rows.reduce((sum, row) => sum + row.steps, 0);
2757
+ lines.push({ text: "", tone: "muted" });
2758
+ lines.push({
2759
+ text: `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${formatSpend(options.rollup.subagentCost, estimates ? options.rollup.subagentListCost ?? 0 : 0)}`,
2760
+ tone: "muted"
2761
+ });
2762
+ }
2763
+ if (rows.length > limit)
2764
+ lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
2765
+ if (rows.length === 0)
2766
+ lines.push({ text: "no sessions recorded for this range", tone: "muted" });
2767
+ return lines;
2768
+ }
2769
+ function dbLines(data, width) {
2770
+ const lines = [];
2771
+ const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
2772
+ lines.push({ text: truncate(data.info.path, width), tone: "base" });
2773
+ lines.push({
2774
+ text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
2775
+ tone: "muted"
2776
+ });
2777
+ lines.push({ text: "", tone: "muted" });
2778
+ lines.push({ text: "what it holds", tone: HEADER_TONE });
2779
+ for (const table of data.info.tables) {
2780
+ lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
2781
+ }
2782
+ lines.push({
2783
+ text: ` window ${data.info.firstAt === undefined ? "\u2013" : new Date(data.info.firstAt).toLocaleDateString("en-GB")} \u2192 ${data.info.lastAt === undefined ? "\u2013" : new Date(data.info.lastAt).toLocaleDateString("en-GB")}`,
2784
+ tone: "muted"
2785
+ });
2786
+ lines.push({ text: "", tone: "muted" });
2787
+ lines.push({ text: "clean up", tone: HEADER_TONE });
2788
+ lines.push({
2789
+ text: truncate(` \u2191\u2193 pick a retention \xB7 enter prunes from its cutoff \xB7 the wipe row deletes everything (asks first)${data.estimates === false ? "" : " \xB7 e backfills list estimates"} \xB7 v gives the space back`, width),
2790
+ tone: "muted",
2791
+ hint: true
2792
+ });
2793
+ if (data.estimates !== false) {
2794
+ lines.push({
2795
+ text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price`, width),
2796
+ tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
2797
+ });
2798
+ }
2799
+ const widths = [10, 13, 10];
2800
+ lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
2801
+ for (const option of data.info.removable) {
2802
+ const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
2803
+ lines.push({
2804
+ text: formatTableRow([`${option.days} days`, `${formatCount(option.steps)} steps`, before], widths, ["left", "right", "left"]),
2805
+ tone: option.steps === 0 ? "muted" : "base",
2806
+ row: { kind: "prune", value: String(option.days) }
2807
+ });
2808
+ }
2809
+ const steps = data.info.tables.find((table) => table.name === "steps")?.rows ?? 0;
2810
+ const sessions = data.info.tables.find((table) => table.name === "sessions")?.rows ?? 0;
2811
+ lines.push({ text: "", tone: "muted" });
2812
+ lines.push({
2813
+ text: truncate(` wipe everything \xB7 ${formatCount(steps)} steps \xB7 ${formatCount(sessions)} sessions \xB7 cannot be undone`, width),
2814
+ tone: steps === 0 && sessions === 0 ? "muted" : "warning",
2815
+ row: { kind: "wipe", value: "all" }
2816
+ });
2817
+ if (data.busy === true) {
2818
+ lines.push({ text: "", tone: "muted" });
2819
+ lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
2820
+ }
2821
+ return lines;
2822
+ }
2823
+ function turnStats(turn) {
2824
+ return {
2825
+ endAt: turn.endAt,
2826
+ startAt: turn.promptAt ?? turn.endAt,
2827
+ promptAt: turn.promptAt,
2828
+ promptGapMs: turn.promptGapMs,
2829
+ providerID: turn.providerID,
2830
+ modelID: turn.modelID,
2831
+ variant: turn.variant,
2832
+ providerChanged: turn.providerChanged,
2833
+ modelChanged: turn.modelChanged,
2834
+ totals: turn.totals,
2835
+ latest: turn.latest,
2836
+ session: undefined,
2837
+ drops: turn.drops.map((drop) => ({ messageID: drop.messageID, tokens: drop.tokens, prevCached: 0, gapMs: drop.gapMs })),
2838
+ cacheDropTokens: turn.drops.reduce((sum, drop) => sum + drop.tokens, 0),
2839
+ cacheExpired: turn.drops.length > 0,
2840
+ steps: turn.steps
2841
+ };
2842
+ }
2843
+ function turnsLines(rows, width, options) {
2844
+ const lines = [];
2845
+ const warning = rows.filter((turn) => turn.drops.length > 0).length;
2846
+ lines.push({
2847
+ text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
2848
+ tone: "muted"
2849
+ });
2850
+ const showSession = options?.sessionTitles !== undefined;
2851
+ for (const turn of rows) {
2852
+ const line = formatLine(turnStats(turn), {
2853
+ ...options,
2854
+ fields: { ...options?.fields, session: false }
2855
+ });
2856
+ const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
2857
+ lines.push({
2858
+ text: truncate(`${title}${line}`, width),
2859
+ tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
2860
+ row: { kind: "turn", value: turn.sessionID }
2861
+ });
2862
+ }
2863
+ if (rows.length === 0)
2864
+ lines.push({ text: "no finished turns for this range", tone: "muted" });
2865
+ return lines;
2866
+ }
2867
+ function sessionSummaryLines(usage, budget = 34, estimates = true) {
2868
+ const buckets = usageBuckets(usage);
2869
+ const steps = formatCount(buckets.steps);
2870
+ const input = formatTokens(buckets.input);
2871
+ const cached = formatTokens(buckets.cached);
2872
+ const out = formatTokens(buckets.output);
2873
+ const hit = formatPercent(buckets.hit);
2874
+ const tps = formatTpsCompact(usage.tps);
2875
+ const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
2876
+ const first = [
2877
+ ` ${steps} steps \xB7 in ${input}`,
2878
+ ` ${steps} steps`
2879
+ ].find((text) => text.length <= budget);
2880
+ const second = [
2881
+ ` cached ${cached} \xB7 out ${out}`,
2882
+ ` cached ${cached}`
2883
+ ].find((text) => text.length <= budget);
2884
+ const last = [
2885
+ ` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
2886
+ ` hit ${hit} \xB7 ${cost}`,
2887
+ ` ${cost}`
2888
+ ].find((text) => text.length <= budget);
2889
+ return [
2890
+ { text: truncate("session", budget), tone: HEADER_TONE },
2891
+ { text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
2892
+ { text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
2893
+ { text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
2894
+ { text: "", tone: "muted" }
2895
+ ];
2896
+ }
2897
+ function sidebarLines(rows, options) {
2898
+ const budget = options?.budget ?? 34;
2899
+ const labels = { input: options?.labels?.input ?? "in", output: options?.labels?.output ?? "out" };
2900
+ const lines = [];
2901
+ for (const [index, turn] of rows.entries()) {
2902
+ const clock = turn.endAt !== undefined ? formatClock(turn.endAt).slice(0, 5) : "--:--";
2903
+ const provider = turn.providerID ?? "unknown";
2904
+ const display = displayTotals(turn.latest);
2905
+ const input = formatTokens(display.input);
2906
+ const prompt = formatTokens(display.prompt);
2907
+ const output = formatTokens(display.output);
2908
+ const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
2909
+ const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
2910
+ const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
2911
+ const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
2912
+ const header = `${clock} ${provider}`;
2913
+ const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
2914
+ const volumes = [
2915
+ ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
2916
+ ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
2917
+ ` ${labels.input} ${input}`
2918
+ ];
2919
+ const facts = [
2920
+ ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
2921
+ ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
2922
+ ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
2923
+ ` hit ${hit}${suffix}`
2924
+ ];
2925
+ lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
2926
+ const edge = index === 0 || index === rows.length - 1;
2927
+ if (edge || turn.modelChanged || turn.providerChanged) {
2928
+ const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
2929
+ lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
2930
+ }
2931
+ lines.push({
2932
+ text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
2933
+ tone: "muted"
2934
+ });
2935
+ lines.push({
2936
+ text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
2937
+ tone: turn.drops.length > 0 ? "warning" : "muted"
2938
+ });
2939
+ }
2940
+ if (rows.length === 0)
2941
+ lines.push({ text: "no finished turns yet", tone: "muted" });
2942
+ return lines;
2943
+ }
2944
+
2945
+ // src/panel-build.ts
2946
+ function detailLabel(row) {
2947
+ switch (row.kind) {
2948
+ case "model":
2949
+ return `model ${row.variant !== undefined ? `${row.value} ${row.variant}` : row.value}`;
2950
+ case "session":
2951
+ case "turn":
2952
+ return `session ${row.value}`;
2953
+ case "period":
2954
+ return `period ${row.value}`;
2955
+ case "provider":
2956
+ return `provider ${row.value}`;
2957
+ case "prune":
2958
+ return `prune older than ${row.value} days`;
2959
+ case "wipe":
2960
+ return "wipe all recorded usage";
2961
+ }
2962
+ }
2963
+ function buildPanel(request) {
2964
+ try {
2965
+ return build(request);
2966
+ } catch (error) {
2967
+ const message = error instanceof Error ? error.message : String(error);
2968
+ return [{ text: `stats query failed: ${message}`, tone: "warning" }];
2969
+ }
2970
+ }
2971
+ function build(request) {
2972
+ const { db, view, now, sessionStart, width } = request;
2973
+ const estimates = request.estimates !== false;
2974
+ const scoped = request.range === "session" && request.sessionID !== "";
2975
+ const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
2976
+ const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
2977
+ if (request.detail !== undefined)
2978
+ return buildDetail(request, range, filters, estimates);
2979
+ switch (view) {
2980
+ case "overview": {
2981
+ const usage = overview(db, range, filters);
2982
+ const sessionUsage = request.sessionID === "" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID });
2983
+ const childIDs = request.sessionID === "" ? [] : childSessionIDs(db, request.sessionID);
2984
+ const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs);
2985
+ return overviewLines({
2986
+ usage,
2987
+ session: sessionUsage,
2988
+ ...children.length > 0 ? { subagents: children } : {},
2989
+ range: request.range,
2990
+ activity: activityOf(db, range, filters, now),
2991
+ coverage: coverageOf(db, { range, filters }),
2992
+ estimates
2993
+ }, width);
2994
+ }
2995
+ case "models": {
2996
+ const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
2997
+ const pairs = cachePairs(db, { range, filters });
2998
+ const switches = switchesOf(pairs);
2999
+ return modelsLines(rows, width, {
3000
+ cache: cacheByModel(pairs),
3001
+ switches: switchesByModel(switches.rows)
3002
+ }, 40, estimates);
3003
+ }
3004
+ case "providers":
3005
+ return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
3006
+ case "cache": {
3007
+ const pairs = cachePairs(db, { range, filters });
3008
+ return cacheLines({
3009
+ drops: cacheDropsOf(db, pairs),
3010
+ evidence: ttlEvidenceOf(pairs),
3011
+ gap: gapReportOf(pairs),
3012
+ models: topCacheModels(pairs)
3013
+ }, width);
3014
+ }
3015
+ case "periods": {
3016
+ const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters));
3017
+ const sessions = overview(db, range, filters).sessions;
3018
+ return periodLines(rows, width, request.granularity, 40, estimates, sessions);
3019
+ }
3020
+ case "latency": {
3021
+ const timings = timingRows(db, { range, filters });
3022
+ const by = filters.modelID !== undefined ? "provider" : "model";
3023
+ return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
3024
+ }
3025
+ case "sessions": {
3026
+ const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates);
3027
+ const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
3028
+ return sessionsLines(rows, width, {
3029
+ limit: 20,
3030
+ estimates,
3031
+ rollup: {
3032
+ subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),
3033
+ subagentCost: child.reduce((sum, row) => sum + row.cost, 0),
3034
+ subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0)
3035
+ }
3036
+ });
3037
+ }
3038
+ case "db":
3039
+ return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now, estimates }, width);
3040
+ case "go":
3041
+ return [
3042
+ {
3043
+ text: "OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.",
3044
+ tone: "muted"
3045
+ }
3046
+ ];
3047
+ case "turns": {
3048
+ const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
3049
+ const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
3050
+ const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
3051
+ return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
3052
+ }
3053
+ }
3054
+ }
3055
+ function rangeForRequest(key, now) {
3056
+ switch (key) {
3057
+ case "today": {
3058
+ const start = new Date(now);
3059
+ start.setHours(0, 0, 0, 0);
3060
+ return { from: start.getTime() };
3061
+ }
3062
+ case "7d":
3063
+ return { from: now - 7 * 24 * 60 * 60 * 1000 };
3064
+ case "30d":
3065
+ return { from: now - 30 * 24 * 60 * 60 * 1000 };
3066
+ default:
3067
+ return;
3068
+ }
3069
+ }
3070
+ function buildDetail(request, range, filters, estimates) {
3071
+ const row = request.detail;
3072
+ const db = request.db;
3073
+ const width = request.width;
3074
+ const head = { text: detailLabel(row), tone: "accent" };
3075
+ const back = { text: "backspace returns \xB7 the header shows where you came from", tone: "muted" };
3076
+ if (row.kind === "model") {
3077
+ const scoped = { ...filters, modelKey: modelKey(row.value, row.variant) };
3078
+ const stats = cacheStatsOf(db, { range, filters: scoped });
3079
+ const steps = stepRows(db, { range, filters: scoped });
3080
+ return [
3081
+ head,
3082
+ {
3083
+ text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 write ${formatTokens(stats.cacheWrite)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3084
+ tone: "muted"
3085
+ },
3086
+ { text: "", tone: "muted" },
3087
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3088
+ { text: "", tone: "muted" },
3089
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
3090
+ { text: "", tone: "muted" },
3091
+ back
3092
+ ];
3093
+ }
3094
+ if (row.kind === "session" || row.kind === "turn") {
3095
+ const rows = turns(db, { sessionID: row.value, limit: 80 });
3096
+ return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: "", tone: "muted" }, back];
3097
+ }
3098
+ if (row.kind === "provider") {
3099
+ const scoped = { ...filters, provider: row.value };
3100
+ const steps = stepRows(db, { range, filters: scoped });
3101
+ const stats = cacheStatsOf(db, { range, filters: scoped });
3102
+ return [
3103
+ head,
3104
+ {
3105
+ text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3106
+ tone: "muted"
3107
+ },
3108
+ { text: "", tone: "muted" },
3109
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3110
+ { text: "", tone: "muted" },
3111
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
3112
+ { text: "", tone: "muted" },
3113
+ back
3114
+ ];
3115
+ }
3116
+ if (row.kind === "period") {
3117
+ const periods = periodsOf(stepRows(db, { range, filters }), request.granularity);
3118
+ const period = periods.find((entry) => entry.key === row.value);
3119
+ const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at);
3120
+ const to = period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY);
3121
+ const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters });
3122
+ return [
3123
+ head,
3124
+ { text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
3125
+ { text: "", tone: "muted" },
3126
+ ...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),
3127
+ { text: "", tone: "muted" },
3128
+ back
3129
+ ];
3130
+ }
3131
+ return [head, back];
3132
+ }
3133
+ function percent(value) {
3134
+ return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
3135
+ }
3136
+ function sortModels(rows, sort, desc, estimates = true) {
3137
+ const sign = desc ? 1 : -1;
3138
+ const pick = (model) => {
3139
+ if (sort === "cached")
3140
+ return model.totals.cached;
3141
+ if (sort === "hit") {
3142
+ const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite;
3143
+ return prompt > 0 ? model.totals.cached / prompt : -1;
3144
+ }
3145
+ if (sort === "out")
3146
+ return model.totals.output + model.totals.reasoning;
3147
+ if (sort === "cost")
3148
+ return estimates ? spend(model.totals) : model.totals.cost;
3149
+ return model.totals.steps;
3150
+ };
3151
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3152
+ }
3153
+ function sortProviders(rows, sort, desc, estimates = true) {
3154
+ const sign = desc ? 1 : -1;
3155
+ const pick = (row) => {
3156
+ if (sort === "cached")
3157
+ return row.cache.cached;
3158
+ if (sort === "hit")
3159
+ return row.cache.hit ?? -1;
3160
+ if (sort === "cost")
3161
+ return estimates ? spend(row.usage) : row.usage.cost;
3162
+ if (sort === "share")
3163
+ return row.share;
3164
+ if (sort === "tps")
3165
+ return row.tps ?? -1;
3166
+ return row.usage.steps;
3167
+ };
3168
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3169
+ }
3170
+ function sortLatency(rows, sort, desc) {
3171
+ const sign = desc ? 1 : -1;
3172
+ const pick = (row) => {
3173
+ if (sort === "tps")
3174
+ return row.tps.p50 ?? -1;
3175
+ if (sort === "wall")
3176
+ return row.wall.p50 ?? -1;
3177
+ return row.count;
3178
+ };
3179
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3180
+ }
3181
+ function sortSessions(rows, sort, desc, estimates = true) {
3182
+ const sign = desc ? 1 : -1;
3183
+ const pick = (row) => {
3184
+ if (sort === "steps")
3185
+ return row.steps;
3186
+ if (sort === "cached")
3187
+ return row.cached;
3188
+ if (sort === "cost")
3189
+ return estimates ? spend(row) : row.cost;
3190
+ return row.lastAt ?? 0;
3191
+ };
3192
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3193
+ }
3194
+ function sortTurns(rows, sort, desc, estimates = true) {
3195
+ const sign = desc ? 1 : -1;
3196
+ const pick = (row) => {
3197
+ if (sort === "cost")
3198
+ return estimates ? spend(row.totals) : row.totals.cost;
3199
+ if (sort === "tokens")
3200
+ return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning;
3201
+ return row.endAt ?? 0;
3202
+ };
3203
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3204
+ }
3205
+ function cacheByModel(pairs) {
3206
+ const map = new Map;
3207
+ for (const row of cacheStatsByModel(pairs)) {
3208
+ map.set(modelKey(row.modelID, row.variant), row.cache);
3209
+ }
3210
+ return map;
3211
+ }
3212
+ function switchesByModel(rows) {
3213
+ return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]));
3214
+ }
3215
+ function topCacheModels(pairs) {
3216
+ return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
3217
+ }
3218
+ function activityOf(db, range, filters, now) {
3219
+ const filter = buildWhere(range, filters, STEP_TIME);
3220
+ const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params);
3221
+ const from = range?.from ?? earliest?.at ?? 0;
3222
+ const to = range?.to ?? now;
3223
+ const span = Math.max(1, to - from);
3224
+ const ladder = [3600000, 3 * 3600000, 6 * 3600000, 12 * 3600000, 86400000, 3 * 86400000, 7 * 86400000, 30 * 86400000];
3225
+ const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1];
3226
+ const rows = db.query(`SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps
3227
+ FROM steps ${filter.where}
3228
+ GROUP BY bucket ORDER BY bucket`).all(bucket, ...filter.params);
3229
+ if (rows.length === 0)
3230
+ return [];
3231
+ const first = Math.floor(from / bucket);
3232
+ const last = rows[rows.length - 1].bucket;
3233
+ const series = [];
3234
+ for (let index = first;index <= last; index += 1) {
3235
+ series.push(rows.find((row) => row.bucket === index)?.steps ?? 0);
3236
+ }
3237
+ return series;
3238
+ }
3239
+
3240
+ // src/pricing.ts
3241
+ function money(value) {
3242
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
3243
+ }
3244
+ function tokens(value) {
3245
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
3246
+ }
3247
+ function priceTable(models) {
3248
+ const table = new Map;
3249
+ if (!Array.isArray(models))
3250
+ return table;
3251
+ for (const model of models) {
3252
+ if (model === null || model === undefined)
3253
+ continue;
3254
+ const providerID = model.providerID;
3255
+ const modelID = model.modelID ?? model.id;
3256
+ if (typeof providerID !== "string" || providerID === "")
3257
+ continue;
3258
+ if (typeof modelID !== "string" || modelID === "")
3259
+ continue;
3260
+ if (!Array.isArray(model.cost) || model.cost.length === 0)
3261
+ continue;
3262
+ const tiers = [];
3263
+ for (const cost of model.cost) {
3264
+ if (cost === null || cost === undefined)
3265
+ continue;
3266
+ let tier;
3267
+ if (cost.tier !== undefined) {
3268
+ const size = cost.tier.size;
3269
+ if (typeof size !== "number" || !Number.isFinite(size))
3270
+ continue;
3271
+ tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
3272
+ }
3273
+ tiers.push({
3274
+ ...tier !== undefined ? { tier } : {},
3275
+ input: money(cost.input),
3276
+ output: money(cost.output),
3277
+ cacheRead: money(cost.cache?.read),
3278
+ cacheWrite: money(cost.cache?.write)
3279
+ });
3280
+ }
3281
+ if (tiers.length > 0)
3282
+ table.set(`${providerID}/${modelID}`, { tiers });
3283
+ }
3284
+ return table;
3285
+ }
3286
+ function priceOf(table, ref) {
3287
+ if (ref.providerID === undefined || ref.providerID === "")
3288
+ return;
3289
+ if (ref.modelID === undefined || ref.modelID === "")
3290
+ return;
3291
+ return table.get(`${ref.providerID}/${ref.modelID}`);
3292
+ }
3293
+ function costOf(table, ref, usage) {
3294
+ const price = priceOf(table, ref);
3295
+ if (price === undefined)
3296
+ return;
3297
+ const input = tokens(usage.input);
3298
+ const output = tokens(usage.output);
3299
+ const reasoning = tokens(usage.reasoning);
3300
+ const cacheRead = tokens(usage.cacheRead);
3301
+ const cacheWrite = tokens(usage.cacheWrite);
3302
+ const prompt = input + cacheRead + cacheWrite;
3303
+ const selected = price.tiers.filter((tier) => tier.tier?.type === "context" && prompt > tier.tier.size).sort((left, right) => (right.tier?.size ?? 0) - (left.tier?.size ?? 0))[0] ?? price.tiers.find((tier) => tier.tier === undefined);
3304
+ if (selected === undefined)
3305
+ return;
3306
+ if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
3307
+ return 0;
3308
+ const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
3309
+ if (!Number.isFinite(billed) || billed <= 0)
3310
+ return;
3311
+ return billed / 1e6;
3312
+ }
3313
+
3314
+ // src/stats/maintenance.ts
3315
+ import { statSync as statSync2 } from "fs";
3316
+ var STEP_TIME2 = "COALESCE(created_at, recorded_at)";
3317
+ var DAY = 24 * 60 * 60 * 1000;
3318
+ function size(path) {
3319
+ try {
3320
+ return statSync2(path).size;
3321
+ } catch {
3322
+ return 0;
3323
+ }
3324
+ }
3325
+ function hasTable(db, name) {
3326
+ try {
3327
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
3328
+ } catch {
3329
+ return false;
3330
+ }
3331
+ }
3332
+ function dbInfo(db, path, now = Date.now()) {
3333
+ const tables = TABLES.map((table) => ({
3334
+ name: table,
3335
+ rows: hasTable(db, table) ? db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n : 0
3336
+ }));
3337
+ const window = db.query(`SELECT MIN(${STEP_TIME2}) AS first, MAX(${STEP_TIME2}) AS last FROM steps`).get();
3338
+ const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
3339
+ return {
3340
+ path,
3341
+ unpriced: hasListCost(db) ? db.query(`SELECT COUNT(*) AS n FROM steps
3342
+ WHERE cost = 0 AND list_cost IS NULL
3343
+ AND provider_id IS NOT NULL AND provider_id <> ''
3344
+ AND model_id IS NOT NULL AND model_id <> ''
3345
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n : 0,
3346
+ bytes: size(path),
3347
+ walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
3348
+ schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
3349
+ tables,
3350
+ firstAt: window.first ?? undefined,
3351
+ lastAt: window.last ?? undefined,
3352
+ removable: [30, 90, 365].map((days) => ({
3353
+ days,
3354
+ steps: db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${STEP_TIME2} < ?`).get(now - days * DAY).n
3355
+ }))
3356
+ };
3357
+ }
3358
+ var PRUNE_BATCH = 5000;
3359
+ function deleteBatched(db, table, where, cutoff) {
3360
+ const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`);
3361
+ let removed = 0;
3362
+ for (;; ) {
3363
+ const changes = statement.run(cutoff).changes;
3364
+ removed += changes;
3365
+ if (changes < PRUNE_BATCH)
3366
+ break;
3367
+ }
3368
+ return removed;
3369
+ }
3370
+ function deleteAllBatched(db, table) {
3371
+ const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} LIMIT ${PRUNE_BATCH})`);
3372
+ let removed = 0;
3373
+ for (;; ) {
3374
+ const changes = statement.run().changes;
3375
+ removed += changes;
3376
+ if (changes < PRUNE_BATCH)
3377
+ break;
3378
+ }
3379
+ return removed;
3380
+ }
3381
+ function pruneOlderThan(db, cutoff) {
3382
+ return {
3383
+ steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
3384
+ prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
3385
+ events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
3386
+ usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
3387
+ };
3388
+ }
3389
+ function wipeAll(db) {
3390
+ return {
3391
+ steps: deleteAllBatched(db, "steps"),
3392
+ prompts: deleteAllBatched(db, "prompts"),
3393
+ events: deleteAllBatched(db, "events"),
3394
+ usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
3395
+ sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
3396
+ };
3397
+ }
3398
+ function footprint(path) {
3399
+ return size(path) + size(`${path}-wal`);
3400
+ }
3401
+ function vacuum(db, path) {
3402
+ const before = footprint(path);
3403
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
3404
+ db.exec("VACUUM");
3405
+ const after = footprint(path);
3406
+ return { before, after, freed: Math.max(0, before - after) };
3407
+ }
3408
+ function hasListCost(db) {
3409
+ try {
3410
+ return db.query("PRAGMA table_info(steps)").all().some((column) => column.name === "list_cost");
3411
+ } catch {
3412
+ return false;
3413
+ }
3414
+ }
3415
+ var BACKFILL_BATCH = 1000;
3416
+ function backfillListCost(db, price) {
3417
+ if (!hasListCost(db))
3418
+ return { candidates: 0, updated: 0 };
3419
+ const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
3420
+ WHERE cost = 0 AND list_cost IS NULL
3421
+ AND provider_id IS NOT NULL AND provider_id <> ''
3422
+ AND model_id IS NOT NULL AND model_id <> ''
3423
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
3424
+ if (candidates === 0)
3425
+ return { candidates: 0, updated: 0 };
3426
+ const select = db.query(`SELECT rowid, provider_id, model_id,
3427
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3428
+ FROM steps
3429
+ WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
3430
+ AND provider_id IS NOT NULL AND provider_id <> ''
3431
+ AND model_id IS NOT NULL AND model_id <> ''
3432
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
3433
+ ORDER BY rowid
3434
+ LIMIT ?`);
3435
+ const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
3436
+ let cursor = 0;
3437
+ let updated = 0;
3438
+ for (;; ) {
3439
+ const rows = select.all(cursor, BACKFILL_BATCH);
3440
+ if (rows.length === 0)
3441
+ break;
3442
+ db.transaction(() => {
3443
+ for (const row of rows) {
3444
+ const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
3445
+ input: row.input_tokens ?? 0,
3446
+ output: row.output_tokens ?? 0,
3447
+ reasoning: row.reasoning_tokens ?? 0,
3448
+ cacheRead: row.cache_read ?? 0,
3449
+ cacheWrite: row.cache_write ?? 0
3450
+ });
3451
+ if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
3452
+ continue;
3453
+ if (update.run(estimate, row.rowid).changes > 0)
3454
+ updated += 1;
3455
+ }
3456
+ })();
3457
+ cursor = rows[rows.length - 1].rowid;
3458
+ if (rows.length < BACKFILL_BATCH)
3459
+ break;
3460
+ }
3461
+ return { candidates, updated };
3462
+ }
3463
+
3464
+ // src/service.ts
3465
+ var DAY2 = 24 * 60 * 60 * 1000;
3466
+ var MAX_DAYS = 3650;
3467
+
3468
+ class ServiceError extends Error {
3469
+ code;
3470
+ constructor(code, message) {
3471
+ super(message);
3472
+ this.name = "ServiceError";
3473
+ this.code = code;
3474
+ }
3475
+ }
3476
+ function clamp2(value, minimum, maximum) {
3477
+ if (!Number.isFinite(value))
3478
+ return minimum;
3479
+ return Math.min(maximum, Math.max(minimum, Math.round(value)));
3480
+ }
3481
+ function sessionStart(db, sessionID) {
3482
+ const session = db.query("SELECT started_at AS at FROM sessions WHERE session_id = ?").get(sessionID);
3483
+ if (session?.at !== null && session?.at !== undefined)
3484
+ return session.at;
3485
+ const step = db.query("SELECT MIN(COALESCE(created_at, recorded_at)) AS at FROM steps WHERE session_id = ?").get(sessionID);
3486
+ return step?.at ?? undefined;
3487
+ }
3488
+ function redact(info, exposePaths) {
3489
+ if (exposePaths)
3490
+ return info;
3491
+ return { ...info, path: basename(info.path) };
3492
+ }
3493
+ function filtersOf(settings) {
3494
+ return {
3495
+ ...settings.modelID !== "" ? { modelID: settings.modelID } : {},
3496
+ ...settings.providerID !== "" ? { provider: settings.providerID } : {}
3497
+ };
3498
+ }
3499
+ function writeDb(path, run) {
3500
+ let db;
3501
+ try {
3502
+ db = openStatsDbWrite(path);
3503
+ return run(db);
3504
+ } catch (error) {
3505
+ if (error instanceof ServiceError)
3506
+ throw error;
3507
+ throw new ServiceError("busy", "the database is busy; try again in a moment");
3508
+ } finally {
3509
+ db?.close();
3510
+ }
3511
+ }
3512
+ function createService(db, options) {
3513
+ const settingsOf = (input) => sanitizeSettings(input.settings);
3514
+ function infoOf() {
3515
+ return redact(dbInfo(db(), options.path), options.exposePaths);
3516
+ }
3517
+ function panel(input) {
3518
+ const settings = settingsOf(input);
3519
+ const database = settings.view === "db" ? infoOf() : undefined;
3520
+ const width = clampPanelWidth(input.width);
3521
+ const filters = filtersOf(settings);
3522
+ const request = {
3523
+ db: db(),
3524
+ view: settings.view,
3525
+ range: settings.range,
3526
+ filters,
3527
+ granularity: settings.granularity,
3528
+ turnsScope: settings.turnsScope,
3529
+ sort: settings.sort === "" ? defaultSort(settings.view) : settings.sort,
3530
+ sortDesc: settings.sortDesc,
3531
+ sessionID: input.sessionID,
3532
+ sessionStart: sessionStart(db(), input.sessionID),
3533
+ now: Date.now(),
3534
+ format: { ...options.format, estimates: options.pricing },
3535
+ estimates: options.pricing,
3536
+ ...input.detail !== undefined ? { detail: input.detail } : {},
3537
+ ...database !== undefined ? { database } : {},
3538
+ busy: input.busy === true,
3539
+ width
3540
+ };
3541
+ return { lines: buildPanel(request), ...database !== undefined ? { database } : {} };
3542
+ }
3543
+ function turnHistory(input) {
3544
+ const handle = db();
3545
+ const width = clamp2(input.width, 20, 120);
3546
+ const limit = clampTurnsLimit(input.limit);
3547
+ const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
3548
+ const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
3549
+ ...options.format,
3550
+ estimates: options.pricing,
3551
+ budget: width
3552
+ });
3553
+ return { summary, history };
3554
+ }
3555
+ function listCost(input) {
3556
+ if (!options.pricing)
3557
+ return { cost: 0 };
3558
+ return { cost: sessionListCost(db(), input.sessionID) };
3559
+ }
3560
+ function filters() {
3561
+ return filterOptions(db());
3562
+ }
3563
+ function requireMaintenance() {
3564
+ if (!options.maintenance)
3565
+ throw new ServiceError("disabled", "database maintenance is disabled");
3566
+ }
3567
+ function requireConfirm(confirm) {
3568
+ if (confirm !== true)
3569
+ throw new ServiceError("invalid", "confirmation is required");
3570
+ }
3571
+ function prune(input) {
3572
+ requireMaintenance();
3573
+ requireConfirm(input.confirm);
3574
+ const days = clamp2(input.days, 1, MAX_DAYS);
3575
+ return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY2));
3576
+ }
3577
+ function wipe(input) {
3578
+ requireMaintenance();
3579
+ requireConfirm(input.confirm);
3580
+ return writeDb(options.path, (handle) => wipeAll(handle));
3581
+ }
3582
+ function compact(input) {
3583
+ requireMaintenance();
3584
+ requireConfirm(input.confirm);
3585
+ return writeDb(options.path, (handle) => vacuum(handle, options.path));
3586
+ }
3587
+ function backfill(input, table) {
3588
+ if (!options.pricing)
3589
+ throw new ServiceError("disabled", "list-price estimates are turned off");
3590
+ requireMaintenance();
3591
+ requireConfirm(input.confirm);
3592
+ const prices = table ?? options.priceTable?.();
3593
+ if (prices === undefined)
3594
+ throw new ServiceError("unavailable", "the model catalog is unavailable");
3595
+ return writeDb(options.path, (handle) => backfillListCost(handle, (ref, tokens) => costOf(prices, ref, tokens)));
3596
+ }
3597
+ return {
3598
+ panel,
3599
+ turnHistory,
3600
+ listCost,
3601
+ filters,
3602
+ dbInfo: infoOf,
3603
+ prune,
3604
+ wipe,
3605
+ compact,
3606
+ backfill
3607
+ };
3608
+ }
3609
+
3610
+ // src/stats-worker.ts
3611
+ var scope = globalThis;
3612
+ var dbPath;
3613
+ var readDb;
3614
+ var service;
3615
+ function read() {
3616
+ if (readDb === undefined) {
3617
+ if (dbPath === undefined)
3618
+ throw new ServiceError("unavailable", "the usage database is not configured");
3619
+ readDb = openStatsDbReadOnly(dbPath);
3620
+ }
3621
+ return readDb;
3622
+ }
3623
+ function closeRead() {
3624
+ readDb?.close();
3625
+ readDb = undefined;
3626
+ }
3627
+ function reopen() {
3628
+ try {
3629
+ read();
3630
+ } catch {}
3631
+ }
3632
+ function serializedPrices(entries) {
3633
+ if (entries === undefined)
3634
+ return;
3635
+ return new Map(entries);
3636
+ }
3637
+ function run(request) {
3638
+ if (service === undefined)
3639
+ throw new ServiceError("unavailable", "the usage worker is not initialized");
3640
+ const maintenance = request.method === "prune" || request.method === "wipe" || request.method === "vacuum" || request.method === "backfill";
3641
+ if (maintenance)
3642
+ closeRead();
3643
+ try {
3644
+ switch (request.method) {
3645
+ case "panel":
3646
+ return service.panel(request.input);
3647
+ case "turns":
3648
+ return service.turnHistory(request.input);
3649
+ case "listCost":
3650
+ return service.listCost(request.input);
3651
+ case "filters":
3652
+ return service.filters();
3653
+ case "dbInfo":
3654
+ return service.dbInfo();
3655
+ case "prune":
3656
+ return service.prune(request.input);
3657
+ case "wipe":
3658
+ return service.wipe(request.input);
3659
+ case "vacuum":
3660
+ return service.compact(request.input);
3661
+ case "backfill":
3662
+ return service.backfill(request.input, serializedPrices(request.prices));
3663
+ }
3664
+ } finally {
3665
+ if (maintenance)
3666
+ reopen();
3667
+ }
3668
+ }
3669
+ function failure(error) {
3670
+ if (error instanceof ServiceError)
3671
+ return { code: error.code, message: error.message };
3672
+ return { code: "unavailable", message: "the usage database is unavailable" };
3673
+ }
3674
+ scope.onmessage = (event) => {
3675
+ const message = event.data;
3676
+ if ("type" in message && message.type === "init") {
3677
+ dbPath = message.dbPath;
3678
+ service = createService(read, { ...message.options, path: message.dbPath });
3679
+ closeRead();
3680
+ try {
3681
+ read();
3682
+ scope.postMessage({ type: "ready" });
3683
+ } catch (error) {
3684
+ scope.postMessage({ type: "error", error: failure(error) });
3685
+ }
3686
+ return;
3687
+ }
3688
+ const request = message;
3689
+ try {
3690
+ const result = run(request);
3691
+ scope.postMessage({ id: request.id, ok: true, result });
3692
+ } catch (error) {
3693
+ scope.postMessage({ id: request.id, ok: false, error: failure(error) });
3694
+ }
3695
+ };
3696
+
3697
+ //# debugId=008189B5EA042DE564756E2164756E21