opencode-usage-insights 0.3.0 → 0.4.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.
Files changed (58) hide show
  1. package/README.md +66 -542
  2. package/dist/core.d.ts +15 -1
  3. package/dist/gui-experimental.cjs +3 -3
  4. package/dist/index.d.ts +0 -47
  5. package/dist/index.js +2066 -1363
  6. package/dist/index.js.map +25 -18
  7. package/dist/limits.d.ts +9 -0
  8. package/dist/line.d.ts +1 -0
  9. package/dist/panel-data.d.ts +56 -7
  10. package/dist/recorder.d.ts +1 -0
  11. package/dist/rpc.d.ts +4 -4
  12. package/dist/rpc.js +7 -6
  13. package/dist/rpc.js.map +4 -4
  14. package/dist/settings-client.d.ts +29 -0
  15. package/dist/settings-rpc.d.ts +746 -0
  16. package/dist/settings.d.ts +114 -0
  17. package/dist/sidebar.d.ts +3 -3
  18. package/dist/stats/aggregates.d.ts +19 -4
  19. package/dist/stats/constants.d.ts +7 -0
  20. package/dist/stats/db.d.ts +8 -128
  21. package/dist/stats/legacy.d.ts +25 -0
  22. package/dist/stats/maintenance.d.ts +1 -1
  23. package/dist/stats/migrate.d.ts +7 -0
  24. package/dist/stats/ndjson.d.ts +16 -0
  25. package/dist/stats/open.d.ts +15 -0
  26. package/dist/stats/paths.d.ts +5 -4
  27. package/dist/stats/queries.d.ts +25 -31
  28. package/dist/stats/records.d.ts +94 -0
  29. package/dist/stats/schema.d.ts +26 -0
  30. package/dist/stats-client.d.ts +9 -0
  31. package/dist/stats-worker.js +1012 -604
  32. package/dist/stats-worker.js.map +19 -14
  33. package/dist/text.d.ts +2 -0
  34. package/dist/tui-settings.d.ts +18 -0
  35. package/dist/tui.d.ts +1 -57
  36. package/dist/tui.js +1364 -384
  37. package/dist/tui.js.map +17 -13
  38. package/docs/cli.md +24 -0
  39. package/docs/configuration.md +108 -0
  40. package/docs/costs.md +44 -0
  41. package/docs/demo.md +94 -68
  42. package/docs/desktop.md +91 -0
  43. package/docs/images/desktop-overview-annotated.png +0 -0
  44. package/docs/images/desktop-overview.png +0 -0
  45. package/docs/images/desktop-settings.png +0 -0
  46. package/docs/images/desktop-turns-go-annotated.png +0 -0
  47. package/docs/images/desktop-turns.png +0 -0
  48. package/docs/images/line.png +0 -0
  49. package/docs/images/panel-cache.png +0 -0
  50. package/docs/images/panel-help.png +0 -0
  51. package/docs/images/panel-latency.png +0 -0
  52. package/docs/images/panel-overview.png +0 -0
  53. package/docs/images/panel-providers.png +0 -0
  54. package/docs/images/sidebar.png +0 -0
  55. package/docs/internals.md +87 -36
  56. package/docs/privacy.md +60 -0
  57. package/docs/tui.md +175 -0
  58. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { Rpc } from "@opencode/plugin/rpc";
7
7
 
8
8
  // src/limits.ts
9
9
  var MAX_PANEL_WIDTH = 200;
10
+ var MAX_HISTORY_WIDTH = 120;
10
11
  var MAX_TURNS = 50;
11
12
  function clampPanelWidth(value) {
12
13
  if (!Number.isFinite(value))
@@ -101,10 +102,10 @@ var PruneResultSchema = {
101
102
  properties: {
102
103
  steps: { type: "number" },
103
104
  prompts: { type: "number" },
104
- events: { type: "number" },
105
+ compactions: { type: "number" },
105
106
  usage: { type: "number" }
106
107
  },
107
- required: ["steps", "prompts", "events", "usage"],
108
+ required: ["steps", "prompts", "compactions", "usage"],
108
109
  additionalProperties: false
109
110
  };
110
111
  var WipeResultSchema = {
@@ -112,11 +113,11 @@ var WipeResultSchema = {
112
113
  properties: {
113
114
  steps: { type: "number" },
114
115
  prompts: { type: "number" },
115
- events: { type: "number" },
116
+ compactions: { type: "number" },
116
117
  usage: { type: "number" },
117
118
  sessions: { type: "number" }
118
119
  },
119
- required: ["steps", "prompts", "events", "usage", "sessions"],
120
+ required: ["steps", "prompts", "compactions", "usage", "sessions"],
120
121
  additionalProperties: false
121
122
  };
122
123
  var BackfillResultSchema = {
@@ -183,7 +184,7 @@ var UsageInsights = Rpc.define({
183
184
  properties: {
184
185
  sessionID: { type: "string", maxLength: 200 },
185
186
  limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
186
- width: { type: "number", minimum: 20, maximum: 120 }
187
+ width: { type: "number", minimum: 20, maximum: MAX_HISTORY_WIDTH }
187
188
  },
188
189
  required: ["sessionID", "limit", "width"],
189
190
  additionalProperties: false
@@ -291,137 +292,366 @@ var UsageInsights = Rpc.define({
291
292
  }
292
293
  });
293
294
 
294
- // src/pricing.ts
295
- function money(value) {
296
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
297
- }
298
- function tokens(value) {
299
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
300
- }
301
- function priceTable(models) {
302
- const table = new Map;
303
- if (!Array.isArray(models))
304
- return table;
305
- for (const model of models) {
306
- if (model === null || model === undefined)
307
- continue;
308
- const providerID = model.providerID;
309
- const modelID = model.modelID ?? model.id;
310
- if (typeof providerID !== "string" || providerID === "")
295
+ // src/settings-rpc.ts
296
+ import { Rpc as Rpc2 } from "@opencode/plugin/rpc";
297
+
298
+ // src/core.ts
299
+ var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
300
+ function transcriptTail(messages, count) {
301
+ const segments = [];
302
+ let current = [];
303
+ for (let index = messages.length - 1;index >= 0; index -= 1) {
304
+ const message = messages[index];
305
+ if (message.type === "assistant") {
306
+ current.unshift(message);
311
307
  continue;
312
- if (typeof modelID !== "string" || modelID === "")
308
+ }
309
+ if (!PROMPT_BOUNDARIES.has(message.type))
313
310
  continue;
314
- if (!Array.isArray(model.cost) || model.cost.length === 0)
311
+ if (current.length === 0)
315
312
  continue;
316
- const tiers = [];
317
- for (const cost of model.cost) {
318
- if (cost === null || cost === undefined)
319
- continue;
320
- let tier;
321
- if (cost.tier !== undefined) {
322
- const size = cost.tier.size;
323
- if (typeof size !== "number" || !Number.isFinite(size))
324
- continue;
325
- tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
326
- }
327
- tiers.push({
328
- ...tier !== undefined ? { tier } : {},
329
- input: money(cost.input),
330
- output: money(cost.output),
331
- cacheRead: money(cost.cache?.read),
332
- cacheWrite: money(cost.cache?.write)
333
- });
334
- }
335
- if (tiers.length > 0)
336
- table.set(`${providerID}/${modelID}`, { tiers });
313
+ segments.unshift({ assistants: current, prompt: message });
314
+ if (segments.length >= count)
315
+ return segments;
316
+ current = [];
337
317
  }
338
- return table;
318
+ if (current.length > 0 && segments.length < count)
319
+ segments.unshift({ assistants: current, prompt: undefined });
320
+ return segments;
339
321
  }
340
- function priceOf(table, ref) {
341
- if (ref.providerID === undefined || ref.providerID === "")
322
+ function countOf(value) {
323
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
324
+ }
325
+ function amountOf(value) {
326
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
327
+ }
328
+ function stampOf(value) {
329
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
330
+ }
331
+ function tokenCounts(message) {
332
+ const tokens = message.tokens;
333
+ return {
334
+ input: countOf(tokens?.input),
335
+ output: countOf(tokens?.output),
336
+ reasoning: countOf(tokens?.reasoning),
337
+ read: countOf(tokens?.cache?.read),
338
+ write: countOf(tokens?.cache?.write)
339
+ };
340
+ }
341
+ function totalize(steps) {
342
+ const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
343
+ for (const step of steps) {
344
+ const counts = tokenCounts(step);
345
+ totals.input += counts.input;
346
+ totals.cached += counts.read;
347
+ totals.output += counts.output;
348
+ totals.reasoning += counts.reasoning;
349
+ totals.cacheWrite += counts.write;
350
+ totals.cost += amountOf(step.cost);
351
+ totals.listCost += amountOf(step.listCost);
352
+ }
353
+ return totals;
354
+ }
355
+ function identityKey(model) {
356
+ if (!model)
342
357
  return;
343
- if (ref.modelID === undefined || ref.modelID === "")
358
+ return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
359
+ }
360
+ function cacheRead(message) {
361
+ return countOf(message?.tokens?.cache?.read);
362
+ }
363
+ function stepCreated(message) {
364
+ return stampOf(message?.time?.created);
365
+ }
366
+ function stepEnd(message) {
367
+ const time = message?.time;
368
+ if (!time)
344
369
  return;
345
- return table.get(`${ref.providerID}/${ref.modelID}`);
370
+ return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
346
371
  }
347
- function costOf(table, ref, usage) {
348
- const price = priceOf(table, ref);
349
- if (price === undefined)
372
+ function cacheDrop(reference, current, scope = "provider") {
373
+ if (!reference)
350
374
  return;
351
- const input = tokens(usage.input);
352
- const output = tokens(usage.output);
353
- const reasoning = tokens(usage.reasoning);
354
- const cacheRead = tokens(usage.cacheRead);
355
- const cacheWrite = tokens(usage.cacheWrite);
356
- const prompt = input + cacheRead + cacheWrite;
357
- 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);
358
- if (selected === undefined)
375
+ const before = reference.model;
376
+ const after = current.model;
377
+ if (!before || !after)
359
378
  return;
360
- if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
361
- return 0;
362
- const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
363
- if (!Number.isFinite(billed) || billed <= 0)
379
+ if (scope === "provider" && before.providerID !== after.providerID)
380
+ return;
381
+ if (before.id !== after.id || (before.variant ?? "") !== (after.variant ?? "")) {
364
382
  return;
365
- return billed / 1e6;
366
- }
367
-
368
- // src/stats/db.ts
369
- import { Database } from "bun:sqlite";
370
- import { chmodSync, mkdirSync } from "fs";
371
- import { dirname } from "path";
372
-
373
- // src/stats/paths.ts
374
- import { homedir } from "os";
375
- import { join } from "path";
376
- import { statSync } from "fs";
377
- function defaultDbPath(env = process.env, platform = process.platform) {
378
- const name = join("opencode", "opencode-usage-insights", "usage.db");
379
- if (platform === "win32") {
380
- return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
381
- }
382
- if (platform === "darwin") {
383
- return join(homedir(), "Library", "Application Support", name);
384
383
  }
385
- return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
384
+ const drop = cacheRead(reference) - cacheRead(current);
385
+ if (isNoiseDrop(after.providerID, drop))
386
+ return;
387
+ return drop > 0 ? drop : undefined;
386
388
  }
387
- function expandHome(path, home = homedir()) {
388
- if (path === "~")
389
- return home;
390
- if (path.startsWith("~/") || path.startsWith("~\\"))
391
- return join(home, path.slice(2));
392
- return path;
389
+ function stepGap(reference, current) {
390
+ const ended = stepEnd(reference);
391
+ const started = stepCreated(current);
392
+ if (ended === undefined || started === undefined)
393
+ return;
394
+ return Math.max(0, started - ended);
393
395
  }
394
- function resolveDbPath(configured, env = process.env, platform = process.platform) {
395
- const home = env.HOME ?? env.USERPROFILE ?? homedir();
396
- if (configured)
397
- return expandHome(configured, home);
398
- if (env.OPENCODE_USAGE_INSIGHTS_DB)
399
- return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
400
- return defaultDbPath(env, platform);
396
+ function tokensPerSecond(produced, from, to) {
397
+ if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
398
+ return;
399
+ if (!Number.isFinite(produced) || produced <= 0)
400
+ return;
401
+ return produced / (to - from) * 1000;
401
402
  }
402
- function ensureRegularFile(path) {
403
- let stats;
404
- try {
405
- stats = statSync(path);
406
- } catch {
403
+ var DROP_EXEMPT_PROVIDERS = new Set(["openai"]);
404
+ function isSettledStep(message) {
405
+ if (message.time?.completed !== undefined)
406
+ return true;
407
+ return message.finish !== undefined && message.finish !== null;
408
+ }
409
+ function computeTurn(messages, session) {
410
+ const segments = transcriptTail(messages, 2);
411
+ const last = segments[segments.length - 1];
412
+ if (!last)
413
+ return;
414
+ const previous = segments[segments.length - 2];
415
+ const lastStep = last.assistants[last.assistants.length - 1];
416
+ if (!lastStep)
417
+ return;
418
+ if (!isSettledStep(lastStep))
407
419
  return;
420
+ const previousStep = previous?.assistants[previous.assistants.length - 1];
421
+ const settled = last.assistants.filter(isSettledStep);
422
+ const drops = [];
423
+ let reference = previousStep !== undefined && isSettledStep(previousStep) ? previousStep : undefined;
424
+ for (const step of settled) {
425
+ const drop = cacheDrop(reference, step);
426
+ if (drop !== undefined) {
427
+ drops.push({
428
+ messageID: step.id,
429
+ tokens: drop,
430
+ prevCached: cacheRead(reference),
431
+ gapMs: stepGap(reference, step)
432
+ });
433
+ }
434
+ reference = step;
408
435
  }
409
- if (!stats.isFile())
410
- throw new Error(`not a regular file: ${path}`);
436
+ const provider = lastStep.model?.providerID;
437
+ const previousProvider = previousStep?.model?.providerID;
438
+ const key = identityKey(lastStep.model);
439
+ const previousKey = identityKey(previousStep?.model);
440
+ return {
441
+ endAt: stepEnd(lastStep),
442
+ startAt: stepCreated(settled[0] ?? lastStep),
443
+ promptAt: stampOf(last.prompt?.time?.created),
444
+ promptGapMs: promptGap(last.prompt, previous?.prompt),
445
+ providerID: provider,
446
+ modelID: lastStep.model?.id,
447
+ variant: lastStep.model?.variant,
448
+ providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,
449
+ modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,
450
+ totals: totalize(settled),
451
+ latest: totalize([lastStep]),
452
+ session,
453
+ drops,
454
+ cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),
455
+ cacheExpired: drops.length > 0,
456
+ steps: settled.length
457
+ };
411
458
  }
412
-
413
- // src/text.ts
414
- var TEXT_LIMIT = 512;
415
- function sanitizeText(value, limit = TEXT_LIMIT) {
416
- if (limit <= 0)
417
- return "";
418
- let cleaned = "";
419
- for (const character of value) {
420
- const code = character.codePointAt(0) ?? 0;
421
- if (code <= 31 || code === 127 || code >= 128 && code <= 159)
422
- continue;
423
- cleaned += character;
424
- if (cleaned.length >= limit)
459
+ function promptGap(current, previous) {
460
+ const now = stampOf(current?.time?.created);
461
+ const before = stampOf(previous?.time?.created);
462
+ if (now === undefined || before === undefined)
463
+ return;
464
+ return Math.max(0, now - before);
465
+ }
466
+ function isNoiseDrop(providerID, drop) {
467
+ if (providerID === undefined)
468
+ return false;
469
+ return DROP_EXEMPT_PROVIDERS.has(providerID) && drop >= 1024 && drop <= 2048;
470
+ }
471
+ var DEFAULT_LABELS = {
472
+ delta: "\u0394",
473
+ turn: "",
474
+ session: "sess",
475
+ step: "step",
476
+ steps: "steps",
477
+ input: "in",
478
+ cached: "cached",
479
+ output: "out",
480
+ reasoning: "reason",
481
+ cost: "cost",
482
+ estimate: "\u2248",
483
+ cacheExpired: "cache expired",
484
+ providerChanged: "changed",
485
+ modelChanged: "model changed"
486
+ };
487
+ var DEFAULT_FIELDS = {
488
+ clock: true,
489
+ delta: true,
490
+ model: true,
491
+ variant: true,
492
+ turn: true,
493
+ session: true,
494
+ reasoning: false,
495
+ cost: true,
496
+ cacheExpiry: true
497
+ };
498
+ function formatClock(ms) {
499
+ if (!Number.isFinite(ms))
500
+ return "--:--";
501
+ const date = new Date(ms);
502
+ const pad = (value) => String(value).padStart(2, "0");
503
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
504
+ }
505
+ function formatDuration(ms) {
506
+ if (!Number.isFinite(ms))
507
+ return "\u2013";
508
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
509
+ const seconds = totalSeconds % 60;
510
+ const minutes = Math.floor(totalSeconds / 60) % 60;
511
+ const hours = Math.floor(totalSeconds / 3600) % 24;
512
+ const days = Math.floor(totalSeconds / 86400);
513
+ if (days > 0)
514
+ return `${days}d${hours}h`;
515
+ if (hours > 0)
516
+ return `${hours}h${String(minutes).padStart(2, "0")}m`;
517
+ if (minutes > 0)
518
+ return `${minutes}m${String(seconds).padStart(2, "0")}s`;
519
+ return `${seconds}s`;
520
+ }
521
+ function formatTokens(value) {
522
+ const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
523
+ if (n < 1000)
524
+ return String(n);
525
+ if (n < 999500) {
526
+ const k = n / 1000;
527
+ return `${trimZeros(k.toFixed(k < 10 ? 2 : 1))}k`;
528
+ }
529
+ if (n < 999500000) {
530
+ const m = n / 1e6;
531
+ return `${trimZeros(m.toFixed(m < 10 ? 2 : 1))}M`;
532
+ }
533
+ return `${Math.round(n / 1e6)}M`;
534
+ }
535
+ function trimZeros(value) {
536
+ return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
537
+ }
538
+ function formatCost(value) {
539
+ if (!Number.isFinite(value) || value <= 0)
540
+ return "$0";
541
+ if (value < 0.00005)
542
+ return "<$0.0001";
543
+ if (value < 1)
544
+ return `$${value.toFixed(4)}`;
545
+ return `$${value.toFixed(2)}`;
546
+ }
547
+ function formatMoney(charged, estimated, marker = "\u2248") {
548
+ const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
549
+ const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
550
+ if (paid !== undefined && estimate !== undefined)
551
+ return `${paid} + ${estimate}`;
552
+ return paid ?? estimate;
553
+ }
554
+ function formatSpend(charged, estimated, marker = "\u2248") {
555
+ const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
556
+ const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
557
+ if (estimate > 0)
558
+ return `${marker.trim()}${formatCost(paid + estimate)}`;
559
+ return formatCost(paid);
560
+ }
561
+ function displayTotals(totals) {
562
+ const prompt = totals.input + totals.cached + totals.cacheWrite;
563
+ return {
564
+ input: prompt - totals.cached,
565
+ cached: totals.cached,
566
+ cacheWrite: totals.cacheWrite,
567
+ output: totals.output + totals.reasoning,
568
+ reasoning: totals.reasoning,
569
+ cost: totals.cost,
570
+ listCost: totals.listCost,
571
+ steps: totals.steps,
572
+ prompt
573
+ };
574
+ }
575
+ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
576
+ const display = displayTotals(totals);
577
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
578
+ const parts = [
579
+ input,
580
+ `${labels.cached} ${formatTokens(display.cached)}`,
581
+ `${labels.output} ${formatTokens(display.output)}`
582
+ ];
583
+ if (fields.reasoning)
584
+ parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
585
+ const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
586
+ if (money !== undefined)
587
+ parts.push(`${labels.cost} ${money}`);
588
+ const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
589
+ const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
590
+ const numbers = parts.join(", ");
591
+ if (head === "")
592
+ return numbers;
593
+ return stepCount > 1 ? `${head} \xB7 ${numbers}` : `${head} ${numbers}`;
594
+ }
595
+ function formatLineSegments(stats, options) {
596
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
597
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
598
+ const turnTotals = options?.turnTotals ?? "latest";
599
+ const estimates = options?.estimates !== false;
600
+ const segments = [];
601
+ if (fields.clock && stats.endAt !== undefined) {
602
+ segments.push({ text: formatClock(stats.endAt), tone: "muted" });
603
+ }
604
+ if (fields.delta && stats.promptGapMs !== undefined) {
605
+ segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: "muted" });
606
+ }
607
+ if (stats.providerID !== undefined) {
608
+ let text = stats.providerID;
609
+ if (fields.model && stats.modelID !== undefined)
610
+ text += `/${stats.modelID}`;
611
+ if (fields.variant && stats.variant)
612
+ text += ` ${stats.variant}`;
613
+ segments.push({ text, tone: stats.providerChanged ? "warning" : "base" });
614
+ if (stats.providerChanged)
615
+ segments.push({ text: labels.providerChanged, tone: "warning" });
616
+ else if (stats.modelChanged)
617
+ segments.push({ text: labels.modelChanged, tone: "muted" });
618
+ }
619
+ if (fields.turn && stats.totals.steps > 0) {
620
+ const totals = turnTotals === "sum" ? stats.totals : stats.latest;
621
+ segments.push({
622
+ text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
623
+ tone: "base"
624
+ });
625
+ }
626
+ if (fields.session && stats.session) {
627
+ segments.push({
628
+ text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
629
+ tone: "muted"
630
+ });
631
+ }
632
+ if (fields.cacheExpiry && stats.cacheExpired) {
633
+ const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
634
+ segments.push({ text: `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${count})`, tone: "warning" });
635
+ }
636
+ return segments;
637
+ }
638
+ function formatLine(stats, options) {
639
+ return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
640
+ }
641
+
642
+ // src/text.ts
643
+ var TEXT_LIMIT = 512;
644
+ var LABEL_LIMIT = 4 * TEXT_LIMIT;
645
+ function sanitizeText(value, limit = TEXT_LIMIT) {
646
+ if (limit <= 0)
647
+ return "";
648
+ let cleaned = "";
649
+ for (const character of value) {
650
+ const code = character.codePointAt(0) ?? 0;
651
+ if (code <= 31 || code === 127 || code >= 128 && code <= 159)
652
+ continue;
653
+ cleaned += character;
654
+ if (cleaned.length >= limit)
425
655
  break;
426
656
  }
427
657
  return cleaned;
@@ -434,47 +664,375 @@ function isToken(value, limit = 64) {
434
664
  return value.length > 0 && value.length <= limit && TOKEN.test(value);
435
665
  }
436
666
 
437
- // src/stats/db.ts
438
- var SCHEMA_VERSION = 11;
439
- var LABEL_LIMIT = 4 * TEXT_LIMIT;
440
- var SCHEMA = `
441
- CREATE TABLE IF NOT EXISTS meta (
442
- key TEXT PRIMARY KEY,
443
- value TEXT NOT NULL
444
- );
445
-
446
- CREATE TABLE IF NOT EXISTS sessions (
447
- session_id TEXT PRIMARY KEY,
448
- parent_id TEXT,
449
- directory TEXT,
450
- title TEXT,
451
- started_at INTEGER,
452
- updated_at INTEGER
453
- );
454
-
455
- CREATE TABLE IF NOT EXISTS prompts (
456
- session_id TEXT NOT NULL,
457
- message_id TEXT NOT NULL,
458
- created_at INTEGER,
459
- PRIMARY KEY (session_id, message_id)
460
- );
461
- CREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);
667
+ // src/settings.ts
668
+ var SETTINGS_STORAGE_KEY = "settings";
669
+ var MAX_LABEL_LENGTH = 80;
670
+ var MAX_QUOTA_NAME_LENGTH = 120;
671
+ var DEFAULT_SIDEBAR_TURNS = 8;
672
+ var TURN_TOTALS = ["latest", "sum"];
673
+ var FIELD_KEYS = Object.keys(DEFAULT_FIELDS);
674
+ var LABEL_KEYS = Object.keys(DEFAULT_LABELS);
675
+ var DEFAULT_SERVER_POLICY = {
676
+ maintenance: true,
677
+ exposePaths: false
678
+ };
679
+ var DEFAULT_USAGE_SETTINGS = {
680
+ pricing: true,
681
+ turnTotals: "latest",
682
+ fields: { ...DEFAULT_FIELDS },
683
+ labels: { ...DEFAULT_LABELS },
684
+ panel: true,
685
+ sidebar: true,
686
+ sidebarTurns: DEFAULT_SIDEBAR_TURNS,
687
+ quota: true,
688
+ quotaName: ""
689
+ };
690
+ function defaultUsageSettings() {
691
+ return {
692
+ ...DEFAULT_USAGE_SETTINGS,
693
+ fields: { ...DEFAULT_USAGE_SETTINGS.fields },
694
+ labels: { ...DEFAULT_USAGE_SETTINGS.labels }
695
+ };
696
+ }
697
+ function defaultSettingsEnvelope(policy = DEFAULT_SERVER_POLICY) {
698
+ return { settings: defaultUsageSettings(), policy: { ...policy } };
699
+ }
700
+ function isRecord(value) {
701
+ return typeof value === "object" && value !== null && !Array.isArray(value);
702
+ }
703
+ function sanitizeSidebarTurns(value) {
704
+ if (typeof value === "number" && Number.isFinite(value))
705
+ return clampTurnsLimit(value);
706
+ if (typeof value === "string" && value.trim() !== "") {
707
+ const parsed = Number(value);
708
+ if (Number.isFinite(parsed))
709
+ return clampTurnsLimit(parsed);
710
+ }
711
+ return DEFAULT_SIDEBAR_TURNS;
712
+ }
713
+ function sanitizeLabels(value) {
714
+ const labels = { ...DEFAULT_LABELS };
715
+ if (!isRecord(value))
716
+ return labels;
717
+ for (const key of LABEL_KEYS) {
718
+ const entry = value[key];
719
+ if (typeof entry === "string")
720
+ labels[key] = sanitizeText(entry, MAX_LABEL_LENGTH);
721
+ }
722
+ return labels;
723
+ }
724
+ function sanitizeFields(value) {
725
+ const fields = { ...DEFAULT_FIELDS };
726
+ if (!isRecord(value))
727
+ return fields;
728
+ for (const key of FIELD_KEYS) {
729
+ const entry = value[key];
730
+ if (typeof entry === "boolean")
731
+ fields[key] = entry;
732
+ }
733
+ return fields;
734
+ }
735
+ function sanitizeUsageSettings(value) {
736
+ if (!isRecord(value))
737
+ return defaultUsageSettings();
738
+ return {
739
+ pricing: typeof value.pricing === "boolean" ? value.pricing : DEFAULT_USAGE_SETTINGS.pricing,
740
+ turnTotals: TURN_TOTALS.includes(value.turnTotals) ? value.turnTotals : DEFAULT_USAGE_SETTINGS.turnTotals,
741
+ fields: sanitizeFields(value.fields),
742
+ labels: sanitizeLabels(value.labels),
743
+ panel: typeof value.panel === "boolean" ? value.panel : DEFAULT_USAGE_SETTINGS.panel,
744
+ sidebar: typeof value.sidebar === "boolean" ? value.sidebar : DEFAULT_USAGE_SETTINGS.sidebar,
745
+ sidebarTurns: sanitizeSidebarTurns(value.sidebarTurns),
746
+ quota: typeof value.quota === "boolean" ? value.quota : DEFAULT_USAGE_SETTINGS.quota,
747
+ quotaName: typeof value.quotaName === "string" ? sanitizeText(value.quotaName.trim(), MAX_QUOTA_NAME_LENGTH) : DEFAULT_USAGE_SETTINGS.quotaName
748
+ };
749
+ }
750
+ function sanitizeServerPolicy(value) {
751
+ if (!isRecord(value))
752
+ return { ...DEFAULT_SERVER_POLICY };
753
+ return {
754
+ maintenance: typeof value.maintenance === "boolean" ? value.maintenance : DEFAULT_SERVER_POLICY.maintenance,
755
+ exposePaths: typeof value.exposePaths === "boolean" ? value.exposePaths : DEFAULT_SERVER_POLICY.exposePaths
756
+ };
757
+ }
758
+ function sanitizeSettingsEnvelope(value) {
759
+ return {
760
+ settings: sanitizeUsageSettings(isRecord(value) ? value.settings : undefined),
761
+ policy: sanitizeServerPolicy(isRecord(value) ? value.policy : undefined)
762
+ };
763
+ }
764
+ function mergeUsageSettings(current, patch) {
765
+ const next = {
766
+ ...current,
767
+ ...typeof patch.pricing === "boolean" ? { pricing: patch.pricing } : {},
768
+ ...TURN_TOTALS.includes(patch.turnTotals) ? { turnTotals: patch.turnTotals } : {},
769
+ ...isRecord(patch.fields) ? { fields: { ...current.fields, ...patch.fields } } : {},
770
+ ...isRecord(patch.labels) ? { labels: { ...current.labels, ...patch.labels } } : {},
771
+ ...typeof patch.panel === "boolean" ? { panel: patch.panel } : {},
772
+ ...typeof patch.sidebar === "boolean" ? { sidebar: patch.sidebar } : {},
773
+ ...patch.sidebarTurns !== undefined ? { sidebarTurns: patch.sidebarTurns } : {},
774
+ ...typeof patch.quota === "boolean" ? { quota: patch.quota } : {},
775
+ ...typeof patch.quotaName === "string" ? { quotaName: patch.quotaName } : {}
776
+ };
777
+ return sanitizeUsageSettings(next);
778
+ }
779
+ function resolveUsageSettings(settings) {
780
+ return {
781
+ format: {
782
+ labels: settings.labels,
783
+ fields: settings.fields,
784
+ turnTotals: settings.turnTotals,
785
+ estimates: settings.pricing
786
+ },
787
+ sidebarTurns: clampTurnsLimit(settings.sidebarTurns),
788
+ quotaName: settings.quotaName.trim() || undefined
789
+ };
790
+ }
791
+ function isValidSidebarTurns(raw) {
792
+ const value = Number(raw);
793
+ return raw.trim() !== "" && Number.isInteger(value) && value >= 1 && value <= 50;
794
+ }
795
+ function parseSidebarTurns(raw) {
796
+ if (!isValidSidebarTurns(raw))
797
+ return;
798
+ return clampTurnsLimit(Number(raw));
799
+ }
800
+ var TRUE_VALUES = new Set(["1", "true", "on", "yes", "y"]);
801
+ var FALSE_VALUES = new Set(["0", "false", "off", "no", "n"]);
802
+ function envFlag(value, fallback) {
803
+ if (value === undefined || value.trim() === "")
804
+ return fallback;
805
+ const normalized = value.trim().toLowerCase();
806
+ if (TRUE_VALUES.has(normalized))
807
+ return true;
808
+ if (FALSE_VALUES.has(normalized))
809
+ return false;
810
+ return fallback;
811
+ }
812
+ function serverPolicy(env = process.env) {
813
+ return {
814
+ maintenance: envFlag(env.OPENCODE_USAGE_INSIGHTS_MAINTENANCE, true),
815
+ exposePaths: envFlag(env.OPENCODE_USAGE_INSIGHTS_EXPOSE_PATHS, false)
816
+ };
817
+ }
462
818
 
463
- CREATE TABLE IF NOT EXISTS steps (
464
- message_id TEXT PRIMARY KEY,
465
- session_id TEXT NOT NULL,
466
- parent_id TEXT,
467
- provider_id TEXT,
468
- model_id TEXT,
469
- variant TEXT,
470
- input_tokens INTEGER NOT NULL DEFAULT 0,
471
- output_tokens INTEGER NOT NULL DEFAULT 0,
472
- reasoning_tokens INTEGER NOT NULL DEFAULT 0,
473
- cache_read INTEGER NOT NULL DEFAULT 0,
819
+ // src/settings-rpc.ts
820
+ var LineFields = {
821
+ type: "object",
822
+ properties: {
823
+ clock: { type: "boolean" },
824
+ delta: { type: "boolean" },
825
+ model: { type: "boolean" },
826
+ variant: { type: "boolean" },
827
+ turn: { type: "boolean" },
828
+ session: { type: "boolean" },
829
+ reasoning: { type: "boolean" },
830
+ cost: { type: "boolean" },
831
+ cacheExpiry: { type: "boolean" }
832
+ },
833
+ additionalProperties: false
834
+ };
835
+ var LineLabels = {
836
+ type: "object",
837
+ properties: {
838
+ delta: { type: "string", maxLength: MAX_LABEL_LENGTH },
839
+ turn: { type: "string", maxLength: MAX_LABEL_LENGTH },
840
+ session: { type: "string", maxLength: MAX_LABEL_LENGTH },
841
+ step: { type: "string", maxLength: MAX_LABEL_LENGTH },
842
+ steps: { type: "string", maxLength: MAX_LABEL_LENGTH },
843
+ input: { type: "string", maxLength: MAX_LABEL_LENGTH },
844
+ cached: { type: "string", maxLength: MAX_LABEL_LENGTH },
845
+ output: { type: "string", maxLength: MAX_LABEL_LENGTH },
846
+ reasoning: { type: "string", maxLength: MAX_LABEL_LENGTH },
847
+ cost: { type: "string", maxLength: MAX_LABEL_LENGTH },
848
+ estimate: { type: "string", maxLength: MAX_LABEL_LENGTH },
849
+ cacheExpired: { type: "string", maxLength: MAX_LABEL_LENGTH },
850
+ providerChanged: { type: "string", maxLength: MAX_LABEL_LENGTH },
851
+ modelChanged: { type: "string", maxLength: MAX_LABEL_LENGTH }
852
+ },
853
+ additionalProperties: false
854
+ };
855
+ var Settings = {
856
+ type: "object",
857
+ properties: {
858
+ pricing: { type: "boolean" },
859
+ turnTotals: { type: "string", enum: ["latest", "sum"] },
860
+ fields: LineFields,
861
+ labels: LineLabels,
862
+ panel: { type: "boolean" },
863
+ sidebar: { type: "boolean" },
864
+ sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
865
+ quota: { type: "boolean" },
866
+ quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
867
+ },
868
+ required: ["pricing", "turnTotals", "fields", "labels", "panel", "sidebar", "sidebarTurns", "quota", "quotaName"],
869
+ additionalProperties: false
870
+ };
871
+ var Patch = {
872
+ type: "object",
873
+ properties: {
874
+ pricing: { type: "boolean" },
875
+ turnTotals: { type: "string", enum: ["latest", "sum"] },
876
+ fields: LineFields,
877
+ labels: LineLabels,
878
+ panel: { type: "boolean" },
879
+ sidebar: { type: "boolean" },
880
+ sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
881
+ quota: { type: "boolean" },
882
+ quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
883
+ },
884
+ additionalProperties: false
885
+ };
886
+ var Policy = {
887
+ type: "object",
888
+ properties: {
889
+ maintenance: { type: "boolean" },
890
+ exposePaths: { type: "boolean" }
891
+ },
892
+ required: ["maintenance", "exposePaths"],
893
+ additionalProperties: false
894
+ };
895
+ var Envelope = {
896
+ type: "object",
897
+ properties: {
898
+ settings: Settings,
899
+ policy: Policy
900
+ },
901
+ required: ["settings", "policy"],
902
+ additionalProperties: false
903
+ };
904
+ var Empty = { type: "object", properties: {}, additionalProperties: false };
905
+ var SetInput = {
906
+ type: "object",
907
+ properties: { patch: Patch },
908
+ required: ["patch"],
909
+ additionalProperties: false
910
+ };
911
+ var UsageInsightsSettings = Rpc2.define({
912
+ id: "usage-insights.settings",
913
+ methods: {
914
+ get: { input: Empty, output: Envelope },
915
+ set: { input: SetInput, output: Envelope },
916
+ reset: { input: Empty, output: Envelope }
917
+ },
918
+ events: {
919
+ updated: { schema: Envelope }
920
+ }
921
+ });
922
+
923
+ // src/pricing.ts
924
+ function money(value) {
925
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
926
+ }
927
+ function tokens(value) {
928
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
929
+ }
930
+ function priceTable(models) {
931
+ const table = new Map;
932
+ if (!Array.isArray(models))
933
+ return table;
934
+ for (const model of models) {
935
+ if (model === null || model === undefined)
936
+ continue;
937
+ const providerID = model.providerID;
938
+ const modelID = model.modelID ?? model.id;
939
+ if (typeof providerID !== "string" || providerID === "")
940
+ continue;
941
+ if (typeof modelID !== "string" || modelID === "")
942
+ continue;
943
+ if (!Array.isArray(model.cost) || model.cost.length === 0)
944
+ continue;
945
+ const tiers = [];
946
+ for (const cost of model.cost) {
947
+ if (cost === null || cost === undefined)
948
+ continue;
949
+ let tier;
950
+ if (cost.tier !== undefined) {
951
+ const size = cost.tier.size;
952
+ if (typeof size !== "number" || !Number.isFinite(size))
953
+ continue;
954
+ tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
955
+ }
956
+ tiers.push({
957
+ ...tier !== undefined ? { tier } : {},
958
+ input: money(cost.input),
959
+ output: money(cost.output),
960
+ cacheRead: money(cost.cache?.read),
961
+ cacheWrite: money(cost.cache?.write)
962
+ });
963
+ }
964
+ if (tiers.length > 0)
965
+ table.set(`${providerID}/${modelID}`, { tiers });
966
+ }
967
+ return table;
968
+ }
969
+ function priceOf(table, ref) {
970
+ if (ref.providerID === undefined || ref.providerID === "")
971
+ return;
972
+ if (ref.modelID === undefined || ref.modelID === "")
973
+ return;
974
+ return table.get(`${ref.providerID}/${ref.modelID}`);
975
+ }
976
+ function costOf(table, ref, usage) {
977
+ const price = priceOf(table, ref);
978
+ if (price === undefined)
979
+ return;
980
+ const input = tokens(usage.input);
981
+ const output = tokens(usage.output);
982
+ const reasoning = tokens(usage.reasoning);
983
+ const cacheRead = tokens(usage.cacheRead);
984
+ const cacheWrite = tokens(usage.cacheWrite);
985
+ const prompt = input + cacheRead + cacheWrite;
986
+ 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);
987
+ if (selected === undefined)
988
+ return;
989
+ if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
990
+ return 0;
991
+ const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
992
+ if (!Number.isFinite(billed) || billed <= 0)
993
+ return;
994
+ return billed / 1e6;
995
+ }
996
+
997
+ // src/stats/schema.ts
998
+ var SCHEMA_VERSION = 14;
999
+ var SCHEMA = `
1000
+ CREATE TABLE IF NOT EXISTS meta (
1001
+ key TEXT PRIMARY KEY,
1002
+ value TEXT NOT NULL
1003
+ );
1004
+
1005
+ CREATE TABLE IF NOT EXISTS sessions (
1006
+ session_id TEXT PRIMARY KEY,
1007
+ parent_id TEXT,
1008
+ directory TEXT,
1009
+ title TEXT,
1010
+ started_at INTEGER
1011
+ );
1012
+
1013
+ CREATE TABLE IF NOT EXISTS prompts (
1014
+ session_id TEXT NOT NULL,
1015
+ message_id TEXT NOT NULL,
1016
+ created_at INTEGER,
1017
+ PRIMARY KEY (session_id, message_id)
1018
+ );
1019
+ CREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);
1020
+
1021
+ CREATE TABLE IF NOT EXISTS steps (
1022
+ message_id TEXT PRIMARY KEY,
1023
+ session_id TEXT NOT NULL,
1024
+ provider_id TEXT,
1025
+ model_id TEXT,
1026
+ variant TEXT,
1027
+ input_tokens INTEGER NOT NULL DEFAULT 0,
1028
+ output_tokens INTEGER NOT NULL DEFAULT 0,
1029
+ reasoning_tokens INTEGER NOT NULL DEFAULT 0,
1030
+ cache_read INTEGER NOT NULL DEFAULT 0,
474
1031
  cache_write INTEGER NOT NULL DEFAULT 0,
475
1032
  cost REAL NOT NULL DEFAULT 0,
476
1033
  list_cost REAL,
477
1034
  created_at INTEGER,
1035
+ first_token_at INTEGER,
478
1036
  streamed_at INTEGER,
479
1037
  completed_at INTEGER,
480
1038
  finish TEXT,
@@ -490,16 +1048,18 @@ CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
490
1048
  CREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));
491
1049
  CREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));
492
1050
 
493
- CREATE TABLE IF NOT EXISTS events (
1051
+ -- The compaction timeline: when a compaction ended, by host event ID. The
1052
+ -- cost and tokens live in the usage table; the payload that used to be copied
1053
+ -- here was never read. Only compactions exist in this table by construction.
1054
+ CREATE TABLE IF NOT EXISTS compactions (
494
1055
  id INTEGER PRIMARY KEY AUTOINCREMENT,
495
1056
  session_id TEXT NOT NULL,
496
- kind TEXT NOT NULL,
497
1057
  message_id TEXT,
498
- at INTEGER,
499
- data TEXT
1058
+ at INTEGER
500
1059
  );
501
- CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
502
- CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
1060
+ CREATE INDEX IF NOT EXISTS compactions_session ON compactions(session_id, at);
1061
+ CREATE INDEX IF NOT EXISTS compactions_at ON compactions(at);
1062
+ CREATE UNIQUE INDEX IF NOT EXISTS compactions_message ON compactions(message_id) WHERE message_id IS NOT NULL;
503
1063
 
504
1064
  -- Usage the host reports with no assistant step of its own: the compaction
505
1065
  -- summarisation and the session-title generation. The host publishes it as
@@ -521,199 +1081,168 @@ CREATE TABLE IF NOT EXISTS usage (
521
1081
  CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
522
1082
  CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
523
1083
  `;
524
- var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
525
- function jsonText(value) {
526
- if (value === undefined || value === null)
527
- return null;
528
- if (typeof value === "string")
529
- return value;
1084
+ var TABLES = ["sessions", "prompts", "compactions", "steps", "usage"];
1085
+ function hasTable(db, name) {
530
1086
  try {
531
- return JSON.stringify(value);
1087
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
532
1088
  } catch {
533
- return null;
1089
+ return false;
534
1090
  }
535
1091
  }
536
- function finite(value) {
537
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
538
- }
539
- function tokenCount(value) {
540
- return Math.max(0, Math.floor(finite(value)));
541
- }
542
- function timestamp(value) {
543
- return typeof value === "number" && Number.isFinite(value) ? value : null;
1092
+ function columnsOf(db, table) {
1093
+ if (!hasTable(db, table))
1094
+ return new Set;
1095
+ return new Set(db.query(`PRAGMA table_info(${table})`).all().map((column) => column.name));
544
1096
  }
545
- var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
546
- var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
547
- function dropUnused(db) {
548
- const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
549
- const tables = new Set(objects.filter((row) => row.type === "table").map((row) => row.name));
550
- const indexes = new Set(objects.filter((row) => row.type === "index").map((row) => row.name));
551
- if (tables.has("http_responses"))
552
- db.exec("DROP TABLE http_responses");
553
- if (indexes.has("steps_upstream"))
554
- db.exec("DROP INDEX steps_upstream");
555
- if (indexes.has("steps_router"))
556
- db.exec("DROP INDEX steps_router");
557
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
558
- for (const name of REMOVED_COLUMNS) {
559
- if (columns.has(name))
560
- db.exec(`ALTER TABLE steps DROP COLUMN ${name}`);
1097
+ // src/stats/open.ts
1098
+ import { Database } from "bun:sqlite";
1099
+ import { chmodSync, mkdirSync } from "fs";
1100
+ import { dirname } from "path";
1101
+
1102
+ // src/stats/paths.ts
1103
+ import { homedir } from "os";
1104
+ import { join } from "path";
1105
+ import { statSync } from "fs";
1106
+ function defaultDbPath(env = process.env, platform = process.platform) {
1107
+ const name = join("opencode", "opencode-usage-insights", "usage.db");
1108
+ if (platform === "win32") {
1109
+ return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
561
1110
  }
562
- if (tables.has("events")) {
563
- const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(", ");
564
- db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
1111
+ if (platform === "darwin") {
1112
+ return join(homedir(), "Library", "Application Support", name);
565
1113
  }
1114
+ return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
566
1115
  }
567
- function addMissing(db) {
568
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
569
- if (columns.size > 0 && !columns.has("list_cost")) {
570
- db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
571
- }
1116
+ function expandHome(path, home = homedir()) {
1117
+ if (path === "~")
1118
+ return home;
1119
+ if (path.startsWith("~/") || path.startsWith("~\\"))
1120
+ return join(home, path.slice(2));
1121
+ return path;
572
1122
  }
573
- function dedupeEvents(db) {
574
- const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
575
- if (table === null)
576
- return;
577
- db.exec(`DELETE FROM events
578
- WHERE kind = 'compaction' AND message_id IS NULL
579
- AND rowid NOT IN (
580
- SELECT MIN(rowid) FROM events
581
- WHERE kind = 'compaction' AND message_id IS NULL
582
- GROUP BY session_id, at, data
583
- )`);
584
- db.exec(`DELETE FROM events
585
- WHERE message_id IS NOT NULL
586
- AND rowid NOT IN (
587
- SELECT MIN(rowid) FROM events
588
- WHERE message_id IS NOT NULL
589
- GROUP BY kind, message_id
590
- )`);
1123
+ function resolveDbPath(configured, env = process.env, platform = process.platform) {
1124
+ const home = env.HOME ?? env.USERPROFILE ?? homedir();
1125
+ if (configured)
1126
+ return expandHome(configured, home);
1127
+ if (env.OPENCODE_USAGE_INSIGHTS_DB)
1128
+ return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
1129
+ return defaultDbPath(env, platform);
591
1130
  }
592
- function addEventKey(db) {
593
- const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
594
- if (table === null)
1131
+ function ensureRegularFile(path) {
1132
+ let stats;
1133
+ try {
1134
+ stats = statSync(path);
1135
+ } catch {
595
1136
  return;
596
- db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
1137
+ }
1138
+ if (!stats.isFile())
1139
+ throw new Error(`not a regular file: ${path}`);
597
1140
  }
598
- function backfillCompactionUsage(db) {
599
- const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
600
- if (!tables.has("events") || !tables.has("usage"))
1141
+
1142
+ // src/stats/constants.ts
1143
+ var COMPACTION_KIND = "compaction";
1144
+
1145
+ // src/stats/legacy.ts
1146
+ function importTimestamp(value) {
1147
+ if (typeof value === "number")
1148
+ return Number.isFinite(value) ? value : undefined;
1149
+ if (typeof value !== "string")
601
1150
  return;
602
- db.exec(`INSERT OR IGNORE INTO usage (
603
- id, session_id, source, at, cost,
604
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
605
- )
606
- SELECT 'compaction:' || rowid, session_id, 'compaction', at,
607
- MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
608
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
609
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
610
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
611
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
612
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
613
- FROM events
614
- WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
615
- AND json_valid(data)`);
1151
+ const trimmed = value.trim();
1152
+ if (trimmed === "")
1153
+ return;
1154
+ const parsed = Number(trimmed);
1155
+ return Number.isFinite(parsed) ? parsed : undefined;
616
1156
  }
617
- function migrate(db) {
618
- dropUnused(db);
619
- addMissing(db);
620
- dedupeEvents(db);
621
- backfillCompactionUsage(db);
622
- addEventKey(db);
1157
+ function numberOrZero(value) {
1158
+ const parsed = importTimestamp(value);
1159
+ return parsed === undefined ? 0 : Math.max(0, parsed);
623
1160
  }
624
- var POSIX = process.platform !== "win32";
625
- function hardenDirectory(path) {
626
- if (!POSIX)
1161
+ function legacyCompactionUsage(row) {
1162
+ if (row.kind !== COMPACTION_KIND)
627
1163
  return;
628
- try {
629
- chmodSync(path, 448);
630
- } catch {}
631
- }
632
- function hardenFiles(path) {
633
- if (!POSIX || path === ":memory:")
1164
+ if (row.message_id !== undefined && row.message_id !== null && row.message_id !== "")
634
1165
  return;
635
- for (const file of [path, `${path}-wal`, `${path}-shm`]) {
1166
+ if (typeof row.session_id !== "string" || row.session_id === "")
1167
+ return;
1168
+ const at = importTimestamp(row.at);
1169
+ if (at === undefined)
1170
+ return;
1171
+ let payload = row.data;
1172
+ if (typeof payload === "string") {
636
1173
  try {
637
- chmodSync(file, 384);
638
- } catch {}
1174
+ payload = JSON.parse(payload);
1175
+ } catch {
1176
+ return;
1177
+ }
639
1178
  }
640
- }
641
- function prepareDirectory(path) {
642
- if (path === ":memory:")
1179
+ if (typeof payload !== "object" || payload === null)
643
1180
  return;
644
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
645
- hardenDirectory(dirname(path));
1181
+ const record = payload;
1182
+ const tokens = typeof record.tokens === "object" && record.tokens !== null ? record.tokens : {};
1183
+ const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
1184
+ return {
1185
+ sessionID: row.session_id,
1186
+ at,
1187
+ cost: numberOrZero(record.cost),
1188
+ input: Math.floor(numberOrZero(tokens.input)),
1189
+ output: Math.floor(numberOrZero(tokens.output)),
1190
+ reasoning: Math.floor(numberOrZero(tokens.reasoning)),
1191
+ cacheRead: Math.floor(numberOrZero(cache.read)),
1192
+ cacheWrite: Math.floor(numberOrZero(cache.write))
1193
+ };
646
1194
  }
647
- function openStatsDb(path) {
648
- if (path !== ":memory:")
649
- ensureRegularFile(path);
650
- prepareDirectory(path);
651
- const db = new Database(path, { create: true });
652
- db.exec("PRAGMA journal_mode = WAL");
653
- db.exec("PRAGMA busy_timeout = 5000");
654
- db.exec("PRAGMA synchronous = NORMAL");
655
- db.exec(SCHEMA);
656
- migrate(db);
657
- db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
658
- hardenFiles(path);
659
- return db;
1195
+
1196
+ // src/stats/records.ts
1197
+ function finite(value) {
1198
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
660
1199
  }
661
- function openStatsDbReadOnly(path) {
662
- ensureRegularFile(path);
663
- const db = new Database(path, { readonly: true });
664
- try {
665
- db.query("SELECT 1 FROM steps LIMIT 1").get();
666
- } catch (error) {
667
- db.close();
668
- throw error;
669
- }
670
- return db;
1200
+ function tokenCount(value) {
1201
+ return Math.max(0, Math.floor(finite(value)));
671
1202
  }
672
- function openStatsDbWrite(path) {
673
- if (path !== ":memory:")
674
- ensureRegularFile(path);
675
- prepareDirectory(path);
676
- const db = new Database(path, { create: true });
677
- db.exec("PRAGMA busy_timeout = 250");
678
- db.exec("PRAGMA synchronous = NORMAL");
679
- hardenFiles(path);
680
- return db;
1203
+ function timestamp(value) {
1204
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
681
1205
  }
682
- function recordStep(db, record) {
1206
+ var STEP_UPSERT = `
1207
+ INSERT INTO steps (
1208
+ message_id, session_id, provider_id, model_id, variant,
1209
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
1210
+ created_at, first_token_at, streamed_at, completed_at, finish, recorded_at
1211
+ ) VALUES (
1212
+ $messageID, $sessionID, $providerID, $modelID, $variant,
1213
+ $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
1214
+ $createdAt, $firstTokenAt, $streamedAt, $completedAt, $finish, $recordedAt
1215
+ )
1216
+ ON CONFLICT(message_id) DO UPDATE SET
1217
+ session_id = excluded.session_id,
1218
+ provider_id = COALESCE(excluded.provider_id, steps.provider_id),
1219
+ model_id = COALESCE(excluded.model_id, steps.model_id),
1220
+ variant = COALESCE(excluded.variant, steps.variant),
1221
+ input_tokens = excluded.input_tokens,
1222
+ output_tokens = excluded.output_tokens,
1223
+ reasoning_tokens = excluded.reasoning_tokens,
1224
+ cache_read = excluded.cache_read,
1225
+ cache_write = excluded.cache_write,
1226
+ cost = excluded.cost,
1227
+ -- A step that starts being charged loses its estimate; an estimate is
1228
+ -- kept when a replayed event arrives without a price table.
1229
+ list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
1230
+ created_at = COALESCE(excluded.created_at, steps.created_at),
1231
+ first_token_at = COALESCE(excluded.first_token_at, steps.first_token_at),
1232
+ streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
1233
+ completed_at = COALESCE(excluded.completed_at, steps.completed_at),
1234
+ finish = COALESCE(excluded.finish, steps.finish),
1235
+ recorded_at = excluded.recorded_at
1236
+ `;
1237
+ function stepCost(record) {
683
1238
  const cost = Math.max(0, finite(record.cost));
684
1239
  const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
685
- db.query(`INSERT INTO steps (
686
- message_id, session_id, parent_id, provider_id, model_id, variant,
687
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
688
- created_at, streamed_at, completed_at, finish, recorded_at
689
- ) VALUES (
690
- $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
691
- $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
692
- $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
693
- )
694
- ON CONFLICT(message_id) DO UPDATE SET
695
- session_id = excluded.session_id,
696
- parent_id = COALESCE(excluded.parent_id, steps.parent_id),
697
- provider_id = COALESCE(excluded.provider_id, steps.provider_id),
698
- model_id = COALESCE(excluded.model_id, steps.model_id),
699
- variant = COALESCE(excluded.variant, steps.variant),
700
- input_tokens = excluded.input_tokens,
701
- output_tokens = excluded.output_tokens,
702
- reasoning_tokens = excluded.reasoning_tokens,
703
- cache_read = excluded.cache_read,
704
- cache_write = excluded.cache_write,
705
- cost = excluded.cost,
706
- -- A step that starts being charged loses its estimate; an estimate is
707
- -- kept when a replayed event arrives without a price table.
708
- list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
709
- created_at = COALESCE(excluded.created_at, steps.created_at),
710
- streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
711
- completed_at = COALESCE(excluded.completed_at, steps.completed_at),
712
- finish = COALESCE(excluded.finish, steps.finish),
713
- recorded_at = excluded.recorded_at`).run({
1240
+ return { cost, listCost };
1241
+ }
1242
+ function stepParams(record, cost, listCost) {
1243
+ return {
714
1244
  $messageID: record.messageID,
715
1245
  $sessionID: record.sessionID,
716
- $parentID: record.parentID ?? null,
717
1246
  $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
718
1247
  $modelID: record.modelID ?? null,
719
1248
  $variant: record.variant ?? null,
@@ -725,11 +1254,16 @@ function recordStep(db, record) {
725
1254
  $cost: cost,
726
1255
  $listCost: listCost,
727
1256
  $createdAt: timestamp(record.createdAt),
1257
+ $firstTokenAt: timestamp(record.firstTokenAt),
728
1258
  $streamedAt: timestamp(record.streamedAt),
729
1259
  $completedAt: timestamp(record.completedAt),
730
1260
  $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
731
1261
  $recordedAt: timestamp(record.recordedAt) ?? Date.now()
732
- });
1262
+ };
1263
+ }
1264
+ function recordStep(db, record) {
1265
+ const { cost, listCost } = stepCost(record);
1266
+ db.query(STEP_UPSERT).run(stepParams(record, cost, listCost));
733
1267
  }
734
1268
  function recordUsage(db, record) {
735
1269
  if (typeof record.id !== "string" || record.id === "")
@@ -762,380 +1296,444 @@ function recordPrompt(db, record) {
762
1296
  $createdAt: timestamp(record.createdAt)
763
1297
  });
764
1298
  }
765
- function recordEvent(db, record) {
766
- db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
767
- VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
1299
+ function recordCompaction(db, record) {
1300
+ db.query(`INSERT OR IGNORE INTO compactions (session_id, message_id, at)
1301
+ VALUES ($sessionID, $messageID, $at)`).run({
768
1302
  $sessionID: record.sessionID,
769
- $kind: sanitizeLabel(record.kind, 64),
770
1303
  $messageID: record.messageID ?? null,
771
- $at: timestamp(record.at) ?? Date.now(),
772
- $data: jsonText(record.data)
1304
+ $at: timestamp(record.at) ?? Date.now()
773
1305
  });
774
1306
  }
775
1307
  function upsertSession(db, record) {
776
- db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at, updated_at)
777
- VALUES ($sessionID, $parentID, $directory, $title, $startedAt, $updatedAt)
1308
+ db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at)
1309
+ VALUES ($sessionID, $parentID, $directory, $title, $startedAt)
778
1310
  ON CONFLICT(session_id) DO UPDATE SET
779
1311
  parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
780
1312
  directory = COALESCE(excluded.directory, sessions.directory),
781
1313
  title = COALESCE(excluded.title, sessions.title),
782
- started_at = COALESCE(sessions.started_at, excluded.started_at),
783
- updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`).run({
1314
+ started_at = COALESCE(sessions.started_at, excluded.started_at)`).run({
784
1315
  $sessionID: record.sessionID,
785
1316
  $parentID: record.parentID ?? null,
786
1317
  $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
787
1318
  $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
788
- $startedAt: timestamp(record.startedAt),
789
- $updatedAt: timestamp(record.updatedAt)
1319
+ $startedAt: timestamp(record.startedAt)
790
1320
  });
791
1321
  }
792
1322
 
793
- // src/core.ts
794
- var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
795
- function transcriptTail(messages, count) {
796
- const segments = [];
797
- let current = [];
798
- for (let index = messages.length - 1;index >= 0; index -= 1) {
799
- const message = messages[index];
800
- if (message.type === "assistant") {
801
- current.unshift(message);
802
- continue;
1323
+ // src/stats/migrate.ts
1324
+ var REMOVED_COLUMNS = {
1325
+ steps: ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router", "parent_id"],
1326
+ sessions: ["updated_at"]
1327
+ };
1328
+ function dropUnused(db) {
1329
+ const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
1330
+ const indexes = new Set(objects.filter((row) => row.type === "index").map((row) => row.name));
1331
+ if (hasTable(db, "http_responses"))
1332
+ db.exec("DROP TABLE http_responses");
1333
+ if (indexes.has("steps_upstream"))
1334
+ db.exec("DROP INDEX steps_upstream");
1335
+ if (indexes.has("steps_router"))
1336
+ db.exec("DROP INDEX steps_router");
1337
+ for (const [table, names] of Object.entries(REMOVED_COLUMNS)) {
1338
+ const columns = columnsOf(db, table);
1339
+ for (const name of names) {
1340
+ if (columns.has(name))
1341
+ db.exec(`ALTER TABLE ${table} DROP COLUMN ${name}`);
803
1342
  }
804
- if (!PROMPT_BOUNDARIES.has(message.type))
805
- continue;
806
- if (current.length === 0)
807
- continue;
808
- segments.unshift({ assistants: current, prompt: message });
809
- if (segments.length >= count)
810
- return segments;
811
- current = [];
812
1343
  }
813
- if (current.length > 0 && segments.length < count)
814
- segments.unshift({ assistants: current, prompt: undefined });
815
- return segments;
816
1344
  }
817
- function countOf(value) {
818
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
819
- }
820
- function amountOf(value) {
821
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
822
- }
823
- function stampOf(value) {
824
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
825
- }
826
- function tokenCounts(message) {
827
- const tokens = message.tokens;
828
- return {
829
- input: countOf(tokens?.input),
830
- output: countOf(tokens?.output),
831
- reasoning: countOf(tokens?.reasoning),
832
- read: countOf(tokens?.cache?.read),
833
- write: countOf(tokens?.cache?.write)
834
- };
835
- }
836
- function totalize(steps) {
837
- const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
838
- for (const step of steps) {
839
- const counts = tokenCounts(step);
840
- totals.input += counts.input;
841
- totals.cached += counts.read;
842
- totals.output += counts.output;
843
- totals.reasoning += counts.reasoning;
844
- totals.cacheWrite += counts.write;
845
- totals.cost += amountOf(step.cost);
846
- totals.listCost += amountOf(step.listCost);
1345
+ function addMissing(db) {
1346
+ const columns = columnsOf(db, "steps");
1347
+ if (columns.size > 0 && !columns.has("list_cost")) {
1348
+ db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
1349
+ }
1350
+ if (columns.size > 0 && !columns.has("first_token_at")) {
1351
+ db.exec("ALTER TABLE steps ADD COLUMN first_token_at INTEGER");
847
1352
  }
848
- return totals;
849
1353
  }
850
- function identityKey(model) {
851
- if (!model)
1354
+ function dedupeLegacyCompactions(db) {
1355
+ if (!hasTable(db, "events"))
852
1356
  return;
853
- return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
854
- }
855
- function cacheRead(message) {
856
- return countOf(message?.tokens?.cache?.read);
857
- }
858
- function stepCreated(message) {
859
- return stampOf(message?.time?.created);
860
- }
861
- function stepEnd(message) {
862
- const time = message?.time;
863
- if (!time)
1357
+ const columns = columnsOf(db, "events");
1358
+ if (!["session_id", "kind", "message_id", "at"].every((name) => columns.has(name)))
864
1359
  return;
865
- return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
1360
+ if (columns.has("data")) {
1361
+ db.query(`DELETE FROM events
1362
+ WHERE kind = ? AND message_id IS NULL
1363
+ AND rowid NOT IN (
1364
+ SELECT MIN(rowid) FROM events
1365
+ WHERE kind = ? AND message_id IS NULL
1366
+ GROUP BY session_id, at, data
1367
+ )`).run(COMPACTION_KIND, COMPACTION_KIND);
1368
+ } else {
1369
+ db.query(`DELETE FROM events
1370
+ WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL
1371
+ AND rowid NOT IN (
1372
+ SELECT MIN(rowid) FROM events
1373
+ WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL
1374
+ GROUP BY session_id, at
1375
+ )`).run(COMPACTION_KIND, COMPACTION_KIND);
1376
+ }
1377
+ db.exec(`DELETE FROM events
1378
+ WHERE message_id IS NOT NULL
1379
+ AND rowid NOT IN (
1380
+ SELECT MIN(rowid) FROM events
1381
+ WHERE message_id IS NOT NULL
1382
+ GROUP BY message_id
1383
+ )`);
866
1384
  }
867
- function cacheDrop(reference, current, scope = "provider") {
868
- if (!reference)
869
- return;
870
- const before = reference.model;
871
- const after = current.model;
872
- if (!before || !after)
873
- return;
874
- if (scope === "provider" && before.providerID !== after.providerID)
1385
+ function backfillCompactionUsage(db) {
1386
+ if (!hasTable(db, "events") || !hasTable(db, "usage"))
875
1387
  return;
876
- if (before.id !== after.id || (before.variant ?? "") !== (after.variant ?? "")) {
1388
+ const columns = columnsOf(db, "events");
1389
+ if (!["session_id", "kind", "message_id", "at", "data"].every((name) => columns.has(name)))
877
1390
  return;
1391
+ const rows = db.query(`SELECT rowid AS id, session_id, kind, message_id, at, data
1392
+ FROM events
1393
+ WHERE kind = ? AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL`).all(COMPACTION_KIND);
1394
+ for (const row of rows) {
1395
+ const legacy = legacyCompactionUsage(row);
1396
+ if (legacy === undefined)
1397
+ continue;
1398
+ recordUsage(db, {
1399
+ id: `compaction:${String(row.id)}`,
1400
+ sessionID: legacy.sessionID,
1401
+ source: COMPACTION_KIND,
1402
+ at: legacy.at,
1403
+ cost: legacy.cost,
1404
+ input: legacy.input,
1405
+ output: legacy.output,
1406
+ reasoning: legacy.reasoning,
1407
+ cacheRead: legacy.cacheRead,
1408
+ cacheWrite: legacy.cacheWrite
1409
+ });
878
1410
  }
879
- const drop = cacheRead(reference) - cacheRead(current);
880
- if (isNoiseDrop(after.providerID, drop))
881
- return;
882
- return drop > 0 ? drop : undefined;
883
- }
884
- function stepGap(reference, current) {
885
- const ended = stepEnd(reference);
886
- const started = stepCreated(current);
887
- if (ended === undefined || started === undefined)
888
- return;
889
- return Math.max(0, started - ended);
890
1411
  }
891
- function tokensPerSecond(produced, from, to) {
892
- if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
1412
+ function migrateLegacyCompactions(db) {
1413
+ if (!hasTable(db, "events"))
893
1414
  return;
894
- if (!Number.isFinite(produced) || produced <= 0)
1415
+ const columns = columnsOf(db, "events");
1416
+ if (!["session_id", "kind", "message_id", "at"].every((name) => columns.has(name)))
895
1417
  return;
896
- return produced / (to - from) * 1000;
1418
+ db.query(`INSERT OR IGNORE INTO compactions (session_id, message_id, at)
1419
+ SELECT session_id, message_id, at FROM events WHERE kind = ?`).run(COMPACTION_KIND);
1420
+ db.exec("DROP TABLE events");
897
1421
  }
898
- var DROP_EXEMPT_PROVIDERS = new Set(["openai"]);
899
- function isSettledStep(message) {
900
- if (message.time?.completed !== undefined)
901
- return true;
902
- return message.finish !== undefined && message.finish !== null;
1422
+ function migrate(db) {
1423
+ db.transaction(() => {
1424
+ dropUnused(db);
1425
+ addMissing(db);
1426
+ dedupeLegacyCompactions(db);
1427
+ backfillCompactionUsage(db);
1428
+ migrateLegacyCompactions(db);
1429
+ })();
903
1430
  }
904
- function computeTurn(messages, session) {
905
- const segments = transcriptTail(messages, 2);
906
- const last = segments[segments.length - 1];
907
- if (!last)
908
- return;
909
- const previous = segments[segments.length - 2];
910
- const lastStep = last.assistants[last.assistants.length - 1];
911
- if (!lastStep)
1431
+
1432
+ // src/stats/open.ts
1433
+ var POSIX = process.platform !== "win32";
1434
+ function hardenDirectory(path) {
1435
+ if (!POSIX)
912
1436
  return;
913
- if (!isSettledStep(lastStep))
1437
+ try {
1438
+ chmodSync(path, 448);
1439
+ } catch {}
1440
+ }
1441
+ function hardenFiles(path) {
1442
+ if (!POSIX || path === ":memory:")
914
1443
  return;
915
- const previousStep = previous?.assistants[previous.assistants.length - 1];
916
- const settled = last.assistants.filter(isSettledStep);
917
- const drops = [];
918
- let reference = previousStep !== undefined && isSettledStep(previousStep) ? previousStep : undefined;
919
- for (const step of settled) {
920
- const drop = cacheDrop(reference, step);
921
- if (drop !== undefined) {
922
- drops.push({
923
- messageID: step.id,
924
- tokens: drop,
925
- prevCached: cacheRead(reference),
926
- gapMs: stepGap(reference, step)
927
- });
928
- }
929
- reference = step;
1444
+ for (const file of [path, `${path}-wal`, `${path}-shm`]) {
1445
+ try {
1446
+ chmodSync(file, 384);
1447
+ } catch {}
930
1448
  }
931
- const provider = lastStep.model?.providerID;
932
- const previousProvider = previousStep?.model?.providerID;
933
- const key = identityKey(lastStep.model);
934
- const previousKey = identityKey(previousStep?.model);
935
- return {
936
- endAt: stepEnd(lastStep),
937
- startAt: stepCreated(settled[0] ?? lastStep),
938
- promptAt: stampOf(last.prompt?.time?.created),
939
- promptGapMs: promptGap(last.prompt, previous?.prompt),
940
- providerID: provider,
941
- modelID: lastStep.model?.id,
942
- variant: lastStep.model?.variant,
943
- providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,
944
- modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,
945
- totals: totalize(settled),
946
- latest: totalize([lastStep]),
947
- session,
948
- drops,
949
- cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),
950
- cacheExpired: drops.length > 0,
951
- steps: settled.length
952
- };
953
1449
  }
954
- function promptGap(current, previous) {
955
- const now = stampOf(current?.time?.created);
956
- const before = stampOf(previous?.time?.created);
957
- if (now === undefined || before === undefined)
1450
+ function prepareDirectory(path) {
1451
+ if (path === ":memory:")
958
1452
  return;
959
- return Math.max(0, now - before);
1453
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
1454
+ hardenDirectory(dirname(path));
960
1455
  }
961
- function isNoiseDrop(providerID, drop) {
962
- if (providerID === undefined)
963
- return false;
964
- return DROP_EXEMPT_PROVIDERS.has(providerID) && drop >= 1024 && drop <= 2048;
1456
+ function openStatsDb(path) {
1457
+ if (path !== ":memory:")
1458
+ ensureRegularFile(path);
1459
+ prepareDirectory(path);
1460
+ const db = new Database(path, { create: true });
1461
+ try {
1462
+ db.exec("PRAGMA journal_mode = WAL");
1463
+ db.exec("PRAGMA busy_timeout = 5000");
1464
+ db.exec("PRAGMA synchronous = NORMAL");
1465
+ db.exec(SCHEMA);
1466
+ migrate(db);
1467
+ db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
1468
+ hardenFiles(path);
1469
+ return db;
1470
+ } catch (error) {
1471
+ db.close();
1472
+ throw error;
1473
+ }
965
1474
  }
966
- var DEFAULT_LABELS = {
967
- delta: "\u0394",
968
- turn: "",
969
- session: "sess",
970
- step: "step",
971
- steps: "steps",
972
- input: "in",
973
- cached: "cached",
974
- output: "out",
975
- reasoning: "reason",
976
- cost: "cost",
977
- estimate: "\u2248",
978
- cacheExpired: "cache expired",
979
- providerChanged: "changed",
980
- modelChanged: "model changed"
981
- };
982
- var DEFAULT_FIELDS = {
983
- clock: true,
984
- delta: true,
985
- model: true,
986
- variant: true,
987
- turn: true,
988
- session: true,
989
- reasoning: false,
990
- cost: true,
991
- cacheExpiry: true
992
- };
993
- function formatClock(ms) {
994
- if (!Number.isFinite(ms))
995
- return "--:--";
996
- const date = new Date(ms);
997
- const pad = (value) => String(value).padStart(2, "0");
998
- return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
1475
+ function openStatsDbReadOnly(path) {
1476
+ ensureRegularFile(path);
1477
+ const db = new Database(path, { readonly: true });
1478
+ try {
1479
+ db.query("SELECT 1 FROM steps LIMIT 1").get();
1480
+ } catch (error) {
1481
+ db.close();
1482
+ throw error;
1483
+ }
1484
+ return db;
999
1485
  }
1000
- function formatDuration(ms) {
1001
- if (!Number.isFinite(ms))
1002
- return "\u2013";
1003
- const totalSeconds = Math.max(0, Math.floor(ms / 1000));
1004
- const seconds = totalSeconds % 60;
1005
- const minutes = Math.floor(totalSeconds / 60) % 60;
1006
- const hours = Math.floor(totalSeconds / 3600) % 24;
1007
- const days = Math.floor(totalSeconds / 86400);
1008
- if (days > 0)
1009
- return `${days}d${hours}h`;
1010
- if (hours > 0)
1011
- return `${hours}h${String(minutes).padStart(2, "0")}m`;
1012
- if (minutes > 0)
1013
- return `${minutes}m${String(seconds).padStart(2, "0")}s`;
1014
- return `${seconds}s`;
1486
+ function openStatsDbWrite(path) {
1487
+ if (path !== ":memory:")
1488
+ ensureRegularFile(path);
1489
+ prepareDirectory(path);
1490
+ const db = new Database(path, { create: true });
1491
+ db.exec("PRAGMA busy_timeout = 250");
1492
+ db.exec("PRAGMA synchronous = NORMAL");
1493
+ hardenFiles(path);
1494
+ return db;
1015
1495
  }
1016
- function formatTokens(value) {
1017
- const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
1018
- if (n < 1000)
1019
- return String(n);
1020
- if (n < 999500) {
1021
- const k = n / 1000;
1022
- return `${trimZeros(k.toFixed(k < 10 ? 2 : 1))}k`;
1496
+ // src/recorder.ts
1497
+ function createRecorder(db, options) {
1498
+ const MAX_TRACKED_SESSIONS = 512;
1499
+ const MAX_PENDING = 256;
1500
+ const pending = new Map;
1501
+ const lastModel = new Map;
1502
+ const now = options?.now ?? (() => Date.now());
1503
+ const MAX_DEFERRED = 256;
1504
+ const deferred = [];
1505
+ function isBusy(error) {
1506
+ const code = error?.code;
1507
+ return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED";
1023
1508
  }
1024
- if (n < 999500000) {
1025
- const m = n / 1e6;
1026
- return `${trimZeros(m.toFixed(m < 10 ? 2 : 1))}M`;
1509
+ function enqueue(run) {
1510
+ if (deferred.length >= MAX_DEFERRED)
1511
+ deferred.shift();
1512
+ deferred.push(run);
1027
1513
  }
1028
- return `${Math.round(n / 1e6)}M`;
1029
- }
1030
- function trimZeros(value) {
1031
- return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
1032
- }
1033
- function formatCost(value) {
1034
- if (!Number.isFinite(value) || value <= 0)
1035
- return "$0";
1036
- if (value < 0.00005)
1037
- return "<$0.0001";
1038
- if (value < 1)
1039
- return `$${value.toFixed(4)}`;
1040
- return `$${value.toFixed(2)}`;
1041
- }
1042
- function formatMoney(charged, estimated, marker = "\u2248") {
1043
- const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
1044
- const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
1045
- if (paid !== undefined && estimate !== undefined)
1046
- return `${paid} + ${estimate}`;
1047
- return paid ?? estimate;
1048
- }
1049
- function formatSpend(charged, estimated, marker = "\u2248") {
1050
- const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
1051
- const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
1052
- if (estimate > 0)
1053
- return `${marker.trim()}${formatCost(paid + estimate)}`;
1054
- return formatCost(paid);
1055
- }
1056
- function displayTotals(totals) {
1057
- const prompt = totals.input + totals.cached + totals.cacheWrite;
1058
- return {
1059
- input: prompt - totals.cached,
1060
- cached: totals.cached,
1061
- cacheWrite: totals.cacheWrite,
1062
- output: totals.output + totals.reasoning,
1063
- reasoning: totals.reasoning,
1064
- cost: totals.cost,
1065
- listCost: totals.listCost,
1066
- steps: totals.steps,
1067
- prompt
1068
- };
1069
- }
1070
- function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
1071
- const display = displayTotals(totals);
1072
- const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
1073
- const parts = [
1074
- input,
1075
- `${labels.cached} ${formatTokens(display.cached)}`,
1076
- `${labels.output} ${formatTokens(display.output)}`
1077
- ];
1078
- if (fields.reasoning)
1079
- parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
1080
- const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
1081
- if (money !== undefined)
1082
- parts.push(`${labels.cost} ${money}`);
1083
- const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
1084
- const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
1085
- const numbers = parts.join(", ");
1086
- if (head === "")
1087
- return numbers;
1088
- return stepCount > 1 ? `${head} \xB7 ${numbers}` : `${head} ${numbers}`;
1089
- }
1090
- function formatLineSegments(stats, options) {
1091
- const labels = { ...DEFAULT_LABELS, ...options?.labels };
1092
- const fields = { ...DEFAULT_FIELDS, ...options?.fields };
1093
- const turnTotals = options?.turnTotals ?? "latest";
1094
- const estimates = options?.estimates !== false;
1095
- const segments = [];
1096
- if (fields.clock && stats.endAt !== undefined) {
1097
- segments.push({ text: formatClock(stats.endAt), tone: "muted" });
1514
+ function flushDeferred() {
1515
+ while (deferred.length > 0) {
1516
+ const next = deferred[0];
1517
+ try {
1518
+ next();
1519
+ } catch {
1520
+ return;
1521
+ }
1522
+ deferred.shift();
1523
+ }
1098
1524
  }
1099
- if (fields.delta && stats.promptGapMs !== undefined) {
1100
- segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: "muted" });
1525
+ function write(run) {
1526
+ if (deferred.length > 0) {
1527
+ flushDeferred();
1528
+ if (deferred.length > 0) {
1529
+ enqueue(run);
1530
+ return;
1531
+ }
1532
+ }
1533
+ try {
1534
+ run();
1535
+ } catch (error) {
1536
+ if (isBusy(error))
1537
+ enqueue(run);
1538
+ }
1101
1539
  }
1102
- if (stats.providerID !== undefined) {
1103
- let text = stats.providerID;
1104
- if (fields.model && stats.modelID !== undefined)
1105
- text += `/${stats.modelID}`;
1106
- if (fields.variant && stats.variant)
1107
- text += ` ${stats.variant}`;
1108
- segments.push({ text, tone: stats.providerChanged ? "warning" : "base" });
1109
- if (stats.providerChanged)
1110
- segments.push({ text: labels.providerChanged, tone: "warning" });
1111
- else if (stats.modelChanged)
1112
- segments.push({ text: labels.modelChanged, tone: "muted" });
1540
+ function remember(map, key, value, limit) {
1541
+ map.delete(key);
1542
+ map.set(key, value);
1543
+ while (map.size > limit) {
1544
+ const oldest = map.keys().next();
1545
+ if (oldest.done === true)
1546
+ break;
1547
+ map.delete(oldest.value);
1548
+ }
1113
1549
  }
1114
- if (fields.turn && stats.totals.steps > 0) {
1115
- const totals = turnTotals === "sum" ? stats.totals : stats.latest;
1116
- segments.push({
1117
- text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
1118
- tone: "base"
1119
- });
1550
+ function forget(sessionID) {
1551
+ lastModel.delete(sessionID);
1552
+ for (const [messageID, step] of pending) {
1553
+ if (step.sessionID === sessionID)
1554
+ pending.delete(messageID);
1555
+ }
1120
1556
  }
1121
- if (fields.session && stats.session) {
1122
- segments.push({
1123
- text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
1124
- tone: "muted"
1557
+ function recordPendingStep(messageID, data, finish, at) {
1558
+ const sessionID = data.sessionID;
1559
+ if (typeof sessionID !== "string")
1560
+ return;
1561
+ const info = pending.get(messageID);
1562
+ pending.delete(messageID);
1563
+ const model = info?.model ?? lastModel.get(sessionID);
1564
+ const charged = data.cost;
1565
+ const estimate = charged !== undefined && charged > 0 ? undefined : options?.price?.({ providerID: model?.providerID, modelID: model?.id }, {
1566
+ input: data.tokens?.input,
1567
+ output: data.tokens?.output,
1568
+ reasoning: data.tokens?.reasoning,
1569
+ cacheRead: data.tokens?.cache?.read,
1570
+ cacheWrite: data.tokens?.cache?.write
1125
1571
  });
1572
+ write(() => recordStep(db, {
1573
+ messageID,
1574
+ sessionID,
1575
+ providerID: model?.providerID,
1576
+ modelID: model?.id,
1577
+ variant: model?.variant,
1578
+ input: data.tokens?.input,
1579
+ output: data.tokens?.output,
1580
+ reasoning: data.tokens?.reasoning,
1581
+ cacheRead: data.tokens?.cache?.read,
1582
+ cacheWrite: data.tokens?.cache?.write,
1583
+ cost: data.cost,
1584
+ listCost: estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined,
1585
+ createdAt: info?.started,
1586
+ firstTokenAt: info?.firstToken,
1587
+ streamedAt: info?.streamed,
1588
+ completedAt: at,
1589
+ finish,
1590
+ recordedAt: now()
1591
+ }));
1126
1592
  }
1127
- if (fields.cacheExpiry && stats.cacheExpired) {
1128
- const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
1129
- segments.push({ text: `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${count})`, tone: "warning" });
1593
+ function handleEvent(event) {
1594
+ if (deferred.length > 0)
1595
+ flushDeferred();
1596
+ const data = event.data ?? {};
1597
+ const at = typeof event.created === "number" ? event.created : now();
1598
+ const sessionID = typeof data.sessionID === "string" ? data.sessionID : undefined;
1599
+ switch (event.type) {
1600
+ case "session.created": {
1601
+ if (sessionID === undefined)
1602
+ return;
1603
+ write(() => upsertSession(db, {
1604
+ sessionID,
1605
+ parentID: data.parentID,
1606
+ directory: data.location?.directory,
1607
+ title: data.title,
1608
+ startedAt: at
1609
+ }));
1610
+ if (data.model !== undefined)
1611
+ remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
1612
+ return;
1613
+ }
1614
+ case "session.deleted": {
1615
+ if (sessionID !== undefined)
1616
+ forget(sessionID);
1617
+ return;
1618
+ }
1619
+ case "session.renamed": {
1620
+ if (sessionID === undefined)
1621
+ return;
1622
+ write(() => upsertSession(db, { sessionID, title: data.title }));
1623
+ return;
1624
+ }
1625
+ case "session.moved": {
1626
+ if (sessionID === undefined)
1627
+ return;
1628
+ write(() => upsertSession(db, { sessionID, directory: data.location?.directory }));
1629
+ return;
1630
+ }
1631
+ case "session.inbox.enqueued": {
1632
+ if (sessionID === undefined)
1633
+ return;
1634
+ if (data.item?.type !== "user" && data.item?.type !== "synthetic")
1635
+ return;
1636
+ const inboxID = data.inboxID;
1637
+ if (typeof inboxID !== "string")
1638
+ return;
1639
+ write(() => recordPrompt(db, { sessionID, messageID: inboxID, createdAt: at }));
1640
+ return;
1641
+ }
1642
+ case "session.model.selected": {
1643
+ if (sessionID !== undefined && data.model !== undefined)
1644
+ remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
1645
+ return;
1646
+ }
1647
+ case "session.step.started": {
1648
+ if (sessionID === undefined || typeof data.assistantMessageID !== "string")
1649
+ return;
1650
+ remember(pending, data.assistantMessageID, {
1651
+ messageID: data.assistantMessageID,
1652
+ sessionID,
1653
+ started: typeof data.started === "number" ? data.started : undefined,
1654
+ firstToken: undefined,
1655
+ streamed: undefined,
1656
+ model: data.model
1657
+ }, MAX_PENDING);
1658
+ return;
1659
+ }
1660
+ case "session.step.first-token": {
1661
+ if (typeof data.assistantMessageID !== "string")
1662
+ return;
1663
+ const info = pending.get(data.assistantMessageID);
1664
+ if (info !== undefined)
1665
+ info.firstToken = at;
1666
+ return;
1667
+ }
1668
+ case "session.step.streamed": {
1669
+ if (typeof data.assistantMessageID !== "string")
1670
+ return;
1671
+ const info = pending.get(data.assistantMessageID);
1672
+ if (info !== undefined)
1673
+ info.streamed = at;
1674
+ return;
1675
+ }
1676
+ case "session.step.ended": {
1677
+ if (typeof data.assistantMessageID !== "string")
1678
+ return;
1679
+ recordPendingStep(data.assistantMessageID, data, data.finish ?? "unknown", at);
1680
+ return;
1681
+ }
1682
+ case "session.step.failed": {
1683
+ if (typeof data.assistantMessageID !== "string")
1684
+ return;
1685
+ recordPendingStep(data.assistantMessageID, data, data.finish ?? "error", at);
1686
+ return;
1687
+ }
1688
+ case "session.usage.recorded": {
1689
+ if (sessionID === undefined)
1690
+ return;
1691
+ const source = typeof data.source === "string" ? data.source : undefined;
1692
+ if (source === undefined || source === "generate")
1693
+ return;
1694
+ const id = typeof event.id === "string" && event.id !== "" ? event.id : `${sessionID}:${source}:${at}:${data.cost ?? 0}`;
1695
+ write(() => recordUsage(db, {
1696
+ id,
1697
+ sessionID,
1698
+ source,
1699
+ at,
1700
+ cost: data.cost,
1701
+ input: data.tokens?.input,
1702
+ output: data.tokens?.output,
1703
+ reasoning: data.tokens?.reasoning,
1704
+ cacheRead: data.tokens?.cache?.read,
1705
+ cacheWrite: data.tokens?.cache?.write
1706
+ }));
1707
+ return;
1708
+ }
1709
+ case "session.compaction.ended": {
1710
+ if (sessionID === undefined)
1711
+ return;
1712
+ const messageID = typeof event.id === "string" && event.id !== "" ? event.id : `compaction:${sessionID}:${at}`;
1713
+ write(() => recordCompaction(db, { sessionID, messageID, at }));
1714
+ return;
1715
+ }
1716
+ default:
1717
+ return;
1718
+ }
1719
+ }
1720
+ function pendingFor(sessionID) {
1721
+ let found;
1722
+ for (const item of pending.values()) {
1723
+ if (item.sessionID !== sessionID)
1724
+ continue;
1725
+ if (found === undefined || (item.started ?? 0) >= (found.started ?? 0))
1726
+ found = item;
1727
+ }
1728
+ return found;
1130
1729
  }
1131
- return segments;
1132
- }
1133
- function formatLine(stats, options) {
1134
- return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
1730
+ return { handleEvent, pendingFor };
1135
1731
  }
1136
1732
 
1733
+ // src/service.ts
1734
+ import { basename } from "path";
1735
+
1137
1736
  // src/stats/queries.ts
1138
- var COMPACTION_KIND = "compaction";
1139
1737
  var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
1140
1738
  function spend(usage) {
1141
1739
  return usage.cost + usage.listCost;
@@ -1205,9 +1803,10 @@ function otherUsageRows(db, range, filters) {
1205
1803
  }
1206
1804
  }
1207
1805
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
1208
- var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
1806
+ var MODEL_KEY_SEPARATOR = "#";
1807
+ var MODEL_KEY_SQL = `COALESCE(model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(variant, '')`;
1209
1808
  function modelKey(modelID, variant) {
1210
- return `${modelID}#${variant ?? ""}`;
1809
+ return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
1211
1810
  }
1212
1811
  function modelLabel(modelID, variant) {
1213
1812
  return variant === undefined ? modelID : `${modelID} ${variant}`;
@@ -1278,7 +1877,10 @@ function overview(db, range, filters) {
1278
1877
  MIN(${STEP_TIME}) AS firstAt,
1279
1878
  MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
1280
1879
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
1281
- COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
1880
+ COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,
1881
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,
1882
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)
1883
+ THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow
1282
1884
  FROM steps ${steps.where}`).get(...steps.params);
1283
1885
  const prompts = rangeWhere(range, "created_at");
1284
1886
  const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
@@ -1289,6 +1891,10 @@ function overview(db, range, filters) {
1289
1891
  }
1290
1892
  const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
1291
1893
  const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
1894
+ const ttftFilter = steps.where === "" ? "WHERE" : `${steps.where} AND`;
1895
+ const ttftRows = db.query(`SELECT MAX(0, first_token_at - created_at) AS ttft
1896
+ FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`).all(...steps.params);
1897
+ const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50);
1292
1898
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
1293
1899
  const other = otherUsage(db, range, filters);
1294
1900
  return {
@@ -1300,7 +1906,9 @@ function overview(db, range, filters) {
1300
1906
  firstAt: row?.firstAt ?? undefined,
1301
1907
  lastAt: row?.lastAt ?? undefined,
1302
1908
  cacheHitRatio: cacheHitRatio(usage),
1303
- tps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0)
1909
+ tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),
1910
+ requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),
1911
+ ttft
1304
1912
  };
1305
1913
  }
1306
1914
  function models(db, range, filters) {
@@ -1455,7 +2063,11 @@ function stepMessage(row) {
1455
2063
  return {
1456
2064
  type: "assistant",
1457
2065
  id: row.message_id,
1458
- time: { created: row.created_at ?? row.recorded_at, completed: row.completed_at ?? undefined },
2066
+ time: {
2067
+ created: row.created_at ?? row.recorded_at,
2068
+ firstToken: row.first_token_at ?? undefined,
2069
+ completed: row.completed_at ?? undefined
2070
+ },
1459
2071
  model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
1460
2072
  tokens: {
1461
2073
  input: row.input_tokens ?? 0,
@@ -1486,7 +2098,7 @@ function turns(db, options) {
1486
2098
  }
1487
2099
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
1488
2100
  input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
1489
- created_at, streamed_at, recorded_at, completed_at, finish
2101
+ created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
1490
2102
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
1491
2103
  ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
1492
2104
  const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
@@ -1529,12 +2141,22 @@ function turns(db, options) {
1529
2141
  const variant = last.variant ?? undefined;
1530
2142
  let produced = 0;
1531
2143
  let window = 0;
2144
+ let decodeProduced = 0;
2145
+ let decodeWindow = 0;
1532
2146
  for (const row of bucket) {
1533
- if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
1534
- continue;
1535
- produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
1536
- window += row.streamed_at - row.created_at;
2147
+ const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
2148
+ if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {
2149
+ produced += tokens;
2150
+ window += row.streamed_at - row.created_at;
2151
+ }
2152
+ const start = row.first_token_at ?? row.created_at;
2153
+ if (start !== null && row.streamed_at !== null && row.streamed_at > start) {
2154
+ decodeProduced += tokens;
2155
+ decodeWindow += row.streamed_at - start;
2156
+ }
1537
2157
  }
2158
+ const first = bucket[0];
2159
+ const ttft = first !== undefined && first.created_at !== null && first.first_token_at !== null ? Math.max(0, first.first_token_at - first.created_at) : undefined;
1538
2160
  const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
1539
2161
  const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
1540
2162
  const firstAt = bucket[0]?.created_at ?? promptAt;
@@ -1554,7 +2176,9 @@ function turns(db, options) {
1554
2176
  totals,
1555
2177
  drops,
1556
2178
  finish: last.finish ?? undefined,
1557
- tps: tokensPerSecond(produced, 0, window)
2179
+ tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
2180
+ requestTps: tokensPerSecond(produced, 0, window),
2181
+ ttft
1558
2182
  });
1559
2183
  bucket = [];
1560
2184
  }
@@ -1574,273 +2198,36 @@ function turns(db, options) {
1574
2198
  break;
1575
2199
  }
1576
2200
  }
1577
- if (index !== promptIndex) {
1578
- close();
1579
- promptIndex = index;
1580
- promptAt = index >= 0 ? prompts[index] : undefined;
1581
- }
1582
- bucket.push(row);
1583
- }
1584
- close();
1585
- const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
1586
- return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
1587
- }
1588
- let promptCount = Math.max(1, limit + 1);
1589
- for (;; ) {
1590
- const { rows, complete } = read(promptCount);
1591
- if (rows.length >= limit || complete)
1592
- return rows.slice(0, limit);
1593
- const next = promptCount * 2 + 1;
1594
- if (!Number.isFinite(next) || next <= promptCount)
1595
- return rows.slice(0, limit);
1596
- promptCount = next;
1597
- }
1598
- }
1599
- function promptFloor(db, sessionID, count) {
1600
- 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);
1601
- return rows.length === count ? rows[count - 1].created_at : undefined;
1602
- }
1603
- function filterOptions(db) {
1604
- 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 }));
1605
- return { models: pick("model_id"), providers: pick("provider_id") };
1606
- }
1607
-
1608
- // src/recorder.ts
1609
- function createRecorder(db, options) {
1610
- const MAX_TRACKED_SESSIONS = 512;
1611
- const MAX_PENDING = 256;
1612
- const pending = new Map;
1613
- const lastModel = new Map;
1614
- const now = options?.now ?? (() => Date.now());
1615
- const MAX_DEFERRED = 256;
1616
- const deferred = [];
1617
- function isBusy(error) {
1618
- const code = error?.code;
1619
- return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED";
1620
- }
1621
- function enqueue(run) {
1622
- if (deferred.length >= MAX_DEFERRED)
1623
- deferred.shift();
1624
- deferred.push(run);
1625
- }
1626
- function flushDeferred() {
1627
- while (deferred.length > 0) {
1628
- const next = deferred[0];
1629
- try {
1630
- next();
1631
- } catch {
1632
- return;
1633
- }
1634
- deferred.shift();
1635
- }
1636
- }
1637
- function write(run) {
1638
- if (deferred.length > 0) {
1639
- flushDeferred();
1640
- if (deferred.length > 0) {
1641
- enqueue(run);
1642
- return;
1643
- }
1644
- }
1645
- try {
1646
- run();
1647
- } catch (error) {
1648
- if (isBusy(error))
1649
- enqueue(run);
1650
- }
1651
- }
1652
- function remember(map, key, value, limit) {
1653
- map.delete(key);
1654
- map.set(key, value);
1655
- while (map.size > limit) {
1656
- const oldest = map.keys().next();
1657
- if (oldest.done === true)
1658
- break;
1659
- map.delete(oldest.value);
1660
- }
1661
- }
1662
- function forget(sessionID) {
1663
- lastModel.delete(sessionID);
1664
- for (const [messageID, step] of pending) {
1665
- if (step.sessionID === sessionID)
1666
- pending.delete(messageID);
1667
- }
1668
- }
1669
- function recordPendingStep(messageID, data, finish, at) {
1670
- const sessionID = data.sessionID;
1671
- if (typeof sessionID !== "string")
1672
- return;
1673
- const info = pending.get(messageID);
1674
- pending.delete(messageID);
1675
- const model = info?.model ?? lastModel.get(sessionID);
1676
- const charged = data.cost;
1677
- const estimate = charged !== undefined && charged > 0 ? undefined : options?.price?.({ providerID: model?.providerID, modelID: model?.id }, {
1678
- input: data.tokens?.input,
1679
- output: data.tokens?.output,
1680
- reasoning: data.tokens?.reasoning,
1681
- cacheRead: data.tokens?.cache?.read,
1682
- cacheWrite: data.tokens?.cache?.write
1683
- });
1684
- write(() => recordStep(db, {
1685
- messageID,
1686
- sessionID,
1687
- providerID: model?.providerID,
1688
- modelID: model?.id,
1689
- variant: model?.variant,
1690
- input: data.tokens?.input,
1691
- output: data.tokens?.output,
1692
- reasoning: data.tokens?.reasoning,
1693
- cacheRead: data.tokens?.cache?.read,
1694
- cacheWrite: data.tokens?.cache?.write,
1695
- cost: data.cost,
1696
- listCost: estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined,
1697
- createdAt: info?.started,
1698
- streamedAt: info?.streamed,
1699
- completedAt: at,
1700
- finish,
1701
- recordedAt: now()
1702
- }));
1703
- }
1704
- function handleEvent(event) {
1705
- if (deferred.length > 0)
1706
- flushDeferred();
1707
- const data = event.data ?? {};
1708
- const at = typeof event.created === "number" ? event.created : now();
1709
- const sessionID = typeof data.sessionID === "string" ? data.sessionID : undefined;
1710
- switch (event.type) {
1711
- case "session.created": {
1712
- if (sessionID === undefined)
1713
- return;
1714
- write(() => upsertSession(db, {
1715
- sessionID,
1716
- parentID: data.parentID,
1717
- directory: data.location?.directory,
1718
- title: data.title,
1719
- startedAt: at,
1720
- updatedAt: at
1721
- }));
1722
- if (data.model !== undefined)
1723
- remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
1724
- return;
1725
- }
1726
- case "session.deleted": {
1727
- if (sessionID !== undefined)
1728
- forget(sessionID);
1729
- return;
1730
- }
1731
- case "session.renamed": {
1732
- if (sessionID === undefined)
1733
- return;
1734
- write(() => upsertSession(db, { sessionID, title: data.title, updatedAt: at }));
1735
- return;
1736
- }
1737
- case "session.moved": {
1738
- if (sessionID === undefined)
1739
- return;
1740
- write(() => upsertSession(db, { sessionID, directory: data.location?.directory, updatedAt: at }));
1741
- return;
1742
- }
1743
- case "session.inbox.enqueued": {
1744
- if (sessionID === undefined)
1745
- return;
1746
- if (data.item?.type !== "user" && data.item?.type !== "synthetic")
1747
- return;
1748
- const inboxID = data.inboxID;
1749
- if (typeof inboxID !== "string")
1750
- return;
1751
- write(() => recordPrompt(db, { sessionID, messageID: inboxID, createdAt: at }));
1752
- return;
1753
- }
1754
- case "session.model.selected": {
1755
- if (sessionID !== undefined && data.model !== undefined)
1756
- remember(lastModel, sessionID, data.model, MAX_TRACKED_SESSIONS);
1757
- return;
1758
- }
1759
- case "session.step.started": {
1760
- if (sessionID === undefined || typeof data.assistantMessageID !== "string")
1761
- return;
1762
- remember(pending, data.assistantMessageID, {
1763
- messageID: data.assistantMessageID,
1764
- sessionID,
1765
- started: typeof data.started === "number" ? data.started : undefined,
1766
- streamed: undefined,
1767
- model: data.model
1768
- }, MAX_PENDING);
1769
- return;
1770
- }
1771
- case "session.step.streamed": {
1772
- if (typeof data.assistantMessageID !== "string")
1773
- return;
1774
- const info = pending.get(data.assistantMessageID);
1775
- if (info !== undefined)
1776
- info.streamed = at;
1777
- return;
1778
- }
1779
- case "session.step.ended": {
1780
- if (typeof data.assistantMessageID !== "string")
1781
- return;
1782
- recordPendingStep(data.assistantMessageID, data, data.finish ?? "unknown", at);
1783
- return;
1784
- }
1785
- case "session.step.failed": {
1786
- if (typeof data.assistantMessageID !== "string")
1787
- return;
1788
- recordPendingStep(data.assistantMessageID, data, data.finish ?? "error", at);
1789
- return;
1790
- }
1791
- case "session.usage.recorded": {
1792
- if (sessionID === undefined)
1793
- return;
1794
- const source = typeof data.source === "string" ? data.source : undefined;
1795
- if (source === undefined || source === "generate")
1796
- return;
1797
- const id = typeof event.id === "string" && event.id !== "" ? event.id : `${sessionID}:${source}:${at}:${data.cost ?? 0}`;
1798
- write(() => recordUsage(db, {
1799
- id,
1800
- sessionID,
1801
- source,
1802
- at,
1803
- cost: data.cost,
1804
- input: data.tokens?.input,
1805
- output: data.tokens?.output,
1806
- reasoning: data.tokens?.reasoning,
1807
- cacheRead: data.tokens?.cache?.read,
1808
- cacheWrite: data.tokens?.cache?.write
1809
- }));
1810
- return;
1811
- }
1812
- case "session.compaction.ended": {
1813
- if (sessionID === undefined)
1814
- return;
1815
- const messageID = typeof event.id === "string" && event.id !== "" ? event.id : `compaction:${sessionID}:${at}`;
1816
- write(() => recordEvent(db, {
1817
- sessionID,
1818
- kind: COMPACTION_KIND,
1819
- messageID,
1820
- at,
1821
- data: { reason: data.reason, model: data.model, tokens: data.tokens, cost: data.cost }
1822
- }));
1823
- return;
1824
- }
1825
- default:
1826
- return;
2201
+ if (index !== promptIndex) {
2202
+ close();
2203
+ promptIndex = index;
2204
+ promptAt = index >= 0 ? prompts[index] : undefined;
2205
+ }
2206
+ bucket.push(row);
1827
2207
  }
2208
+ close();
2209
+ const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
2210
+ return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
1828
2211
  }
1829
- function pendingFor(sessionID) {
1830
- let found;
1831
- for (const item of pending.values()) {
1832
- if (item.sessionID !== sessionID)
1833
- continue;
1834
- if (found === undefined || (item.started ?? 0) >= (found.started ?? 0))
1835
- found = item;
1836
- }
1837
- return found;
2212
+ let promptCount = Math.max(1, limit + 1);
2213
+ for (;; ) {
2214
+ const { rows, complete } = read(promptCount);
2215
+ if (rows.length >= limit || complete)
2216
+ return rows.slice(0, limit);
2217
+ const next = promptCount * 2 + 1;
2218
+ if (!Number.isFinite(next) || next <= promptCount)
2219
+ return rows.slice(0, limit);
2220
+ promptCount = next;
1838
2221
  }
1839
- return { handleEvent, pendingFor };
1840
2222
  }
1841
-
1842
- // src/service.ts
1843
- import { basename } from "path";
2223
+ function promptFloor(db, sessionID, count) {
2224
+ 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);
2225
+ return rows.length === count ? rows[count - 1].created_at : undefined;
2226
+ }
2227
+ function filterOptions(db) {
2228
+ 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 }));
2229
+ return { models: pick("model_id"), providers: pick("provider_id") };
2230
+ }
1844
2231
 
1845
2232
  // src/stats/aggregates.ts
1846
2233
  var STEP_AT = "COALESCE(created_at, recorded_at)";
@@ -1869,8 +2256,9 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
1869
2256
  COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1870
2257
  COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1871
2258
  COALESCE(list_cost, 0) AS listCost,
1872
- created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1873
- var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
2259
+ created_at AS createdAt, first_token_at AS firstTokenAt, streamed_at AS streamedAt,
2260
+ completed_at AS completedAt, ${STEP_AT} AS at`;
2261
+ var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "firstTokenAt", "streamedAt", "completedAt"];
1874
2262
  var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1875
2263
  function stepRows(db, options) {
1876
2264
  const filter = buildWhere(options?.range, options?.filters);
@@ -1949,6 +2337,7 @@ function coverageOf(db, options) {
1949
2337
  COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1950
2338
  COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1951
2339
  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,
2340
+ COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at AND first_token_at IS NULL THEN 1 ELSE 0 END), 0) AS missingFirstToken,
1952
2341
  MIN(${STEP_AT}) AS firstAt,
1953
2342
  MAX(${STEP_AT}) AS lastAt
1954
2343
  FROM steps ${filter.where}`).get(...filter.params);
@@ -1959,6 +2348,7 @@ function coverageOf(db, options) {
1959
2348
  missingModel: row.missingModel,
1960
2349
  unsettled: row.unsettled,
1961
2350
  missingTps: row.missingTps,
2351
+ missingFirstToken: row.missingFirstToken,
1962
2352
  firstAt: row.firstAt ?? undefined,
1963
2353
  lastAt: row.lastAt ?? undefined
1964
2354
  };
@@ -1971,7 +2361,14 @@ function groupedRows(db, options) {
1971
2361
  function timingOf(step) {
1972
2362
  const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
1973
2363
  const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
1974
- return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
2364
+ const ttft = step.createdAt !== undefined && step.firstTokenAt !== undefined ? Math.max(0, step.firstTokenAt - step.createdAt) : undefined;
2365
+ return {
2366
+ wall,
2367
+ stream,
2368
+ ttft,
2369
+ tps: tokensPerSecond(step.output + step.reasoning, step.firstTokenAt ?? step.createdAt, step.streamedAt),
2370
+ requestTps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt)
2371
+ };
1975
2372
  }
1976
2373
  function timingRows(db, options) {
1977
2374
  return groupedRows(db, options);
@@ -1979,17 +2376,29 @@ function timingRows(db, options) {
1979
2376
  function latencyOf(rows) {
1980
2377
  const wall = [];
1981
2378
  const stream = [];
2379
+ const ttft = [];
1982
2380
  const tps = [];
2381
+ const requestTps = [];
1983
2382
  for (const step of rows) {
1984
2383
  const timing = timingOf(step);
1985
2384
  if (timing.wall !== undefined)
1986
2385
  wall.push(timing.wall);
1987
2386
  if (timing.stream !== undefined)
1988
2387
  stream.push(timing.stream);
2388
+ if (timing.ttft !== undefined)
2389
+ ttft.push(timing.ttft);
1989
2390
  if (timing.tps !== undefined)
1990
2391
  tps.push(timing.tps);
2392
+ if (timing.requestTps !== undefined)
2393
+ requestTps.push(timing.requestTps);
1991
2394
  }
1992
- return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
2395
+ return {
2396
+ wall: latencyStats(wall),
2397
+ stream: latencyStats(stream),
2398
+ ttft: latencyStats(ttft),
2399
+ tps: latencyStats(tps),
2400
+ requestTps: latencyStats(requestTps)
2401
+ };
1993
2402
  }
1994
2403
  function latencyGroupsOf(rows, by) {
1995
2404
  const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
@@ -1997,25 +2406,33 @@ function latencyGroupsOf(rows, by) {
1997
2406
  for (const [group, steps] of groupBy(rows, key)) {
1998
2407
  const wall = [];
1999
2408
  const stream = [];
2409
+ const ttft = [];
2000
2410
  const tps = [];
2411
+ const requestTps = [];
2001
2412
  for (const step of steps) {
2002
2413
  const timing = timingOf(step);
2003
2414
  if (timing.wall !== undefined)
2004
2415
  wall.push(timing.wall);
2005
2416
  if (timing.stream !== undefined)
2006
2417
  stream.push(timing.stream);
2418
+ if (timing.ttft !== undefined)
2419
+ ttft.push(timing.ttft);
2007
2420
  if (timing.tps !== undefined)
2008
2421
  tps.push(timing.tps);
2422
+ if (timing.requestTps !== undefined)
2423
+ requestTps.push(timing.requestTps);
2009
2424
  }
2010
- const [modelID, variant] = group.split("#");
2425
+ const { modelID, variant } = splitModelKey(group);
2011
2426
  groups.push({
2012
2427
  key: group,
2013
- label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
2428
+ label: by === "model" ? variant === undefined ? modelID : `${modelID} ${variant}` : group,
2014
2429
  count: steps.length,
2015
2430
  usage: usageOf(steps),
2016
2431
  wall: latencyStats(wall),
2017
2432
  stream: latencyStats(stream),
2018
- tps: latencyStats(tps)
2433
+ ttft: latencyStats(ttft),
2434
+ tps: latencyStats(tps),
2435
+ requestTps: latencyStats(requestTps)
2019
2436
  });
2020
2437
  }
2021
2438
  return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
@@ -2098,7 +2515,10 @@ var GAP_BUCKETS = [
2098
2515
  ["<1m", 0, 60000],
2099
2516
  ["1\u20135m", 60000, 5 * 60000],
2100
2517
  ["5\u201315m", 5 * 60000, 15 * 60000],
2101
- ["15\u201360m", 15 * 60000, 60 * 60000],
2518
+ ["15\u201320m", 15 * 60000, 20 * 60000],
2519
+ ["20\u201330m", 20 * 60000, 30 * 60000],
2520
+ ["30\u201345m", 30 * 60000, 45 * 60000],
2521
+ ["45\u201360m", 45 * 60000, 60 * 60000],
2102
2522
  ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
2103
2523
  [">6h", 6 * 60 * 60000, undefined]
2104
2524
  ];
@@ -2192,21 +2612,21 @@ function cacheDropsOf(db, rows, options) {
2192
2612
  }
2193
2613
  if (losses.length === 0)
2194
2614
  return [];
2195
- const compactions = new Map;
2615
+ const times = new Map;
2196
2616
  const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
2197
- const events = db.query(`SELECT session_id, at FROM events
2198
- WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
2617
+ const timeline = db.query(`SELECT session_id, at FROM compactions
2618
+ WHERE at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
2199
2619
  ORDER BY at`).all(...sessionIDs);
2200
- for (const event of events) {
2201
- const list = compactions.get(event.session_id);
2620
+ for (const row of timeline) {
2621
+ const list = times.get(row.session_id);
2202
2622
  if (list !== undefined)
2203
- list.push(event.at);
2623
+ list.push(row.at);
2204
2624
  else
2205
- compactions.set(event.session_id, [event.at]);
2625
+ times.set(row.session_id, [row.at]);
2206
2626
  }
2207
2627
  return losses.map((loss) => {
2208
2628
  const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
2209
- const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
2629
+ const compacted = (times.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
2210
2630
  const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
2211
2631
  return {
2212
2632
  sessionID: loss.current.sessionID,
@@ -2225,14 +2645,34 @@ function cacheDropsOf(db, rows, options) {
2225
2645
  function groupValues(steps) {
2226
2646
  const wall = [];
2227
2647
  const tps = [];
2648
+ const requestTps = [];
2649
+ const ttft = [];
2228
2650
  for (const step of steps) {
2229
2651
  const timing = timingOf(step);
2230
2652
  if (timing.wall !== undefined)
2231
2653
  wall.push(timing.wall);
2232
2654
  if (timing.tps !== undefined)
2233
2655
  tps.push(timing.tps);
2656
+ if (timing.requestTps !== undefined)
2657
+ requestTps.push(timing.requestTps);
2658
+ if (timing.ttft !== undefined)
2659
+ ttft.push(timing.ttft);
2234
2660
  }
2235
- return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
2661
+ return {
2662
+ cache: cacheStatsOfSteps(steps),
2663
+ tps: latencyStats(tps).p50,
2664
+ requestTps: latencyStats(requestTps).p50,
2665
+ ttft: latencyStats(ttft).p50,
2666
+ wall: latencyStats(wall).p50
2667
+ };
2668
+ }
2669
+ var MODEL_LIST_SEPARATOR = "\x00";
2670
+ function splitModelKey(key) {
2671
+ const separator = key.indexOf(MODEL_KEY_SEPARATOR);
2672
+ if (separator === -1)
2673
+ return { modelID: key, variant: undefined };
2674
+ const variant = key.slice(separator + 1);
2675
+ return { modelID: key.slice(0, separator), variant: variant === "" ? undefined : variant };
2236
2676
  }
2237
2677
  function providerOf(steps, models) {
2238
2678
  const values = groupValues(steps);
@@ -2246,17 +2686,22 @@ function providerOf(steps, models) {
2246
2686
  }
2247
2687
  return {
2248
2688
  provider: steps[0].providerID,
2249
- models: models.split("\x00"),
2689
+ models: models.split(MODEL_LIST_SEPARATOR),
2250
2690
  share: 0,
2251
2691
  usage: usageOf(steps),
2252
2692
  cache: values.cache,
2253
2693
  tps: values.tps,
2694
+ requestTps: values.requestTps,
2695
+ ttft: values.ttft,
2254
2696
  wall: values.wall,
2255
2697
  firstAt,
2256
2698
  lastAt
2257
2699
  };
2258
2700
  }
2259
- 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");
2701
+ var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => {
2702
+ const { modelID, variant } = splitModelKey(key);
2703
+ return modelLabel(modelID, variant);
2704
+ }).join(MODEL_LIST_SEPARATOR);
2260
2705
  function providerSummaryOf(rows) {
2261
2706
  const out = [];
2262
2707
  for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
@@ -2269,7 +2714,7 @@ function providerBreakdownOf(rows) {
2269
2714
  const out = [];
2270
2715
  for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
2271
2716
  for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
2272
- const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
2717
+ const { modelID, variant } = splitModelKey(model);
2273
2718
  out.push({
2274
2719
  ...providerOf(steps, modelNames(steps)),
2275
2720
  modelID,
@@ -2475,8 +2920,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
2475
2920
  var GRANULARITIES = ["day", "week", "month"];
2476
2921
  var SORT_KEYS = {
2477
2922
  models: ["steps", "cached", "hit", "out", "cost"],
2478
- providers: ["steps", "cached", "hit", "cost", "share", "tps"],
2479
- latency: ["n", "tps", "wall"],
2923
+ providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
2924
+ latency: ["n", "tps", "ttft", "wall"],
2480
2925
  sessions: ["last", "steps", "cached", "cost"],
2481
2926
  turns: ["time", "cost", "tokens"]
2482
2927
  };
@@ -2574,10 +3019,10 @@ function formatTps(value) {
2574
3019
  return "\u2013";
2575
3020
  return `${value.toFixed(1)}/s`;
2576
3021
  }
2577
- function formatTpsCompact(value) {
3022
+ function formatRateValue(value) {
2578
3023
  if (value === undefined || !Number.isFinite(value) || value < 0)
2579
3024
  return "\u2013";
2580
- return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
3025
+ return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
2581
3026
  }
2582
3027
  function formatGap(value) {
2583
3028
  if (value === undefined || !Number.isFinite(value))
@@ -2609,15 +3054,6 @@ function truncateMiddle(value, width) {
2609
3054
  const tail = width - 1 - head;
2610
3055
  return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
2611
3056
  }
2612
- function tableWidths(width, layouts) {
2613
- for (const layout of layouts) {
2614
- const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
2615
- if (total <= width)
2616
- return [...layout];
2617
- }
2618
- const last = layouts[layouts.length - 1];
2619
- return last === undefined ? [] : [...last];
2620
- }
2621
3057
  function modelCell(modelID, variant, width) {
2622
3058
  return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
2623
3059
  }
@@ -2636,6 +3072,47 @@ function formatTableRow(cells, widths, aligns) {
2636
3072
  }
2637
3073
  return parts.join(" ");
2638
3074
  }
3075
+ function fitTableColumns(columns, width) {
3076
+ const chosen = new Set;
3077
+ for (let index = 0;index < columns.length; index += 1) {
3078
+ if (columns[index].priority === undefined)
3079
+ chosen.add(index);
3080
+ }
3081
+ if (chosen.size === 0)
3082
+ return [];
3083
+ const total = () => {
3084
+ let sum = chosen.size - 1;
3085
+ for (const index of chosen)
3086
+ sum += columns[index].width;
3087
+ return sum;
3088
+ };
3089
+ const optional = columns.map((column, index) => ({ column, index })).filter((entry) => entry.column.priority !== undefined).sort((left, right) => left.column.priority - right.column.priority || left.index - right.index);
3090
+ for (const { column, index } of optional) {
3091
+ if (total() + column.width + 1 + (column.reserve ?? 0) <= width)
3092
+ chosen.add(index);
3093
+ }
3094
+ while (chosen.size > 1 && total() > width)
3095
+ chosen.delete(Math.max(...chosen));
3096
+ const widths = new Map;
3097
+ let room = width - total();
3098
+ for (let index = 0;index < columns.length && room > 0; index += 1) {
3099
+ if (!chosen.has(index))
3100
+ continue;
3101
+ const column = columns[index];
3102
+ const grow = Math.min(room, (column.max ?? column.width) - column.width);
3103
+ if (grow <= 0)
3104
+ continue;
3105
+ widths.set(index, column.width + grow);
3106
+ room -= grow;
3107
+ }
3108
+ return [...chosen].sort((left, right) => left - right).map((index) => ({ index, width: widths.get(index) ?? columns[index].width }));
3109
+ }
3110
+ function fitTable(columns, width) {
3111
+ return fitTableColumns(columns, width).map(({ index, width: fitted }) => {
3112
+ const column = columns[index];
3113
+ return { index, header: column.header, width: fitted, align: column.align ?? "left", cell: column.cell };
3114
+ });
3115
+ }
2639
3116
  function count(n, singular, plural = `${singular}s`) {
2640
3117
  return `${formatCount(n)} ${n === 1 ? singular : plural}`;
2641
3118
  }
@@ -2643,21 +3120,30 @@ function kvGrid(pairs, width) {
2643
3120
  const lines = [];
2644
3121
  const label = 11;
2645
3122
  const column = Math.floor(width / 2);
3123
+ const pairLines = (pair) => {
3124
+ const text = `${padCell(pair[0], label)}${pair[1]}`;
3125
+ if (text.length <= width)
3126
+ return [text];
3127
+ return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width));
3128
+ };
2646
3129
  for (let index = 0;index < pairs.length; index += 2) {
2647
3130
  const left = pairs[index];
2648
3131
  const right = pairs[index + 1];
2649
- const leftText = `${padCell(left[0], label)}${left[1]}`;
2650
3132
  if (right === undefined) {
2651
- lines.push({ text: leftText, tone: "base" });
3133
+ for (const text of pairLines(left))
3134
+ lines.push({ text, tone: "base" });
2652
3135
  continue;
2653
3136
  }
3137
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
2654
3138
  const rightText = `${padCell(right[0], label)}${right[1]}`;
2655
3139
  const gap = Math.max(2, column - leftText.length);
2656
3140
  if (leftText.length + gap + rightText.length <= width) {
2657
3141
  lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
2658
3142
  } else {
2659
- lines.push({ text: leftText, tone: "base" });
2660
- lines.push({ text: rightText, tone: "base" });
3143
+ for (const text of pairLines(left))
3144
+ lines.push({ text, tone: "base" });
3145
+ for (const text of pairLines(right))
3146
+ lines.push({ text, tone: "base" });
2661
3147
  }
2662
3148
  }
2663
3149
  return lines;
@@ -2767,7 +3253,11 @@ function helpLines(width) {
2767
3253
  { text: " \u2248 list-price estimate for steps the host reported as $0;" },
2768
3254
  { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
2769
3255
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
2770
- { text: " tps out / streaming seconds, shown as p50" },
3256
+ { text: " ttft request \u2192 first streamed token" },
3257
+ { text: " tps output+reasoning / first token \u2192 last chunk (OpenCode)" },
3258
+ { text: " rtps output+reasoning / request \u2192 last chunk (includes TTFT)" },
3259
+ { text: " turn 200 tps \xB7 2.1s ttft \xB7 cost" },
3260
+ { text: " session 200 tps \xB7 167 rtps \xB7 ttft p50 \xB7 cost" },
2771
3261
  { text: " switches how often a step's model or provider differs from the step" },
2772
3262
  { text: " before it in the same session (the models view's detail), with" },
2773
3263
  { text: " the cache a provider switch cost" },
@@ -2896,26 +3386,32 @@ function usagePairs(usage, estimates = true) {
2896
3386
  ];
2897
3387
  if (buckets.reasoning > 0)
2898
3388
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
3389
+ if ("tps" in usage && usage.tps !== undefined)
3390
+ pairs.push(["tps", formatTps(usage.tps)]);
3391
+ if ("requestTps" in usage && usage.requestTps !== undefined)
3392
+ pairs.push(["rtps", formatTps(usage.requestTps)]);
3393
+ if ("ttft" in usage && usage.ttft !== undefined)
3394
+ pairs.push(["ttft p50", formatMs(usage.ttft)]);
2899
3395
  pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
2900
3396
  const other = usage.otherCost ?? 0;
2901
3397
  if (other > 0)
2902
3398
  pairs.push(["other", `${formatCost(other)} comp/title`]);
2903
- if ("tps" in usage && usage.tps !== undefined)
2904
- pairs.push(["tps", formatTps(usage.tps)]);
2905
3399
  return pairs;
2906
3400
  }
2907
3401
  function overviewLines(data, width) {
2908
3402
  const lines = [];
2909
3403
  const estimates = data.estimates !== false;
2910
3404
  lines.push({
2911
- text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
3405
+ text: truncate(`${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`, width),
2912
3406
  tone: "muted"
2913
3407
  });
2914
3408
  lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
2915
3409
  if (data.activity !== undefined && data.activity.length > 1) {
2916
- const series = reduceSeries(data.activity);
3410
+ const suffix = ` ${count(data.activity.length, "bucket")}`;
3411
+ const bars = Math.max(4, width - "activity ".length - suffix.length);
3412
+ const series = reduceSeries(data.activity, bars);
2917
3413
  lines.push({ text: "", tone: "muted" });
2918
- lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
3414
+ lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: "muted" });
2919
3415
  }
2920
3416
  if (data.session !== undefined) {
2921
3417
  lines.push({ text: "", tone: "muted" });
@@ -2926,7 +3422,7 @@ function overviewLines(data, width) {
2926
3422
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
2927
3423
  const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
2928
3424
  lines.push({
2929
- text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
3425
+ text: truncate(` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`, width),
2930
3426
  tone: "muted"
2931
3427
  });
2932
3428
  }
@@ -2952,71 +3448,40 @@ function coveragePairs(coverage) {
2952
3448
  ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
2953
3449
  ["providers", formatCount(coverage.providers)],
2954
3450
  ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
3451
+ ["no ttft", share(coverage.missingFirstToken)],
2955
3452
  [
2956
3453
  "window",
2957
3454
  `${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
2958
3455
  ]
2959
3456
  ];
2960
3457
  }
2961
- function modelColumns(width) {
2962
- const layouts = [
2963
- { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
2964
- { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
2965
- { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
2966
- { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
2967
- { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
2968
- ];
2969
- for (const layout of layouts) {
2970
- const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
2971
- if (total <= width)
2972
- return layout;
2973
- }
2974
- return layouts[layouts.length - 1];
2975
- }
2976
3458
  function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2977
- const columns = modelColumns(width);
2978
- const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
2979
- const aligns = ["left", "right", "right", "right"];
2980
- const header = ["model", "steps", "prompt", "cached"];
2981
- if (columns.hit > 0) {
2982
- widths.push(columns.hit);
2983
- aligns.push("right");
2984
- header.push("hit");
2985
- }
2986
- widths.push(columns.out);
2987
- aligns.push("right");
2988
- header.push("out");
2989
- if (columns.cost > 0) {
2990
- widths.push(columns.cost);
2991
- aligns.push("right");
2992
- header.push("cost");
2993
- }
2994
- if (columns.spread > 0) {
2995
- widths.push(columns.spread);
2996
- aligns.push("left");
2997
- header.push("providers");
2998
- }
2999
- const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
3459
+ let modelWidth = 14;
3460
+ const columns = fitTable([
3461
+ { header: "model", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },
3462
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
3463
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => row.prompt },
3464
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => row.cached },
3465
+ { header: "hit", width: 6, max: 7, priority: 2, reserve: 10, align: "right", cell: (row) => row.hit },
3466
+ { header: "out", width: 7, max: 9, priority: 3, reserve: 10, align: "right", cell: (row) => row.output },
3467
+ { header: "cost", width: 8, max: 9, priority: 1, align: "right", cell: (row) => row.cost },
3468
+ { header: "providers", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers }
3469
+ ], width);
3470
+ modelWidth = columns.find((column) => column.index === 0)?.width ?? 0;
3471
+ if (columns.length === 0)
3472
+ return [{ text: truncate("no room for a table at this width", width), tone: "muted" }];
3473
+ const lines = [
3474
+ {
3475
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
3476
+ tone: HEADER_TONE
3477
+ }
3478
+ ];
3000
3479
  for (const model of rows.slice(0, limit)) {
3001
3480
  const key = modelKey(model.modelID, model.variant);
3002
- const name = modelCell(model.modelID, model.variant, columns.model);
3003
3481
  const buckets = usageBuckets(model.totals);
3004
3482
  const providers = unique(model.providers.map((provider) => provider.providerID));
3005
3483
  const cache = extras?.cache?.get(key);
3006
3484
  const switches = extras?.switches?.get(key);
3007
- const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
3008
- if (columns.hit > 0)
3009
- cells.push(formatPercent(cache?.hit ?? buckets.hit));
3010
- cells.push(formatTokens(buckets.output));
3011
- if (columns.cost > 0)
3012
- cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
3013
- if (columns.spread > 0)
3014
- cells.push(providers.join(", "));
3015
- lines.push({
3016
- text: formatTableRow(cells, widths, aligns),
3017
- tone: "base",
3018
- row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
3019
- });
3020
3485
  const details = [];
3021
3486
  if (cache !== undefined)
3022
3487
  details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
@@ -3026,62 +3491,77 @@ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
3026
3491
  if (switches.cacheLost > 0)
3027
3492
  details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
3028
3493
  }
3029
- if (details.length > 0) {
3030
- lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
3494
+ const view = {
3495
+ modelID: model.modelID,
3496
+ variant: model.variant,
3497
+ steps: formatCount(buckets.steps),
3498
+ prompt: formatTokens(buckets.prompt),
3499
+ cached: formatTokens(buckets.cached),
3500
+ hit: formatPercent(cache?.hit ?? buckets.hit),
3501
+ output: formatTokens(buckets.output),
3502
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),
3503
+ providers: providers.join(", "),
3504
+ detail: details.join(" \xB7 ")
3505
+ };
3506
+ lines.push({
3507
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
3508
+ tone: "base",
3509
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
3510
+ });
3511
+ if (view.detail !== "") {
3512
+ lines.push({ text: truncate(`${" ".repeat(modelWidth + 1)}${view.detail}`, width), tone: "muted" });
3031
3513
  }
3032
3514
  }
3033
3515
  if (rows.length > limit)
3034
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
3516
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, width), tone: "muted" });
3035
3517
  if (rows.length === 0)
3036
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
3518
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
3037
3519
  return lines;
3038
3520
  }
3039
3521
  function unique(values) {
3040
3522
  return [...new Set(values)];
3041
3523
  }
3042
- var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
3043
- function fitColumns(columns, width) {
3044
- const chosen = [...columns];
3045
- while (chosen.length > 1 && tableWidth(chosen) > width) {
3046
- const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
3047
- if (optional === -1)
3048
- break;
3049
- chosen.splice(chosen.length - 1 - optional, 1);
3050
- }
3051
- return chosen;
3052
- }
3053
3524
  function renderTable(rows, columns, width, options) {
3054
- const chosen = fitColumns(columns, width);
3525
+ const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {
3526
+ const column = columns[index];
3527
+ const align = column.align ?? "left";
3528
+ return { ...column, width: fitted, align };
3529
+ });
3530
+ if (chosen.length === 0)
3531
+ return [{ text: truncate(options.empty, width), tone: "muted" }];
3055
3532
  const widths = chosen.map((column) => column.width);
3056
- const aligns = chosen.map((column) => column.align ?? "left");
3057
- const alignsTyped = aligns;
3058
- const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
3533
+ const aligns = chosen.map((column) => column.align);
3534
+ const lines = [
3535
+ { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE }
3536
+ ];
3059
3537
  if (rows.length === 0)
3060
- lines.push({ text: options.empty, tone: "muted" });
3538
+ lines.push({ text: truncate(options.empty, width), tone: "muted" });
3061
3539
  for (const row of rows.slice(0, options.limit)) {
3062
3540
  const identity = options.row?.(row);
3063
3541
  lines.push({
3064
- text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
3542
+ text: formatTableRow(chosen.map((column) => column.cell(row, column.width)), widths, aligns),
3065
3543
  tone: options.tone?.(row) ?? "base",
3066
3544
  ...identity === undefined ? {} : { row: identity }
3067
3545
  });
3068
3546
  }
3069
- if (rows.length > options.limit)
3070
- lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
3547
+ if (rows.length > options.limit) {
3548
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - options.limit, "more row")}`, width), tone: "muted" });
3549
+ }
3071
3550
  return lines;
3072
3551
  }
3073
3552
  function providerSummaryLines(rows, width, limit = 40, estimates = true) {
3074
3553
  const lines = renderTable(rows, [
3075
- { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
3076
- { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
3554
+ { header: "provider", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
3555
+ { header: "models", width: 6, align: "right", priority: 4, cell: (row) => formatCount(row.models.length) },
3077
3556
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
3078
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
3079
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
3080
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
3081
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
3082
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
3083
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
3084
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3557
+ { header: "share", width: 6, align: "right", priority: 3, cell: (row) => formatPercent(row.share, 0) },
3558
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
3559
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
3560
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
3561
+ { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
3562
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 6, cell: (row) => formatMs(row.ttft) },
3563
+ { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
3564
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3085
3565
  ], width, {
3086
3566
  limit,
3087
3567
  empty: "no usage recorded for this range",
@@ -3092,16 +3572,17 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
3092
3572
  }
3093
3573
  function providerLines(rows, width, limit = 40, estimates = true) {
3094
3574
  return renderTable(rows, [
3095
- { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
3096
- { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
3575
+ { header: "model", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },
3576
+ { header: "provider", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
3097
3577
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
3098
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
3099
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
3100
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
3101
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
3102
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
3103
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
3104
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3578
+ { header: "share", width: 6, align: "right", priority: 5, cell: (row) => formatPercent(row.share, 0) },
3579
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },
3580
+ { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
3581
+ { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
3582
+ { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
3583
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 7, cell: (row) => formatMs(row.ttft) },
3584
+ { header: "wall", width: 7, align: "right", priority: 8, cell: (row) => formatMs(row.wall) },
3585
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3105
3586
  ], width, {
3106
3587
  limit,
3107
3588
  empty: "no usage recorded for this range",
@@ -3111,80 +3592,126 @@ function providerLines(rows, width, limit = 40, estimates = true) {
3111
3592
  }
3112
3593
  function cacheLines(data, width) {
3113
3594
  const lines = [];
3595
+ const push = (text, tone = "base") => {
3596
+ lines.push({ text: truncate(text, width), tone });
3597
+ };
3114
3598
  const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
3115
- lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
3599
+ push(`reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, total > 0 ? "warning" : "base");
3116
3600
  for (const reason of ["expired", "compaction", "unknown"]) {
3117
3601
  const group = data.drops.filter((drop) => drop.reason === reason);
3118
3602
  if (group.length === 0)
3119
3603
  continue;
3120
3604
  const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
3121
- lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
3605
+ push(` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, reason === "expired" ? "warning" : "muted");
3122
3606
  }
3123
3607
  if (data.drops.length === 0)
3124
- lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
3608
+ push(" none: prompt cache held through every gap", "muted");
3125
3609
  if (data.models !== undefined && data.models.length > 0) {
3126
3610
  lines.push({ text: "", tone: "muted" });
3127
- lines.push({ text: "reuse by model", tone: HEADER_TONE });
3128
- const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
3129
- lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
3130
- for (const row of data.models.slice(0, 10)) {
3131
- const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
3132
- lines.push({
3133
- 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"]),
3134
- tone: "base",
3135
- row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
3136
- });
3611
+ push("reuse by model", HEADER_TONE);
3612
+ let modelWidth = 12;
3613
+ const reuse = fitTable([
3614
+ { header: "model", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },
3615
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.cache.steps) },
3616
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
3617
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
3618
+ { header: "write", width: 6, max: 8, align: "right", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },
3619
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
3620
+ { header: "hit p50", width: 7, max: 9, align: "right", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) }
3621
+ ], width);
3622
+ modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0;
3623
+ if (reuse.length > 0) {
3624
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
3625
+ for (const row of data.models.slice(0, 10)) {
3626
+ lines.push({
3627
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
3628
+ tone: "base",
3629
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
3630
+ });
3631
+ }
3137
3632
  }
3138
3633
  }
3139
3634
  if (data.gap !== undefined && data.gap.samples > 0) {
3140
3635
  lines.push({ text: "", tone: "muted" });
3141
- lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
3142
- const widths = [9, 8, 9, 9, 10];
3143
- lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
3144
- for (const bucket of data.gap.buckets) {
3145
- if (bucket.samples === 0)
3146
- continue;
3147
- lines.push({
3148
- text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
3149
- tone: bucket.drops > 0 ? "warning" : "base"
3150
- });
3636
+ push("cache survival against idle time", HEADER_TONE);
3637
+ const buckets = data.gap.buckets;
3638
+ const survival = fitTable([
3639
+ { header: "gap", width: 8, max: 12, cell: (bucket) => bucket.label },
3640
+ { header: "pairs", width: 6, align: "right", cell: (bucket) => formatCount(bucket.samples) },
3641
+ { header: "kept", width: 7, align: "right", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },
3642
+ { header: "drops", width: 7, align: "right", cell: (bucket) => formatCount(bucket.drops) },
3643
+ { header: "lost", width: 8, align: "right", cell: (bucket) => formatTokens(bucket.lostTokens) }
3644
+ ], width);
3645
+ if (survival.length > 0) {
3646
+ lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: "muted" });
3647
+ for (const bucket of buckets) {
3648
+ if (bucket.samples === 0)
3649
+ continue;
3650
+ lines.push({
3651
+ text: formatTableRow(survival.map((column) => column.cell(bucket)), survival.map((column) => column.width), survival.map((column) => column.align)),
3652
+ tone: bucket.drops > 0 ? "warning" : "base"
3653
+ });
3654
+ }
3151
3655
  }
3152
3656
  if (data.gap.providers.length > 1) {
3153
3657
  lines.push({ text: "", tone: "muted" });
3154
- lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
3155
- const providerWidths = [26, 8, 9, 9];
3156
- lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
3157
- for (const row of data.gap.providers.slice(0, 8)) {
3158
- lines.push({
3159
- text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
3160
- tone: "base"
3161
- });
3658
+ push("reuse kept, by provider", HEADER_TONE);
3659
+ const providers = data.gap.providers;
3660
+ const reuse = fitTable([
3661
+ { header: "provider", width: 12, max: 30, cell: (row) => row.provider },
3662
+ { header: "pairs", width: 6, align: "right", cell: (row) => formatCount(row.samples) },
3663
+ { header: "kept", width: 7, align: "right", cell: (row) => formatPercent(row.retainedRatio, 0) },
3664
+ { header: "lost", width: 8, align: "right", cell: (row) => formatTokens(row.lostTokens) }
3665
+ ], width);
3666
+ if (reuse.length > 0) {
3667
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
3668
+ for (const row of providers.slice(0, 8)) {
3669
+ lines.push({
3670
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
3671
+ tone: "base"
3672
+ });
3673
+ }
3162
3674
  }
3163
3675
  }
3164
3676
  }
3165
3677
  lines.push({ text: "", tone: "muted" });
3166
- lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
3678
+ push("observed cache TTL bounds", HEADER_TONE);
3167
3679
  if (data.evidence.length === 0) {
3168
- lines.push({ text: " no comparable step pairs yet", tone: "muted" });
3680
+ push(" no comparable step pairs yet", "muted");
3169
3681
  } else {
3170
- const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
3171
- lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
3172
- for (const row of data.evidence.slice(0, 10)) {
3173
- lines.push({
3174
- text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
3175
- tone: "base"
3176
- });
3682
+ const evidence = fitTable([
3683
+ { header: "model", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },
3684
+ { header: "hits up to", width: 10, align: "right", cell: (row) => formatGap(row.maxHitGapMs) },
3685
+ { header: "drops from", width: 10, align: "right", cell: (row) => formatGap(row.minDropGapMs) },
3686
+ { header: "samples", width: 7, align: "right", priority: 1, cell: (row) => formatCount(row.samples) }
3687
+ ], width);
3688
+ if (evidence.length > 0) {
3689
+ lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: "muted" });
3690
+ for (const row of data.evidence.slice(0, 10)) {
3691
+ lines.push({
3692
+ text: formatTableRow(evidence.map((column) => column.cell(row)), evidence.map((column) => column.width), evidence.map((column) => column.align)),
3693
+ tone: "base"
3694
+ });
3695
+ }
3177
3696
  }
3178
3697
  }
3179
3698
  if (data.drops.length > 0) {
3180
3699
  lines.push({ text: "", tone: "muted" });
3181
- lines.push({ text: "recent losses", tone: HEADER_TONE });
3182
- for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
3183
- const when = new Date(drop.at).toLocaleTimeString("en-GB");
3184
- lines.push({
3185
- 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"]),
3186
- tone: drop.reason === "expired" ? "warning" : "base"
3187
- });
3700
+ push("recent losses", HEADER_TONE);
3701
+ const losses = fitTable([
3702
+ { header: "when", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString("en-GB") },
3703
+ { header: "provider/model", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? ""}/${drop.modelID ?? ""}` },
3704
+ { header: "tokens", width: 7, align: "right", cell: (drop) => `\u2212${formatTokens(drop.tokens)}` },
3705
+ { header: "idle", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}` }
3706
+ ], width);
3707
+ if (losses.length > 0) {
3708
+ lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: "muted" });
3709
+ for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {
3710
+ lines.push({
3711
+ text: formatTableRow(losses.map((column) => column.cell(drop)), losses.map((column) => column.width), losses.map((column) => column.align)),
3712
+ tone: drop.reason === "expired" ? "warning" : "base"
3713
+ });
3714
+ }
3188
3715
  }
3189
3716
  }
3190
3717
  return lines;
@@ -3205,110 +3732,183 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true, tot
3205
3732
  }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
3206
3733
  const overall = usageBuckets(totals);
3207
3734
  lines.push({
3208
- text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
3735
+ text: truncate(`${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`, width),
3209
3736
  tone: "muted"
3210
3737
  });
3211
3738
  if (rows.length > 1) {
3212
- lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
3213
- lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
3739
+ const bars = Math.max(4, width - 8);
3740
+ lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: "muted" });
3741
+ lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: "muted" });
3214
3742
  lines.push({
3215
- text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
3743
+ text: truncate(`cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)), bars)}`, width),
3216
3744
  tone: "muted"
3217
3745
  });
3218
3746
  }
3219
- const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
3220
- const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
3221
- const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
3222
- const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
3223
- lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
3747
+ const columns = fitTable([
3748
+ { header: "period", width: 10, max: 24, cell: (row) => row.label },
3749
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
3750
+ { header: "sess", width: 6, align: "right", priority: 5, cell: (row) => row.sessions },
3751
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
3752
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
3753
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
3754
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
3755
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
3756
+ ], width);
3757
+ if (columns.length === 0)
3758
+ return [...lines, { text: truncate("no room for a table at this width", width), tone: "muted" }];
3759
+ const header = formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align));
3760
+ lines.push({ text: header, tone: HEADER_TONE });
3224
3761
  const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
3225
3762
  for (const row of newest) {
3226
3763
  const buckets = usageBuckets(row.usage);
3227
- const cells = [
3228
- row.label,
3229
- formatCount(row.steps),
3230
- ...withSessions ? [formatCount(row.sessions)] : [],
3231
- formatTokens(buckets.prompt),
3232
- formatTokens(buckets.cached),
3233
- formatPercent(buckets.hit, 0),
3234
- formatTokens(buckets.output),
3235
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3236
- ];
3237
- lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
3764
+ const view = {
3765
+ label: row.label,
3766
+ steps: formatCount(row.steps),
3767
+ sessions: formatCount(row.sessions),
3768
+ prompt: formatTokens(buckets.prompt),
3769
+ cached: formatTokens(buckets.cached),
3770
+ hit: formatPercent(buckets.hit, 0),
3771
+ output: formatTokens(buckets.output),
3772
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3773
+ };
3774
+ lines.push({
3775
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
3776
+ tone: "base",
3777
+ row: { kind: "period", value: row.key }
3778
+ });
3238
3779
  }
3239
3780
  lines.push({ text: "", tone: "muted" });
3781
+ const total = {
3782
+ label: "total",
3783
+ steps: formatCount(totals.steps),
3784
+ sessions: formatCount(totalSessions ?? totals.sessions),
3785
+ prompt: formatTokens(overall.prompt),
3786
+ cached: formatTokens(overall.cached),
3787
+ hit: formatPercent(overall.hit, 0),
3788
+ output: formatTokens(overall.output),
3789
+ cost: formatSpend(overall.cost, estimates ? overall.listCost : 0)
3790
+ };
3240
3791
  lines.push({
3241
- text: formatTableRow([
3242
- "total",
3243
- formatCount(totals.steps),
3244
- ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
3245
- formatTokens(overall.prompt),
3246
- formatTokens(overall.cached),
3247
- formatPercent(overall.hit, 0),
3248
- formatTokens(overall.output),
3249
- formatSpend(overall.cost, estimates ? overall.listCost : 0)
3250
- ], widths, aligns),
3792
+ text: formatTableRow(columns.map((column) => column.cell(total)), columns.map((column) => column.width), columns.map((column) => column.align)),
3251
3793
  tone: HEADER_TONE
3252
3794
  });
3253
3795
  if (rows.length === 0)
3254
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
3796
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
3255
3797
  return lines;
3256
3798
  }
3799
+ function latencyMetric(label, values, width) {
3800
+ const prefix = padCell(label, 11);
3801
+ let text = `${prefix}${values[0] ?? "\u2013"}`;
3802
+ for (let index = 1;index < values.length; index += 1) {
3803
+ const next = `${text} \xB7 ${values[index]}`;
3804
+ if (next.length > width)
3805
+ break;
3806
+ text = next;
3807
+ }
3808
+ return text;
3809
+ }
3257
3810
  function latencyLines(report, width, groups, limit = 12, estimates = true) {
3258
3811
  const lines = [];
3812
+ if (width >= 68) {
3813
+ lines.push({
3814
+ 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]),
3815
+ tone: "base"
3816
+ });
3817
+ lines.push({
3818
+ 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]),
3819
+ tone: "base"
3820
+ });
3821
+ lines.push({
3822
+ text: formatTableRow(["ttft", "p50", formatMs(report.ttft.p50), "p90", formatMs(report.ttft.p90), "p99", formatMs(report.ttft.p99)], [10, 4, 9, 4, 9, 4, 9]),
3823
+ tone: "base"
3824
+ });
3825
+ lines.push({
3826
+ text: formatTableRow(["tps", "p50", formatTps(report.tps.p50), "p90", formatTps(report.tps.p90), "p99", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),
3827
+ tone: "base"
3828
+ });
3829
+ lines.push({
3830
+ text: formatTableRow(["rtps", "p50", formatTps(report.requestTps.p50), "p90", formatTps(report.requestTps.p90), "p99", formatTps(report.requestTps.p99)], [10, 4, 9, 4, 9, 4, 9]),
3831
+ tone: "base"
3832
+ });
3833
+ } else {
3834
+ lines.push({
3835
+ text: latencyMetric("wall", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),
3836
+ tone: "base"
3837
+ });
3838
+ lines.push({
3839
+ text: latencyMetric("stream", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),
3840
+ tone: "base"
3841
+ });
3842
+ lines.push({
3843
+ text: latencyMetric("ttft", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),
3844
+ tone: "base"
3845
+ });
3846
+ lines.push({
3847
+ text: latencyMetric("tps", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
3848
+ tone: "base"
3849
+ });
3850
+ lines.push({
3851
+ text: latencyMetric("rtps", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),
3852
+ tone: "base"
3853
+ });
3854
+ }
3855
+ lines.push({ text: "", tone: "muted" });
3259
3856
  lines.push({
3260
- 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]),
3261
- tone: "base"
3262
- });
3263
- lines.push({
3264
- 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]),
3265
- tone: "base"
3266
- });
3267
- lines.push({
3268
- 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]),
3269
- tone: "base"
3857
+ text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
3858
+ tone: "muted"
3270
3859
  });
3271
- lines.push({ text: "", tone: "muted" });
3272
3860
  lines.push({
3273
- text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
3861
+ text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
3274
3862
  tone: "muted"
3275
3863
  });
3276
3864
  if (report.wall.count === 0)
3277
- lines.push({ text: "no completed steps for this range", tone: "muted" });
3865
+ lines.push({ text: truncate("no completed steps for this range", width), tone: "muted" });
3278
3866
  if (groups !== undefined && groups.length > 0) {
3279
3867
  lines.push({ text: "", tone: "muted" });
3280
3868
  lines.push({ text: "by group", tone: HEADER_TONE });
3281
- const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
3282
- const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
3283
- lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
3284
- for (const row of groups.slice(0, limit)) {
3285
- const thin = row.count < 5;
3286
- lines.push({
3287
- text: formatTableRow([
3288
- row.label,
3289
- formatCount(row.count),
3290
- formatMs(row.wall.p50),
3291
- formatMs(row.wall.p90),
3292
- formatMs(row.stream.p50),
3293
- formatTps(row.tps.p50),
3294
- formatTps(row.tps.p90),
3295
- formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
3296
- ], widths, aligns),
3297
- tone: thin ? "muted" : "base",
3298
- row: { kind: "model", value: row.key }
3299
- });
3869
+ const columns = fitTable([
3870
+ { header: "group", width: 8, max: 32, cell: (row) => row.label },
3871
+ { header: "n", width: 4, align: "right", cell: (row) => formatCount(row.count) },
3872
+ { header: "wall p50", width: 8, align: "right", cell: (row) => formatMs(row.wall.p50) },
3873
+ { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
3874
+ { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
3875
+ { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
3876
+ { header: "tps p90", width: 8, max: 9, align: "right", priority: 4, cell: (row) => formatTps(row.tps.p90) },
3877
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatMs(row.ttft.p50) },
3878
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3879
+ ], width);
3880
+ if (columns.length > 0) {
3881
+ lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: "muted" });
3882
+ for (const row of groups.slice(0, limit)) {
3883
+ const thin = row.count < 5;
3884
+ lines.push({
3885
+ text: formatTableRow(columns.map((column) => column.cell(row)), columns.map((column) => column.width), columns.map((column) => column.align)),
3886
+ tone: thin ? "muted" : "base",
3887
+ row: { kind: "model", value: row.key }
3888
+ });
3889
+ }
3300
3890
  }
3301
- lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
3891
+ lines.push({ text: truncate("n < 5 is dimmed: too few samples to compare", width), tone: "muted" });
3302
3892
  }
3303
3893
  return lines;
3304
3894
  }
3305
3895
  function sessionsLines(rows, width, options) {
3306
3896
  const limit = options?.limit ?? 20;
3307
3897
  const estimates = options?.estimates !== false;
3308
- const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
3309
- const aligns = ["left", "right", "right", "right", "right", "right", "right"];
3898
+ const columns = fitTable([
3899
+ { header: "title", width: 10, max: 48, cell: (row) => row.title },
3900
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
3901
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
3902
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
3903
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
3904
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
3905
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
3906
+ ], width);
3310
3907
  const lines = [
3311
- { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
3908
+ {
3909
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
3910
+ tone: HEADER_TONE
3911
+ }
3312
3912
  ];
3313
3913
  const byID = new Map(rows.map((row) => [row.sessionID, row]));
3314
3914
  const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
@@ -3316,18 +3916,18 @@ function sessionsLines(rows, width, options) {
3316
3916
  const orderedAll = [...ordered, ...children];
3317
3917
  for (const row of orderedAll.slice(0, limit)) {
3318
3918
  const child = row.parentID !== undefined && byID.has(row.parentID);
3319
- const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
3320
3919
  const buckets = usageBuckets(row);
3920
+ const view = {
3921
+ title: `${child ? "\u21B3 " : ""}${row.title ?? row.sessionID}`,
3922
+ steps: formatCount(buckets.steps),
3923
+ prompt: formatTokens(buckets.prompt),
3924
+ cached: formatTokens(buckets.cached),
3925
+ hit: formatPercent(buckets.hit, 0),
3926
+ output: formatTokens(buckets.output),
3927
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3928
+ };
3321
3929
  lines.push({
3322
- text: formatTableRow([
3323
- `${child ? "\u21B3 " : ""}${title}`,
3324
- formatCount(buckets.steps),
3325
- formatTokens(buckets.prompt),
3326
- formatTokens(buckets.cached),
3327
- formatPercent(buckets.hit, 0),
3328
- formatTokens(buckets.output),
3329
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3330
- ], widths, aligns),
3930
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
3331
3931
  tone: child ? "muted" : "base",
3332
3932
  row: { kind: "session", value: row.sessionID }
3333
3933
  });
@@ -3342,14 +3942,14 @@ function sessionsLines(rows, width, options) {
3342
3942
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
3343
3943
  lines.push({ text: "", tone: "muted" });
3344
3944
  lines.push({
3345
- 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)}`,
3945
+ text: truncate(`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)}`, width),
3346
3946
  tone: "muted"
3347
3947
  });
3348
3948
  }
3349
3949
  if (rows.length > limit)
3350
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
3950
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, width), tone: "muted" });
3351
3951
  if (rows.length === 0)
3352
- lines.push({ text: "no sessions recorded for this range", tone: "muted" });
3952
+ lines.push({ text: truncate("no sessions recorded for this range", width), tone: "muted" });
3353
3953
  return lines;
3354
3954
  }
3355
3955
  function dbLines(data, width) {
@@ -3357,16 +3957,16 @@ function dbLines(data, width) {
3357
3957
  const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
3358
3958
  lines.push({ text: truncate(data.info.path, width), tone: "base" });
3359
3959
  lines.push({
3360
- text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
3960
+ text: truncate(`${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`, width),
3361
3961
  tone: "muted"
3362
3962
  });
3363
3963
  lines.push({ text: "", tone: "muted" });
3364
3964
  lines.push({ text: "what it holds", tone: HEADER_TONE });
3365
3965
  for (const table of data.info.tables) {
3366
- lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
3966
+ lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? "muted" : "base" });
3367
3967
  }
3368
3968
  lines.push({
3369
- 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")}`,
3969
+ text: truncate(` 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")}`, width),
3370
3970
  tone: "muted"
3371
3971
  });
3372
3972
  lines.push({ text: "", tone: "muted" });
@@ -3382,7 +3982,7 @@ function dbLines(data, width) {
3382
3982
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
3383
3983
  });
3384
3984
  }
3385
- const widths = [10, 13, 10];
3985
+ const widths = [9, 11, 10];
3386
3986
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
3387
3987
  for (const option of data.info.removable) {
3388
3988
  const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
@@ -3402,7 +4002,7 @@ function dbLines(data, width) {
3402
4002
  });
3403
4003
  if (data.busy === true) {
3404
4004
  lines.push({ text: "", tone: "muted" });
3405
- lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
4005
+ lines.push({ text: truncate("the recorder is writing: try the vacuum again in a moment", width), tone: "warning" });
3406
4006
  }
3407
4007
  return lines;
3408
4008
  }
@@ -3426,28 +4026,74 @@ function turnStats(turn) {
3426
4026
  steps: turn.steps
3427
4027
  };
3428
4028
  }
4029
+ function compactTurnLine(stats, width, options) {
4030
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
4031
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
4032
+ const estimates = options?.estimates !== false;
4033
+ const headParts = [];
4034
+ if (fields.clock && stats.endAt !== undefined)
4035
+ headParts.push(formatClock(stats.endAt));
4036
+ if (stats.providerID !== undefined) {
4037
+ let identity = stats.providerID;
4038
+ if (fields.model && stats.modelID !== undefined)
4039
+ identity += `/${stats.modelID}`;
4040
+ if (fields.variant && stats.variant)
4041
+ identity += ` ${stats.variant}`;
4042
+ headParts.push(identity);
4043
+ }
4044
+ let head = headParts.join(" ");
4045
+ const totals = options?.turnTotals === "sum" ? stats.totals : stats.latest;
4046
+ const display = displayTotals(totals);
4047
+ const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined;
4048
+ const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim();
4049
+ const warning = fields.cacheExpiry && stats.cacheExpired ? `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` \xD7${stats.drops.length}` : ""})` : undefined;
4050
+ let suffix = [warning, cost].filter((part) => part !== undefined).join(" \xB7 ");
4051
+ if (suffix !== "" && suffix.length + 3 > width)
4052
+ suffix = cost ?? suffix;
4053
+ head = truncate(head, Math.max(0, width - (suffix === "" ? 0 : suffix.length + 3)));
4054
+ if (!fields.turn || stats.totals.steps === 0)
4055
+ return [head, suffix].filter((part) => part !== "").join(" \xB7 ");
4056
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
4057
+ const volumes = [
4058
+ input,
4059
+ `${labels.cached} ${formatTokens(display.cached)}`,
4060
+ `${labels.output} ${formatTokens(display.output)}`,
4061
+ ...fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []
4062
+ ];
4063
+ let numbers = "";
4064
+ for (const volume of volumes) {
4065
+ const next = numbers === "" ? volume : `${numbers}, ${volume}`;
4066
+ if ([head, next, suffix].filter((part) => part !== "").join(" \xB7 ").length > width)
4067
+ break;
4068
+ numbers = next;
4069
+ }
4070
+ return [head, numbers, suffix].filter((part) => part !== "").join(" \xB7 ");
4071
+ }
3429
4072
  function turnsLines(rows, width, options) {
3430
4073
  const lines = [];
3431
4074
  const warning = rows.filter((turn) => turn.drops.length > 0).length;
3432
4075
  lines.push({
3433
- text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
4076
+ text: truncate(`${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`, width),
3434
4077
  tone: "muted"
3435
4078
  });
3436
4079
  const showSession = options?.sessionTitles !== undefined;
3437
4080
  for (const turn of rows) {
3438
- const line = formatLine(turnStats(turn), {
4081
+ const stats = turnStats(turn);
4082
+ const line = formatLine(stats, {
3439
4083
  ...options,
3440
4084
  fields: { ...options?.fields, session: false }
3441
4085
  });
3442
4086
  const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
4087
+ const available = Math.max(0, width - title.length);
4088
+ const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`;
3443
4089
  lines.push({
3444
- text: truncate(`${title}${line}`, width),
4090
+ text: truncate(text, width),
3445
4091
  tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
3446
4092
  row: { kind: "turn", value: turn.sessionID }
3447
4093
  });
3448
4094
  }
3449
4095
  if (rows.length === 0)
3450
- lines.push({ text: "no finished turns for this range", tone: "muted" });
4096
+ lines.push({ text: truncate("no finished turns for this range", width), tone: "muted" });
3451
4097
  return lines;
3452
4098
  }
3453
4099
  function sessionSummaryLines(usage, budget = 34, estimates = true) {
@@ -3457,7 +4103,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
3457
4103
  const cached = formatTokens(buckets.cached);
3458
4104
  const out = formatTokens(buckets.output);
3459
4105
  const hit = formatPercent(buckets.hit);
3460
- const tps = formatTpsCompact(usage.tps);
4106
+ const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`;
4107
+ const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`;
4108
+ const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`;
3461
4109
  const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
3462
4110
  const first = [
3463
4111
  ` ${steps} steps \xB7 in ${input}`,
@@ -3467,16 +4115,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
3467
4115
  ` cached ${cached} \xB7 out ${out}`,
3468
4116
  ` cached ${cached}`
3469
4117
  ].find((text) => text.length <= budget);
3470
- const last = [
3471
- ` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
3472
- ` hit ${hit} \xB7 ${cost}`,
3473
- ` ${cost}`
4118
+ const rates = [tps, rtps].filter((part) => part !== undefined);
4119
+ const rateLine = [
4120
+ ` hit ${hit}${rates.length > 0 ? ` \xB7 ${rates.join(" \xB7 ")}` : ""}`,
4121
+ ` hit ${hit}${rates[0] !== undefined ? ` \xB7 ${rates[0]}` : ""}`,
4122
+ ` hit ${hit}`
3474
4123
  ].find((text) => text.length <= budget);
4124
+ const tail = [
4125
+ ttft === undefined ? undefined : ` ${ttft} \xB7 ${cost}`,
4126
+ ` ${cost}`
4127
+ ].filter((text) => text !== undefined).find((text) => text.length <= budget);
3475
4128
  return [
3476
4129
  { text: truncate("session", budget), tone: HEADER_TONE },
3477
4130
  { text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
3478
4131
  { text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
3479
- { text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
4132
+ { text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
4133
+ { text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
3480
4134
  { text: "", tone: "muted" }
3481
4135
  ];
3482
4136
  }
@@ -3493,20 +4147,28 @@ function sidebarLines(rows, options) {
3493
4147
  const output = formatTokens(display.output);
3494
4148
  const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
3495
4149
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
3496
- const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
4150
+ const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`;
4151
+ const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`;
4152
+ const rate = [tps, ttft].filter((part) => part !== undefined).join(" \xB7 ");
3497
4153
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
3498
4154
  const header = `${clock} ${provider}`;
3499
4155
  const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
4156
+ const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
3500
4157
  const volumes = [
3501
- ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
4158
+ ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
4159
+ ` ${labels.input} ${input} \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
3502
4160
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
3503
4161
  ` ${labels.input} ${input}`
3504
4162
  ];
4163
+ const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
4164
+ const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
3505
4165
  const facts = [
3506
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
3507
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
3508
- ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
3509
- ` hit ${hit}${suffix}`
4166
+ ` ${join(hitPart, rate, `${cost}${suffix}`)}`,
4167
+ ` ${join(hitPart, tps, `${cost}${suffix}`)}`,
4168
+ ` ${join(tps, `${cost}${suffix}`)}`,
4169
+ ` ${join(tps)}`,
4170
+ ` ${join(hitPart, `${cost}${suffix}`)}`,
4171
+ ` ${join(`${cost}${suffix}`)}`
3510
4172
  ];
3511
4173
  lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
3512
4174
  const edge = index === 0 || index === rows.length - 1;
@@ -3514,10 +4176,7 @@ function sidebarLines(rows, options) {
3514
4176
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
3515
4177
  lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
3516
4178
  }
3517
- lines.push({
3518
- text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
3519
- tone: "muted"
3520
- });
4179
+ lines.push({ text: truncate(volume, budget), tone: "muted" });
3521
4180
  lines.push({
3522
4181
  text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
3523
4182
  tone: turn.drops.length > 0 ? "warning" : "muted"
@@ -3547,11 +4206,12 @@ function detailLabel(row) {
3547
4206
  }
3548
4207
  }
3549
4208
  function buildPanel(request) {
4209
+ const width = clampPanelWidth(request.width);
3550
4210
  try {
3551
- return build(request);
4211
+ return build({ ...request, width }).map((line) => line.text.length <= width ? line : { ...line, text: truncate(line.text, width) });
3552
4212
  } catch (error) {
3553
4213
  const message = error instanceof Error ? error.message : String(error);
3554
- return [{ text: `stats query failed: ${message}`, tone: "warning" }];
4214
+ return [{ text: truncate(`stats query failed: ${message}`, width), tone: "warning" }];
3555
4215
  }
3556
4216
  }
3557
4217
  function build(request) {
@@ -3665,10 +4325,15 @@ function buildDetail(request, range, filters, estimates) {
3665
4325
  const steps = stepRows(db, { range, filters: scoped });
3666
4326
  return [
3667
4327
  head,
3668
- {
3669
- 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)}`,
3670
- tone: "muted"
3671
- },
4328
+ ...kvGrid([
4329
+ ["steps", formatCount(stats.steps)],
4330
+ ["in", formatTokens(stats.prompt - stats.cached)],
4331
+ ["prompt", formatTokens(stats.prompt)],
4332
+ ["cached", formatTokens(stats.cached)],
4333
+ ["write", formatTokens(stats.cacheWrite)],
4334
+ ["hit", percent(stats.hit)],
4335
+ ["p50", percent(stats.hitP50)]
4336
+ ], width),
3672
4337
  { text: "", tone: "muted" },
3673
4338
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3674
4339
  { text: "", tone: "muted" },
@@ -3687,10 +4352,14 @@ function buildDetail(request, range, filters, estimates) {
3687
4352
  const stats = cacheStatsOf(db, { range, filters: scoped });
3688
4353
  return [
3689
4354
  head,
3690
- {
3691
- 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)}`,
3692
- tone: "muted"
3693
- },
4355
+ ...kvGrid([
4356
+ ["steps", formatCount(stats.steps)],
4357
+ ["in", formatTokens(stats.prompt - stats.cached)],
4358
+ ["prompt", formatTokens(stats.prompt)],
4359
+ ["cached", formatTokens(stats.cached)],
4360
+ ["hit", percent(stats.hit)],
4361
+ ["p50", percent(stats.hitP50)]
4362
+ ], width),
3694
4363
  { text: "", tone: "muted" },
3695
4364
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3696
4365
  { text: "", tone: "muted" },
@@ -3749,6 +4418,8 @@ function sortProviders(rows, sort, desc, estimates = true) {
3749
4418
  return row.share;
3750
4419
  if (sort === "tps")
3751
4420
  return row.tps ?? -1;
4421
+ if (sort === "ttft")
4422
+ return row.ttft ?? -1;
3752
4423
  return row.usage.steps;
3753
4424
  };
3754
4425
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
@@ -3758,6 +4429,8 @@ function sortLatency(rows, sort, desc) {
3758
4429
  const pick = (row) => {
3759
4430
  if (sort === "tps")
3760
4431
  return row.tps.p50 ?? -1;
4432
+ if (sort === "ttft")
4433
+ return row.ttft.p50 ?? -1;
3761
4434
  if (sort === "wall")
3762
4435
  return row.wall.p50 ?? -1;
3763
4436
  return row.count;
@@ -3834,13 +4507,6 @@ function size(path) {
3834
4507
  return 0;
3835
4508
  }
3836
4509
  }
3837
- function hasTable(db, name) {
3838
- try {
3839
- return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
3840
- } catch {
3841
- return false;
3842
- }
3843
- }
3844
4510
  function dbInfo(db, path, now = Date.now()) {
3845
4511
  const tables = TABLES.map((table) => ({
3846
4512
  name: table,
@@ -3894,7 +4560,7 @@ function pruneOlderThan(db, cutoff) {
3894
4560
  return {
3895
4561
  steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
3896
4562
  prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
3897
- events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
4563
+ compactions: deleteBatched(db, "compactions", "at IS NOT NULL AND at < ?", cutoff),
3898
4564
  usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
3899
4565
  };
3900
4566
  }
@@ -3902,7 +4568,7 @@ function wipeAll(db) {
3902
4568
  return {
3903
4569
  steps: deleteAllBatched(db, "steps"),
3904
4570
  prompts: deleteAllBatched(db, "prompts"),
3905
- events: deleteAllBatched(db, "events"),
4571
+ compactions: deleteAllBatched(db, "compactions"),
3906
4572
  usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
3907
4573
  sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
3908
4574
  };
@@ -3925,23 +4591,41 @@ function hasListCost(db) {
3925
4591
  }
3926
4592
  }
3927
4593
  var BACKFILL_BATCH = 1000;
4594
+ var UNPRICED_WHERE = `cost = 0 AND list_cost IS NULL
4595
+ AND provider_id IS NOT NULL AND provider_id <> ''
4596
+ AND model_id IS NOT NULL AND model_id <> ''
4597
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`;
4598
+ function priceStep(step, price) {
4599
+ const estimate = price({ providerID: step.provider_id ?? undefined, modelID: step.model_id ?? undefined }, {
4600
+ input: step.input_tokens ?? 0,
4601
+ output: step.output_tokens ?? 0,
4602
+ reasoning: step.reasoning_tokens ?? 0,
4603
+ cacheRead: step.cache_read ?? 0,
4604
+ cacheWrite: step.cache_write ?? 0
4605
+ });
4606
+ return estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined;
4607
+ }
4608
+ function backfillBatch(db, rows, price, update) {
4609
+ let updated = 0;
4610
+ db.transaction(() => {
4611
+ for (const row of rows) {
4612
+ const estimate = priceStep(row, price);
4613
+ if (estimate !== undefined && update(estimate, row.rowid) > 0)
4614
+ updated += 1;
4615
+ }
4616
+ })();
4617
+ return updated;
4618
+ }
3928
4619
  function backfillListCost(db, price) {
3929
4620
  if (!hasListCost(db))
3930
4621
  return { candidates: 0, updated: 0 };
3931
- const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
3932
- WHERE cost = 0 AND list_cost IS NULL
3933
- AND provider_id IS NOT NULL AND provider_id <> ''
3934
- AND model_id IS NOT NULL AND model_id <> ''
3935
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
4622
+ const candidates = db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${UNPRICED_WHERE}`).get().n;
3936
4623
  if (candidates === 0)
3937
4624
  return { candidates: 0, updated: 0 };
3938
4625
  const select = db.query(`SELECT rowid, provider_id, model_id,
3939
4626
  input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3940
4627
  FROM steps
3941
- WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
3942
- AND provider_id IS NOT NULL AND provider_id <> ''
3943
- AND model_id IS NOT NULL AND model_id <> ''
3944
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
4628
+ WHERE ${UNPRICED_WHERE} AND rowid > ?
3945
4629
  ORDER BY rowid
3946
4630
  LIMIT ?`);
3947
4631
  const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
@@ -3951,21 +4635,7 @@ function backfillListCost(db, price) {
3951
4635
  const rows = select.all(cursor, BACKFILL_BATCH);
3952
4636
  if (rows.length === 0)
3953
4637
  break;
3954
- db.transaction(() => {
3955
- for (const row of rows) {
3956
- const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
3957
- input: row.input_tokens ?? 0,
3958
- output: row.output_tokens ?? 0,
3959
- reasoning: row.reasoning_tokens ?? 0,
3960
- cacheRead: row.cache_read ?? 0,
3961
- cacheWrite: row.cache_write ?? 0
3962
- });
3963
- if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
3964
- continue;
3965
- if (update.run(estimate, row.rowid).changes > 0)
3966
- updated += 1;
3967
- }
3968
- })();
4638
+ updated += backfillBatch(db, rows, price, (estimate, rowid) => update.run(estimate, rowid).changes);
3969
4639
  cursor = rows[rows.length - 1].rowid;
3970
4640
  if (rows.length < BACKFILL_BATCH)
3971
4641
  break;
@@ -4054,7 +4724,7 @@ function createService(db, options) {
4054
4724
  }
4055
4725
  function turnHistory(input) {
4056
4726
  const handle = db();
4057
- const width = clamp2(input.width, 20, 120);
4727
+ const width = clamp2(input.width, 20, MAX_HISTORY_WIDTH);
4058
4728
  const limit = clampTurnsLimit(input.limit);
4059
4729
  const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
4060
4730
  const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
@@ -4154,6 +4824,7 @@ class StatsClient {
4154
4824
  startPromise;
4155
4825
  starting;
4156
4826
  startAbort;
4827
+ abortStart;
4157
4828
  fallbackService;
4158
4829
  fallbackMode = false;
4159
4830
  stopped = false;
@@ -4162,6 +4833,13 @@ class StatsClient {
4162
4833
  constructor(config) {
4163
4834
  this.config = config;
4164
4835
  }
4836
+ reconfigure(options) {
4837
+ this.config.options = options;
4838
+ this.fallbackService = undefined;
4839
+ if (this.worker !== undefined || this.starting !== undefined) {
4840
+ this.hardReset("the usage service was reconfigured", false);
4841
+ }
4842
+ }
4165
4843
  request(method, input, options = {}) {
4166
4844
  if (this.stopped)
4167
4845
  return Promise.reject(new StatsError("unavailable", "the usage service is stopped"));
@@ -4182,7 +4860,9 @@ class StatsClient {
4182
4860
  return;
4183
4861
  this.stopped = true;
4184
4862
  this.rejectAll(new StatsError("unavailable", "the usage service stopped"));
4863
+ this.abortStart?.();
4185
4864
  this.startAbort?.();
4865
+ this.abortStart = undefined;
4186
4866
  this.worker?.terminate();
4187
4867
  this.worker = undefined;
4188
4868
  this.starting = undefined;
@@ -4238,7 +4918,7 @@ class StatsClient {
4238
4918
  }
4239
4919
  this.starting = worker;
4240
4920
  let timer;
4241
- const finish = (ok, reason) => {
4921
+ const finish = (ok, reason, useFallback = true) => {
4242
4922
  if (settled)
4243
4923
  return;
4244
4924
  settled = true;
@@ -4247,6 +4927,7 @@ class StatsClient {
4247
4927
  this.startPromise = undefined;
4248
4928
  this.starting = undefined;
4249
4929
  this.startAbort = undefined;
4930
+ this.abortStart = undefined;
4250
4931
  if (this.stopped) {
4251
4932
  worker.terminate();
4252
4933
  this.worker = undefined;
@@ -4255,11 +4936,13 @@ class StatsClient {
4255
4936
  }
4256
4937
  if (!ok) {
4257
4938
  worker.terminate();
4258
- this.useFallback(reason ?? "the usage worker did not start");
4939
+ if (useFallback)
4940
+ this.useFallback(reason ?? "the usage worker did not start");
4259
4941
  }
4260
4942
  resolve();
4261
4943
  };
4262
- this.startAbort = () => finish(false, "the usage service stopped");
4944
+ this.startAbort = () => finish(false, "the usage service stopped", false);
4945
+ this.abortStart = () => finish(false, "the usage service was reconfigured", false);
4263
4946
  timer = setTimeout(() => finish(false, "the usage worker did not start in time"), this.config.timeouts?.start ?? START_TIMEOUT_MS);
4264
4947
  worker.onmessage = (event) => {
4265
4948
  const message = event.data;
@@ -4373,9 +5056,12 @@ class StatsClient {
4373
5056
  pending.reject(error);
4374
5057
  }
4375
5058
  }
4376
- hardReset(message) {
4377
- this.config.log?.(message);
5059
+ hardReset(message, log = true) {
5060
+ if (log)
5061
+ this.config.log?.(message);
4378
5062
  this.rejectAll(new StatsError("unavailable", message));
5063
+ this.abortStart?.();
5064
+ this.abortStart = undefined;
4379
5065
  this.worker?.terminate();
4380
5066
  this.worker = undefined;
4381
5067
  this.starting?.terminate();
@@ -4446,123 +5132,140 @@ function rpcFailure(context, error) {
4446
5132
  return context.error(error.code, error.message);
4447
5133
  return context.error("unavailable", "the usage database is unavailable");
4448
5134
  }
5135
+ function serviceOptionsFor(settings, policy) {
5136
+ return {
5137
+ pricing: settings.pricing,
5138
+ maintenance: policy.maintenance,
5139
+ exposePaths: policy.exposePaths,
5140
+ format: {
5141
+ labels: settings.labels,
5142
+ fields: settings.fields,
5143
+ turnTotals: settings.turnTotals,
5144
+ estimates: settings.pricing
5145
+ }
5146
+ };
5147
+ }
4449
5148
  var src_default = Plugin.define({
4450
5149
  id: "usage-insights",
4451
5150
  async setup(ctx) {
4452
- const options = ctx.options ?? {};
4453
- if (options.enabled === false)
4454
- return;
4455
- const path = resolveDbPath(options.db);
4456
- const db = tryOpen(path);
4457
- if (db === undefined)
5151
+ if (Object.keys(ctx.options ?? {}).length > 0) {
5152
+ console.warn("[usage-insights] plugin options in opencode.json(c) are no longer read; edit the settings in the TUI or Desktop instead");
5153
+ }
5154
+ const policy = serverPolicy();
5155
+ const path = resolveDbPath();
5156
+ const stored = await ctx.storage.get(SETTINGS_STORAGE_KEY).catch(() => {
5157
+ console.warn("[usage-insights] could not read the shared settings; using the defaults");
4458
5158
  return;
4459
- try {
4460
- db.exec("PRAGMA busy_timeout = 1000");
4461
- } catch {}
4462
- const pricing = options.pricing !== "off";
4463
- const maintenance = options.maintenance !== false;
4464
- const exposePaths = options.exposePaths === true;
4465
- const source = pricing ? createPriceSource(ctx) : undefined;
4466
- source?.refresh(true);
4467
- const format = {
4468
- ...options.labels !== undefined ? { labels: options.labels } : {},
4469
- ...options.fields !== undefined ? { fields: options.fields } : {},
4470
- ...options.turnTotals !== undefined ? { turnTotals: options.turnTotals } : {}
4471
- };
4472
- const serviceOptions = { pricing, maintenance, exposePaths, format };
4473
- const stats = new StatsClient({
4474
- dbPath: path,
4475
- options: serviceOptions,
4476
- priceTable: () => source?.table(),
4477
- fallback: () => createService(() => db, {
4478
- ...serviceOptions,
4479
- path,
4480
- priceTable: () => source?.table()
4481
- }),
4482
- log: (message) => console.warn(`[usage-insights] ${message}`)
4483
5159
  });
4484
- const registration = await ctx.rpc.register(UsageInsights, {
4485
- panel: async (input, context) => {
4486
- try {
4487
- return await stats.request("panel", input);
4488
- } catch (error) {
4489
- return rpcFailure(context, error);
4490
- }
4491
- },
4492
- turns: async (input, context) => {
4493
- try {
4494
- return await stats.request("turns", input);
4495
- } catch (error) {
4496
- return rpcFailure(context, error);
4497
- }
4498
- },
4499
- listCost: async (input, context) => {
4500
- try {
4501
- return await stats.request("listCost", input);
4502
- } catch (error) {
4503
- return rpcFailure(context, error);
4504
- }
4505
- },
4506
- filters: async (_input, context) => {
4507
- try {
4508
- return await stats.request("filters", {});
4509
- } catch (error) {
4510
- return rpcFailure(context, error);
4511
- }
4512
- },
4513
- dbInfo: async (_input, context) => {
4514
- try {
4515
- return await stats.request("dbInfo", {});
4516
- } catch (error) {
4517
- return rpcFailure(context, error);
4518
- }
4519
- },
4520
- prune: async (input, context) => {
4521
- try {
4522
- return await stats.request("prune", input);
4523
- } catch (error) {
4524
- return rpcFailure(context, error);
4525
- }
4526
- },
4527
- wipe: async (input, context) => {
4528
- try {
4529
- return await stats.request("wipe", input);
4530
- } catch (error) {
4531
- return rpcFailure(context, error);
4532
- }
4533
- },
4534
- vacuum: async (input, context) => {
4535
- try {
4536
- return await stats.request("vacuum", input);
4537
- } catch (error) {
4538
- return rpcFailure(context, error);
4539
- }
5160
+ let settings = sanitizeUsageSettings(stored);
5161
+ const source = createPriceSource(ctx);
5162
+ if (settings.pricing)
5163
+ source.refresh(true);
5164
+ let runtime;
5165
+ let serviceOptions = serviceOptionsFor(settings, policy);
5166
+ let nextOpenAttempt = 0;
5167
+ function ensureRuntime() {
5168
+ if (runtime !== undefined)
5169
+ return runtime;
5170
+ const now = Date.now();
5171
+ if (now < nextOpenAttempt)
5172
+ return;
5173
+ const db = tryOpen(path);
5174
+ if (db === undefined) {
5175
+ nextOpenAttempt = now + 5000;
5176
+ return;
5177
+ }
5178
+ try {
5179
+ db.exec("PRAGMA busy_timeout = 1000");
5180
+ } catch {}
5181
+ const stats = new StatsClient({
5182
+ dbPath: path,
5183
+ options: serviceOptions,
5184
+ priceTable: () => source.table(),
5185
+ fallback: () => createService(() => db, {
5186
+ ...serviceOptions,
5187
+ path,
5188
+ priceTable: () => source.table()
5189
+ }),
5190
+ log: (message) => console.warn(`[usage-insights] ${message}`)
5191
+ });
5192
+ const recorder = createRecorder(db, {
5193
+ price: (ref, tokens) => settings.pricing ? source.price(ref, tokens) : undefined
5194
+ });
5195
+ runtime = { db, stats, recorder };
5196
+ return runtime;
5197
+ }
5198
+ function applySettings(next) {
5199
+ const previous = settings;
5200
+ settings = next;
5201
+ if (next.pricing && !previous.pricing)
5202
+ source.refresh(true);
5203
+ const serverChanged = previous.pricing !== next.pricing || previous.turnTotals !== next.turnTotals || JSON.stringify(previous.fields) !== JSON.stringify(next.fields) || JSON.stringify(previous.labels) !== JSON.stringify(next.labels);
5204
+ if (!serverChanged)
5205
+ return;
5206
+ serviceOptions = serviceOptionsFor(settings, policy);
5207
+ runtime?.stats.reconfigure(serviceOptions);
5208
+ }
5209
+ const envelope = () => ({ settings, policy });
5210
+ let notifySettings;
5211
+ const settingsRegistration = await ctx.rpc.register(UsageInsightsSettings, {
5212
+ get: async () => envelope(),
5213
+ set: async (input) => {
5214
+ const next = mergeUsageSettings(settings, input.patch);
5215
+ await ctx.storage.set(SETTINGS_STORAGE_KEY, next);
5216
+ applySettings(next);
5217
+ const saved = envelope();
5218
+ await notifySettings?.(saved).catch(() => {});
5219
+ return saved;
4540
5220
  },
4541
- backfill: async (input, context) => {
4542
- try {
4543
- return await stats.request("backfill", input);
4544
- } catch (error) {
4545
- return rpcFailure(context, error);
4546
- }
5221
+ reset: async () => {
5222
+ await ctx.storage.remove(SETTINGS_STORAGE_KEY);
5223
+ applySettings(defaultUsageSettings());
5224
+ const saved = envelope();
5225
+ await notifySettings?.(saved).catch(() => {});
5226
+ return saved;
5227
+ }
5228
+ });
5229
+ notifySettings = (next) => settingsRegistration.events.emit("updated", next);
5230
+ async function request(method, input, context) {
5231
+ const current = ensureRuntime();
5232
+ if (current === undefined)
5233
+ return context.error("unavailable", "the usage database is unavailable");
5234
+ try {
5235
+ return await current.stats.request(method, input);
5236
+ } catch (error) {
5237
+ return rpcFailure(context, error);
4547
5238
  }
4548
- }).catch((error) => {
4549
- stats.stop();
4550
- db.close();
5239
+ }
5240
+ const dataRegistration = await ctx.rpc.register(UsageInsights, {
5241
+ panel: (input, context) => request("panel", input, context),
5242
+ turns: (input, context) => request("turns", input, context),
5243
+ listCost: (input, context) => request("listCost", input, context),
5244
+ filters: (_input, context) => request("filters", {}, context),
5245
+ dbInfo: (_input, context) => request("dbInfo", {}, context),
5246
+ prune: (input, context) => request("prune", input, context),
5247
+ wipe: (input, context) => request("wipe", input, context),
5248
+ vacuum: (input, context) => request("vacuum", input, context),
5249
+ backfill: (input, context) => request("backfill", input, context)
5250
+ }).catch(async (error) => {
5251
+ await settingsRegistration.dispose().catch(() => {});
5252
+ runtime?.stats.stop();
5253
+ runtime?.db.close();
4551
5254
  throw error;
4552
5255
  });
4553
- const recorder = createRecorder(db, source === undefined ? undefined : { price: source.price });
5256
+ ensureRuntime();
4554
5257
  const abort = new AbortController;
4555
5258
  const stream = (async () => {
4556
5259
  try {
4557
5260
  for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
4558
5261
  try {
4559
- if (event.type === "model.updated")
4560
- source?.refresh(true);
4561
- recorder.handleEvent(event);
5262
+ if (event.type === "model.updated" && settings.pricing)
5263
+ source.refresh(true);
5264
+ runtime?.recorder.handleEvent(event);
4562
5265
  if (RECORDED_EVENTS.has(event.type)) {
4563
5266
  const data = event.data;
4564
5267
  const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
4565
- registration.events.emit("recorded", { at: Date.now(), ...sessionID !== undefined ? { sessionID } : {} }).catch(() => {});
5268
+ dataRegistration.events.emit("recorded", { at: Date.now(), ...sessionID !== undefined ? { sessionID } : {} }).catch(() => {});
4566
5269
  }
4567
5270
  } catch {}
4568
5271
  }
@@ -4570,10 +5273,10 @@ var src_default = Plugin.define({
4570
5273
  })();
4571
5274
  return async () => {
4572
5275
  abort.abort();
4573
- await registration.dispose();
5276
+ await Promise.allSettled([dataRegistration.dispose(), settingsRegistration.dispose()]);
4574
5277
  await stream;
4575
- stats.stop();
4576
- db.close();
5278
+ runtime?.stats.stop();
5279
+ runtime?.db.close();
4577
5280
  };
4578
5281
  }
4579
5282
  });
@@ -4581,4 +5284,4 @@ export {
4581
5284
  src_default as default
4582
5285
  };
4583
5286
 
4584
- //# debugId=81E9F82B0FBCADEE64756E2164756E21
5287
+ //# debugId=416DE53B4E3B355564756E2164756E21