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/tui.js CHANGED
@@ -351,22 +351,9 @@ function formatLine(stats, options) {
351
351
  return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
352
352
  }
353
353
 
354
- // src/limits.ts
355
- var MAX_PANEL_WIDTH = 200;
356
- var MAX_TURNS = 50;
357
- function clampPanelWidth(value) {
358
- if (!Number.isFinite(value))
359
- return 20;
360
- return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
361
- }
362
- function clampTurnsLimit(value) {
363
- if (!Number.isFinite(value))
364
- return 1;
365
- return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
366
- }
367
-
368
354
  // src/text.ts
369
355
  var TEXT_LIMIT = 512;
356
+ var LABEL_LIMIT = 4 * TEXT_LIMIT;
370
357
  function sanitizeText(value, limit = TEXT_LIMIT) {
371
358
  if (limit <= 0)
372
359
  return "";
@@ -496,7 +483,6 @@ function lineText(parts) {
496
483
  }
497
484
 
498
485
  // src/stats/queries.ts
499
- var COMPACTION_KIND = "compaction";
500
486
  var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
501
487
  function spend(usage) {
502
488
  return usage.cost + usage.listCost;
@@ -566,9 +552,10 @@ function otherUsageRows(db, range, filters) {
566
552
  }
567
553
  }
568
554
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
569
- var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
555
+ var MODEL_KEY_SEPARATOR = "#";
556
+ var MODEL_KEY_SQL = `COALESCE(model_id, '(unknown)') || '${MODEL_KEY_SEPARATOR}' || COALESCE(variant, '')`;
570
557
  function modelKey(modelID, variant) {
571
- return `${modelID}#${variant ?? ""}`;
558
+ return `${modelID}${MODEL_KEY_SEPARATOR}${variant ?? ""}`;
572
559
  }
573
560
  function modelLabel(modelID, variant) {
574
561
  return variant === undefined ? modelID : `${modelID} ${variant}`;
@@ -639,7 +626,10 @@ function overview(db, range, filters) {
639
626
  MIN(${STEP_TIME}) AS firstAt,
640
627
  MAX(COALESCE(completed_at, ${STEP_TIME})) AS lastAt,
641
628
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS produced,
642
- COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
629
+ COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window,
630
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at) THEN output_tokens + reasoning_tokens ELSE 0 END), 0) AS decodeProduced,
631
+ COALESCE(SUM(CASE WHEN streamed_at > COALESCE(first_token_at, created_at)
632
+ THEN streamed_at - COALESCE(first_token_at, created_at) ELSE 0 END), 0) AS decodeWindow
643
633
  FROM steps ${steps.where}`).get(...steps.params);
644
634
  const prompts = rangeWhere(range, "created_at");
645
635
  const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
@@ -650,6 +640,10 @@ function overview(db, range, filters) {
650
640
  }
651
641
  const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
652
642
  const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
643
+ const ttftFilter = steps.where === "" ? "WHERE" : `${steps.where} AND`;
644
+ const ttftRows = db.query(`SELECT MAX(0, first_token_at - created_at) AS ttft
645
+ FROM steps ${ttftFilter} created_at IS NOT NULL AND first_token_at IS NOT NULL`).all(...steps.params);
646
+ const ttft = ttftRows.length === 0 ? undefined : percentile(ttftRows.map((entry) => entry.ttft), 50);
653
647
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
654
648
  const other = otherUsage(db, range, filters);
655
649
  return {
@@ -661,7 +655,9 @@ function overview(db, range, filters) {
661
655
  firstAt: row?.firstAt ?? undefined,
662
656
  lastAt: row?.lastAt ?? undefined,
663
657
  cacheHitRatio: cacheHitRatio(usage),
664
- tps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0)
658
+ tps: row === null ? undefined : tokensPerSecond(row.decodeProduced ?? 0, 0, row.decodeWindow ?? 0),
659
+ requestTps: row === null ? undefined : tokensPerSecond(row.produced ?? 0, 0, row.window ?? 0),
660
+ ttft
665
661
  };
666
662
  }
667
663
  function models(db, range, filters) {
@@ -816,7 +812,11 @@ function stepMessage(row) {
816
812
  return {
817
813
  type: "assistant",
818
814
  id: row.message_id,
819
- time: { created: row.created_at ?? row.recorded_at, completed: row.completed_at ?? undefined },
815
+ time: {
816
+ created: row.created_at ?? row.recorded_at,
817
+ firstToken: row.first_token_at ?? undefined,
818
+ completed: row.completed_at ?? undefined
819
+ },
820
820
  model: row.provider_id !== null && row.model_id !== null ? { providerID: row.provider_id, id: row.model_id, variant: row.variant ?? undefined } : undefined,
821
821
  tokens: {
822
822
  input: row.input_tokens ?? 0,
@@ -847,7 +847,7 @@ function turns(db, options) {
847
847
  }
848
848
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
849
849
  input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
850
- created_at, streamed_at, recorded_at, completed_at, finish
850
+ created_at, first_token_at, streamed_at, recorded_at, completed_at, finish
851
851
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
852
852
  ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
853
853
  const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
@@ -890,12 +890,22 @@ function turns(db, options) {
890
890
  const variant = last.variant ?? undefined;
891
891
  let produced = 0;
892
892
  let window = 0;
893
+ let decodeProduced = 0;
894
+ let decodeWindow = 0;
893
895
  for (const row of bucket) {
894
- if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
895
- continue;
896
- produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
897
- window += row.streamed_at - row.created_at;
896
+ const tokens = (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
897
+ if (row.created_at !== null && row.streamed_at !== null && row.streamed_at > row.created_at) {
898
+ produced += tokens;
899
+ window += row.streamed_at - row.created_at;
900
+ }
901
+ const start = row.first_token_at ?? row.created_at;
902
+ if (start !== null && row.streamed_at !== null && row.streamed_at > start) {
903
+ decodeProduced += tokens;
904
+ decodeWindow += row.streamed_at - start;
905
+ }
898
906
  }
907
+ const first = bucket[0];
908
+ const ttft = first !== undefined && first.created_at !== null && first.first_token_at !== null ? Math.max(0, first.first_token_at - first.created_at) : undefined;
899
909
  const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
900
910
  const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
901
911
  const firstAt = bucket[0]?.created_at ?? promptAt;
@@ -915,7 +925,9 @@ function turns(db, options) {
915
925
  totals,
916
926
  drops,
917
927
  finish: last.finish ?? undefined,
918
- tps: tokensPerSecond(produced, 0, window)
928
+ tps: tokensPerSecond(decodeProduced, 0, decodeWindow),
929
+ requestTps: tokensPerSecond(produced, 0, window),
930
+ ttft
919
931
  });
920
932
  bucket = [];
921
933
  }
@@ -1092,8 +1104,8 @@ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
1092
1104
  var GRANULARITIES = ["day", "week", "month"];
1093
1105
  var SORT_KEYS = {
1094
1106
  models: ["steps", "cached", "hit", "out", "cost"],
1095
- providers: ["steps", "cached", "hit", "cost", "share", "tps"],
1096
- latency: ["n", "tps", "wall"],
1107
+ providers: ["steps", "cached", "hit", "cost", "share", "tps", "ttft"],
1108
+ latency: ["n", "tps", "ttft", "wall"],
1097
1109
  sessions: ["last", "steps", "cached", "cost"],
1098
1110
  turns: ["time", "cost", "tokens"]
1099
1111
  };
@@ -1191,10 +1203,10 @@ function formatTps(value) {
1191
1203
  return "\u2013";
1192
1204
  return `${value.toFixed(1)}/s`;
1193
1205
  }
1194
- function formatTpsCompact(value) {
1206
+ function formatRateValue(value) {
1195
1207
  if (value === undefined || !Number.isFinite(value) || value < 0)
1196
1208
  return "\u2013";
1197
- return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
1209
+ return value >= 10 ? String(Math.round(value)) : value.toFixed(1);
1198
1210
  }
1199
1211
  function formatGap(value) {
1200
1212
  if (value === undefined || !Number.isFinite(value))
@@ -1226,15 +1238,6 @@ function truncateMiddle(value, width) {
1226
1238
  const tail = width - 1 - head;
1227
1239
  return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
1228
1240
  }
1229
- function tableWidths(width, layouts) {
1230
- for (const layout of layouts) {
1231
- const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
1232
- if (total <= width)
1233
- return [...layout];
1234
- }
1235
- const last = layouts[layouts.length - 1];
1236
- return last === undefined ? [] : [...last];
1237
- }
1238
1241
  function modelCell(modelID, variant, width) {
1239
1242
  return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
1240
1243
  }
@@ -1253,6 +1256,47 @@ function formatTableRow(cells, widths, aligns) {
1253
1256
  }
1254
1257
  return parts.join(" ");
1255
1258
  }
1259
+ function fitTableColumns(columns, width) {
1260
+ const chosen = new Set;
1261
+ for (let index = 0;index < columns.length; index += 1) {
1262
+ if (columns[index].priority === undefined)
1263
+ chosen.add(index);
1264
+ }
1265
+ if (chosen.size === 0)
1266
+ return [];
1267
+ const total = () => {
1268
+ let sum = chosen.size - 1;
1269
+ for (const index of chosen)
1270
+ sum += columns[index].width;
1271
+ return sum;
1272
+ };
1273
+ 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);
1274
+ for (const { column, index } of optional) {
1275
+ if (total() + column.width + 1 + (column.reserve ?? 0) <= width)
1276
+ chosen.add(index);
1277
+ }
1278
+ while (chosen.size > 1 && total() > width)
1279
+ chosen.delete(Math.max(...chosen));
1280
+ const widths = new Map;
1281
+ let room = width - total();
1282
+ for (let index = 0;index < columns.length && room > 0; index += 1) {
1283
+ if (!chosen.has(index))
1284
+ continue;
1285
+ const column = columns[index];
1286
+ const grow = Math.min(room, (column.max ?? column.width) - column.width);
1287
+ if (grow <= 0)
1288
+ continue;
1289
+ widths.set(index, column.width + grow);
1290
+ room -= grow;
1291
+ }
1292
+ return [...chosen].sort((left, right) => left - right).map((index) => ({ index, width: widths.get(index) ?? columns[index].width }));
1293
+ }
1294
+ function fitTable(columns, width) {
1295
+ return fitTableColumns(columns, width).map(({ index, width: fitted }) => {
1296
+ const column = columns[index];
1297
+ return { index, header: column.header, width: fitted, align: column.align ?? "left", cell: column.cell };
1298
+ });
1299
+ }
1256
1300
  function count(n, singular, plural = `${singular}s`) {
1257
1301
  return `${formatCount(n)} ${n === 1 ? singular : plural}`;
1258
1302
  }
@@ -1260,21 +1304,30 @@ function kvGrid(pairs, width) {
1260
1304
  const lines = [];
1261
1305
  const label = 11;
1262
1306
  const column = Math.floor(width / 2);
1307
+ const pairLines = (pair) => {
1308
+ const text = `${padCell(pair[0], label)}${pair[1]}`;
1309
+ if (text.length <= width)
1310
+ return [text];
1311
+ return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width));
1312
+ };
1263
1313
  for (let index = 0;index < pairs.length; index += 2) {
1264
1314
  const left = pairs[index];
1265
1315
  const right = pairs[index + 1];
1266
- const leftText = `${padCell(left[0], label)}${left[1]}`;
1267
1316
  if (right === undefined) {
1268
- lines.push({ text: leftText, tone: "base" });
1317
+ for (const text of pairLines(left))
1318
+ lines.push({ text, tone: "base" });
1269
1319
  continue;
1270
1320
  }
1321
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
1271
1322
  const rightText = `${padCell(right[0], label)}${right[1]}`;
1272
1323
  const gap = Math.max(2, column - leftText.length);
1273
1324
  if (leftText.length + gap + rightText.length <= width) {
1274
1325
  lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
1275
1326
  } else {
1276
- lines.push({ text: leftText, tone: "base" });
1277
- lines.push({ text: rightText, tone: "base" });
1327
+ for (const text of pairLines(left))
1328
+ lines.push({ text, tone: "base" });
1329
+ for (const text of pairLines(right))
1330
+ lines.push({ text, tone: "base" });
1278
1331
  }
1279
1332
  }
1280
1333
  return lines;
@@ -1384,7 +1437,11 @@ function helpLines(width) {
1384
1437
  { text: " \u2248 list-price estimate for steps the host reported as $0;" },
1385
1438
  { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
1386
1439
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
1387
- { text: " tps out / streaming seconds, shown as p50" },
1440
+ { text: " ttft request \u2192 first streamed token" },
1441
+ { text: " tps output+reasoning / first token \u2192 last chunk (OpenCode)" },
1442
+ { text: " rtps output+reasoning / request \u2192 last chunk (includes TTFT)" },
1443
+ { text: " turn 200 tps \xB7 2.1s ttft \xB7 cost" },
1444
+ { text: " session 200 tps \xB7 167 rtps \xB7 ttft p50 \xB7 cost" },
1388
1445
  { text: " switches how often a step's model or provider differs from the step" },
1389
1446
  { text: " before it in the same session (the models view's detail), with" },
1390
1447
  { text: " the cache a provider switch cost" },
@@ -1513,26 +1570,32 @@ function usagePairs(usage, estimates = true) {
1513
1570
  ];
1514
1571
  if (buckets.reasoning > 0)
1515
1572
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
1573
+ if ("tps" in usage && usage.tps !== undefined)
1574
+ pairs.push(["tps", formatTps(usage.tps)]);
1575
+ if ("requestTps" in usage && usage.requestTps !== undefined)
1576
+ pairs.push(["rtps", formatTps(usage.requestTps)]);
1577
+ if ("ttft" in usage && usage.ttft !== undefined)
1578
+ pairs.push(["ttft p50", formatMs(usage.ttft)]);
1516
1579
  pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
1517
1580
  const other = usage.otherCost ?? 0;
1518
1581
  if (other > 0)
1519
1582
  pairs.push(["other", `${formatCost(other)} comp/title`]);
1520
- if ("tps" in usage && usage.tps !== undefined)
1521
- pairs.push(["tps", formatTps(usage.tps)]);
1522
1583
  return pairs;
1523
1584
  }
1524
1585
  function overviewLines(data, width) {
1525
1586
  const lines = [];
1526
1587
  const estimates = data.estimates !== false;
1527
1588
  lines.push({
1528
- text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
1589
+ text: truncate(`${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`, width),
1529
1590
  tone: "muted"
1530
1591
  });
1531
1592
  lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
1532
1593
  if (data.activity !== undefined && data.activity.length > 1) {
1533
- const series = reduceSeries(data.activity);
1594
+ const suffix = ` ${count(data.activity.length, "bucket")}`;
1595
+ const bars = Math.max(4, width - "activity ".length - suffix.length);
1596
+ const series = reduceSeries(data.activity, bars);
1534
1597
  lines.push({ text: "", tone: "muted" });
1535
- lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
1598
+ lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: "muted" });
1536
1599
  }
1537
1600
  if (data.session !== undefined) {
1538
1601
  lines.push({ text: "", tone: "muted" });
@@ -1543,7 +1606,7 @@ function overviewLines(data, width) {
1543
1606
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
1544
1607
  const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
1545
1608
  lines.push({
1546
- text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
1609
+ text: truncate(` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`, width),
1547
1610
  tone: "muted"
1548
1611
  });
1549
1612
  }
@@ -1569,71 +1632,40 @@ function coveragePairs(coverage) {
1569
1632
  ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
1570
1633
  ["providers", formatCount(coverage.providers)],
1571
1634
  ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
1635
+ ["no ttft", share(coverage.missingFirstToken)],
1572
1636
  [
1573
1637
  "window",
1574
1638
  `${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
1575
1639
  ]
1576
1640
  ];
1577
1641
  }
1578
- function modelColumns(width) {
1579
- const layouts = [
1580
- { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
1581
- { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
1582
- { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
1583
- { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
1584
- { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
1585
- ];
1586
- for (const layout of layouts) {
1587
- const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
1588
- if (total <= width)
1589
- return layout;
1590
- }
1591
- return layouts[layouts.length - 1];
1592
- }
1593
1642
  function modelsLines(rows, width, extras, limit = 40, estimates = true) {
1594
- const columns = modelColumns(width);
1595
- const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
1596
- const aligns = ["left", "right", "right", "right"];
1597
- const header = ["model", "steps", "prompt", "cached"];
1598
- if (columns.hit > 0) {
1599
- widths.push(columns.hit);
1600
- aligns.push("right");
1601
- header.push("hit");
1602
- }
1603
- widths.push(columns.out);
1604
- aligns.push("right");
1605
- header.push("out");
1606
- if (columns.cost > 0) {
1607
- widths.push(columns.cost);
1608
- aligns.push("right");
1609
- header.push("cost");
1610
- }
1611
- if (columns.spread > 0) {
1612
- widths.push(columns.spread);
1613
- aligns.push("left");
1614
- header.push("providers");
1615
- }
1616
- const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
1643
+ let modelWidth = 14;
1644
+ const columns = fitTable([
1645
+ { header: "model", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },
1646
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
1647
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => row.prompt },
1648
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => row.cached },
1649
+ { header: "hit", width: 6, max: 7, priority: 2, reserve: 10, align: "right", cell: (row) => row.hit },
1650
+ { header: "out", width: 7, max: 9, priority: 3, reserve: 10, align: "right", cell: (row) => row.output },
1651
+ { header: "cost", width: 8, max: 9, priority: 1, align: "right", cell: (row) => row.cost },
1652
+ { header: "providers", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers }
1653
+ ], width);
1654
+ modelWidth = columns.find((column) => column.index === 0)?.width ?? 0;
1655
+ if (columns.length === 0)
1656
+ return [{ text: truncate("no room for a table at this width", width), tone: "muted" }];
1657
+ const lines = [
1658
+ {
1659
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
1660
+ tone: HEADER_TONE
1661
+ }
1662
+ ];
1617
1663
  for (const model of rows.slice(0, limit)) {
1618
1664
  const key = modelKey(model.modelID, model.variant);
1619
- const name = modelCell(model.modelID, model.variant, columns.model);
1620
1665
  const buckets = usageBuckets(model.totals);
1621
1666
  const providers = unique(model.providers.map((provider) => provider.providerID));
1622
1667
  const cache = extras?.cache?.get(key);
1623
1668
  const switches = extras?.switches?.get(key);
1624
- const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
1625
- if (columns.hit > 0)
1626
- cells.push(formatPercent(cache?.hit ?? buckets.hit));
1627
- cells.push(formatTokens(buckets.output));
1628
- if (columns.cost > 0)
1629
- cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
1630
- if (columns.spread > 0)
1631
- cells.push(providers.join(", "));
1632
- lines.push({
1633
- text: formatTableRow(cells, widths, aligns),
1634
- tone: "base",
1635
- row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
1636
- });
1637
1669
  const details = [];
1638
1670
  if (cache !== undefined)
1639
1671
  details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
@@ -1643,62 +1675,77 @@ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
1643
1675
  if (switches.cacheLost > 0)
1644
1676
  details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
1645
1677
  }
1646
- if (details.length > 0) {
1647
- lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
1678
+ const view = {
1679
+ modelID: model.modelID,
1680
+ variant: model.variant,
1681
+ steps: formatCount(buckets.steps),
1682
+ prompt: formatTokens(buckets.prompt),
1683
+ cached: formatTokens(buckets.cached),
1684
+ hit: formatPercent(cache?.hit ?? buckets.hit),
1685
+ output: formatTokens(buckets.output),
1686
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),
1687
+ providers: providers.join(", "),
1688
+ detail: details.join(" \xB7 ")
1689
+ };
1690
+ lines.push({
1691
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
1692
+ tone: "base",
1693
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
1694
+ });
1695
+ if (view.detail !== "") {
1696
+ lines.push({ text: truncate(`${" ".repeat(modelWidth + 1)}${view.detail}`, width), tone: "muted" });
1648
1697
  }
1649
1698
  }
1650
1699
  if (rows.length > limit)
1651
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
1700
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, width), tone: "muted" });
1652
1701
  if (rows.length === 0)
1653
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
1702
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
1654
1703
  return lines;
1655
1704
  }
1656
1705
  function unique(values) {
1657
1706
  return [...new Set(values)];
1658
1707
  }
1659
- var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
1660
- function fitColumns(columns, width) {
1661
- const chosen = [...columns];
1662
- while (chosen.length > 1 && tableWidth(chosen) > width) {
1663
- const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
1664
- if (optional === -1)
1665
- break;
1666
- chosen.splice(chosen.length - 1 - optional, 1);
1667
- }
1668
- return chosen;
1669
- }
1670
1708
  function renderTable(rows, columns, width, options) {
1671
- const chosen = fitColumns(columns, width);
1709
+ const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {
1710
+ const column = columns[index];
1711
+ const align = column.align ?? "left";
1712
+ return { ...column, width: fitted, align };
1713
+ });
1714
+ if (chosen.length === 0)
1715
+ return [{ text: truncate(options.empty, width), tone: "muted" }];
1672
1716
  const widths = chosen.map((column) => column.width);
1673
- const aligns = chosen.map((column) => column.align ?? "left");
1674
- const alignsTyped = aligns;
1675
- const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
1717
+ const aligns = chosen.map((column) => column.align);
1718
+ const lines = [
1719
+ { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE }
1720
+ ];
1676
1721
  if (rows.length === 0)
1677
- lines.push({ text: options.empty, tone: "muted" });
1722
+ lines.push({ text: truncate(options.empty, width), tone: "muted" });
1678
1723
  for (const row of rows.slice(0, options.limit)) {
1679
1724
  const identity = options.row?.(row);
1680
1725
  lines.push({
1681
- text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
1726
+ text: formatTableRow(chosen.map((column) => column.cell(row, column.width)), widths, aligns),
1682
1727
  tone: options.tone?.(row) ?? "base",
1683
1728
  ...identity === undefined ? {} : { row: identity }
1684
1729
  });
1685
1730
  }
1686
- if (rows.length > options.limit)
1687
- lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
1731
+ if (rows.length > options.limit) {
1732
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - options.limit, "more row")}`, width), tone: "muted" });
1733
+ }
1688
1734
  return lines;
1689
1735
  }
1690
1736
  function providerSummaryLines(rows, width, limit = 40, estimates = true) {
1691
1737
  const lines = renderTable(rows, [
1692
- { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
1693
- { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
1738
+ { header: "provider", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
1739
+ { header: "models", width: 6, align: "right", priority: 4, cell: (row) => formatCount(row.models.length) },
1694
1740
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
1695
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
1696
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1697
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1698
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1699
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1700
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1701
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1741
+ { header: "share", width: 6, align: "right", priority: 3, cell: (row) => formatPercent(row.share, 0) },
1742
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1743
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1744
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
1745
+ { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
1746
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 6, cell: (row) => formatMs(row.ttft) },
1747
+ { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
1748
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1702
1749
  ], width, {
1703
1750
  limit,
1704
1751
  empty: "no usage recorded for this range",
@@ -1709,16 +1756,17 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
1709
1756
  }
1710
1757
  function providerLines(rows, width, limit = 40, estimates = true) {
1711
1758
  return renderTable(rows, [
1712
- { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
1713
- { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
1759
+ { header: "model", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },
1760
+ { header: "provider", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
1714
1761
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
1715
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
1716
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1717
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1718
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1719
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1720
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1721
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1762
+ { header: "share", width: 6, align: "right", priority: 5, cell: (row) => formatPercent(row.share, 0) },
1763
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },
1764
+ { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
1765
+ { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
1766
+ { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
1767
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 7, cell: (row) => formatMs(row.ttft) },
1768
+ { header: "wall", width: 7, align: "right", priority: 8, cell: (row) => formatMs(row.wall) },
1769
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1722
1770
  ], width, {
1723
1771
  limit,
1724
1772
  empty: "no usage recorded for this range",
@@ -1728,80 +1776,126 @@ function providerLines(rows, width, limit = 40, estimates = true) {
1728
1776
  }
1729
1777
  function cacheLines(data, width) {
1730
1778
  const lines = [];
1779
+ const push = (text, tone = "base") => {
1780
+ lines.push({ text: truncate(text, width), tone });
1781
+ };
1731
1782
  const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
1732
- lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
1783
+ push(`reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, total > 0 ? "warning" : "base");
1733
1784
  for (const reason of ["expired", "compaction", "unknown"]) {
1734
1785
  const group = data.drops.filter((drop) => drop.reason === reason);
1735
1786
  if (group.length === 0)
1736
1787
  continue;
1737
1788
  const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
1738
- lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
1789
+ push(` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, reason === "expired" ? "warning" : "muted");
1739
1790
  }
1740
1791
  if (data.drops.length === 0)
1741
- lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
1792
+ push(" none: prompt cache held through every gap", "muted");
1742
1793
  if (data.models !== undefined && data.models.length > 0) {
1743
1794
  lines.push({ text: "", tone: "muted" });
1744
- lines.push({ text: "reuse by model", tone: HEADER_TONE });
1745
- const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
1746
- lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
1747
- for (const row of data.models.slice(0, 10)) {
1748
- const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
1749
- lines.push({
1750
- 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"]),
1751
- tone: "base",
1752
- row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
1753
- });
1795
+ push("reuse by model", HEADER_TONE);
1796
+ let modelWidth = 12;
1797
+ const reuse = fitTable([
1798
+ { header: "model", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },
1799
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.cache.steps) },
1800
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1801
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1802
+ { header: "write", width: 6, max: 8, align: "right", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },
1803
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
1804
+ { header: "hit p50", width: 7, max: 9, align: "right", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) }
1805
+ ], width);
1806
+ modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0;
1807
+ if (reuse.length > 0) {
1808
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
1809
+ for (const row of data.models.slice(0, 10)) {
1810
+ lines.push({
1811
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
1812
+ tone: "base",
1813
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
1814
+ });
1815
+ }
1754
1816
  }
1755
1817
  }
1756
1818
  if (data.gap !== undefined && data.gap.samples > 0) {
1757
1819
  lines.push({ text: "", tone: "muted" });
1758
- lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
1759
- const widths = [9, 8, 9, 9, 10];
1760
- lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
1761
- for (const bucket of data.gap.buckets) {
1762
- if (bucket.samples === 0)
1763
- continue;
1764
- lines.push({
1765
- text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
1766
- tone: bucket.drops > 0 ? "warning" : "base"
1767
- });
1820
+ push("cache survival against idle time", HEADER_TONE);
1821
+ const buckets = data.gap.buckets;
1822
+ const survival = fitTable([
1823
+ { header: "gap", width: 8, max: 12, cell: (bucket) => bucket.label },
1824
+ { header: "pairs", width: 6, align: "right", cell: (bucket) => formatCount(bucket.samples) },
1825
+ { header: "kept", width: 7, align: "right", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },
1826
+ { header: "drops", width: 7, align: "right", cell: (bucket) => formatCount(bucket.drops) },
1827
+ { header: "lost", width: 8, align: "right", cell: (bucket) => formatTokens(bucket.lostTokens) }
1828
+ ], width);
1829
+ if (survival.length > 0) {
1830
+ lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: "muted" });
1831
+ for (const bucket of buckets) {
1832
+ if (bucket.samples === 0)
1833
+ continue;
1834
+ lines.push({
1835
+ text: formatTableRow(survival.map((column) => column.cell(bucket)), survival.map((column) => column.width), survival.map((column) => column.align)),
1836
+ tone: bucket.drops > 0 ? "warning" : "base"
1837
+ });
1838
+ }
1768
1839
  }
1769
1840
  if (data.gap.providers.length > 1) {
1770
1841
  lines.push({ text: "", tone: "muted" });
1771
- lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
1772
- const providerWidths = [26, 8, 9, 9];
1773
- lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
1774
- for (const row of data.gap.providers.slice(0, 8)) {
1775
- lines.push({
1776
- text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
1777
- tone: "base"
1778
- });
1842
+ push("reuse kept, by provider", HEADER_TONE);
1843
+ const providers = data.gap.providers;
1844
+ const reuse = fitTable([
1845
+ { header: "provider", width: 12, max: 30, cell: (row) => row.provider },
1846
+ { header: "pairs", width: 6, align: "right", cell: (row) => formatCount(row.samples) },
1847
+ { header: "kept", width: 7, align: "right", cell: (row) => formatPercent(row.retainedRatio, 0) },
1848
+ { header: "lost", width: 8, align: "right", cell: (row) => formatTokens(row.lostTokens) }
1849
+ ], width);
1850
+ if (reuse.length > 0) {
1851
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
1852
+ for (const row of providers.slice(0, 8)) {
1853
+ lines.push({
1854
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
1855
+ tone: "base"
1856
+ });
1857
+ }
1779
1858
  }
1780
1859
  }
1781
1860
  }
1782
1861
  lines.push({ text: "", tone: "muted" });
1783
- lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
1862
+ push("observed cache TTL bounds", HEADER_TONE);
1784
1863
  if (data.evidence.length === 0) {
1785
- lines.push({ text: " no comparable step pairs yet", tone: "muted" });
1864
+ push(" no comparable step pairs yet", "muted");
1786
1865
  } else {
1787
- const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
1788
- lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
1789
- for (const row of data.evidence.slice(0, 10)) {
1790
- lines.push({
1791
- text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
1792
- tone: "base"
1793
- });
1866
+ const evidence = fitTable([
1867
+ { header: "model", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },
1868
+ { header: "hits up to", width: 10, align: "right", cell: (row) => formatGap(row.maxHitGapMs) },
1869
+ { header: "drops from", width: 10, align: "right", cell: (row) => formatGap(row.minDropGapMs) },
1870
+ { header: "samples", width: 7, align: "right", priority: 1, cell: (row) => formatCount(row.samples) }
1871
+ ], width);
1872
+ if (evidence.length > 0) {
1873
+ lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: "muted" });
1874
+ for (const row of data.evidence.slice(0, 10)) {
1875
+ lines.push({
1876
+ text: formatTableRow(evidence.map((column) => column.cell(row)), evidence.map((column) => column.width), evidence.map((column) => column.align)),
1877
+ tone: "base"
1878
+ });
1879
+ }
1794
1880
  }
1795
1881
  }
1796
1882
  if (data.drops.length > 0) {
1797
1883
  lines.push({ text: "", tone: "muted" });
1798
- lines.push({ text: "recent losses", tone: HEADER_TONE });
1799
- for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
1800
- const when = new Date(drop.at).toLocaleTimeString("en-GB");
1801
- lines.push({
1802
- 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"]),
1803
- tone: drop.reason === "expired" ? "warning" : "base"
1804
- });
1884
+ push("recent losses", HEADER_TONE);
1885
+ const losses = fitTable([
1886
+ { header: "when", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString("en-GB") },
1887
+ { header: "provider/model", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? ""}/${drop.modelID ?? ""}` },
1888
+ { header: "tokens", width: 7, align: "right", cell: (drop) => `\u2212${formatTokens(drop.tokens)}` },
1889
+ { header: "idle", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}` }
1890
+ ], width);
1891
+ if (losses.length > 0) {
1892
+ lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: "muted" });
1893
+ for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {
1894
+ lines.push({
1895
+ text: formatTableRow(losses.map((column) => column.cell(drop)), losses.map((column) => column.width), losses.map((column) => column.align)),
1896
+ tone: drop.reason === "expired" ? "warning" : "base"
1897
+ });
1898
+ }
1805
1899
  }
1806
1900
  }
1807
1901
  return lines;
@@ -1822,110 +1916,183 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true, tot
1822
1916
  }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
1823
1917
  const overall = usageBuckets(totals);
1824
1918
  lines.push({
1825
- text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
1919
+ text: truncate(`${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`, width),
1826
1920
  tone: "muted"
1827
1921
  });
1828
1922
  if (rows.length > 1) {
1829
- lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
1830
- lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
1923
+ const bars = Math.max(4, width - 8);
1924
+ lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: "muted" });
1925
+ lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: "muted" });
1831
1926
  lines.push({
1832
- text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
1927
+ text: truncate(`cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)), bars)}`, width),
1833
1928
  tone: "muted"
1834
1929
  });
1835
1930
  }
1836
- const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
1837
- const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
1838
- const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
1839
- const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
1840
- lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
1931
+ const columns = fitTable([
1932
+ { header: "period", width: 10, max: 24, cell: (row) => row.label },
1933
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
1934
+ { header: "sess", width: 6, align: "right", priority: 5, cell: (row) => row.sessions },
1935
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
1936
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
1937
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
1938
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
1939
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
1940
+ ], width);
1941
+ if (columns.length === 0)
1942
+ return [...lines, { text: truncate("no room for a table at this width", width), tone: "muted" }];
1943
+ const header = formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align));
1944
+ lines.push({ text: header, tone: HEADER_TONE });
1841
1945
  const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
1842
1946
  for (const row of newest) {
1843
1947
  const buckets = usageBuckets(row.usage);
1844
- const cells = [
1845
- row.label,
1846
- formatCount(row.steps),
1847
- ...withSessions ? [formatCount(row.sessions)] : [],
1848
- formatTokens(buckets.prompt),
1849
- formatTokens(buckets.cached),
1850
- formatPercent(buckets.hit, 0),
1851
- formatTokens(buckets.output),
1852
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1853
- ];
1854
- lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
1948
+ const view = {
1949
+ label: row.label,
1950
+ steps: formatCount(row.steps),
1951
+ sessions: formatCount(row.sessions),
1952
+ prompt: formatTokens(buckets.prompt),
1953
+ cached: formatTokens(buckets.cached),
1954
+ hit: formatPercent(buckets.hit, 0),
1955
+ output: formatTokens(buckets.output),
1956
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1957
+ };
1958
+ lines.push({
1959
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
1960
+ tone: "base",
1961
+ row: { kind: "period", value: row.key }
1962
+ });
1855
1963
  }
1856
1964
  lines.push({ text: "", tone: "muted" });
1965
+ const total = {
1966
+ label: "total",
1967
+ steps: formatCount(totals.steps),
1968
+ sessions: formatCount(totalSessions ?? totals.sessions),
1969
+ prompt: formatTokens(overall.prompt),
1970
+ cached: formatTokens(overall.cached),
1971
+ hit: formatPercent(overall.hit, 0),
1972
+ output: formatTokens(overall.output),
1973
+ cost: formatSpend(overall.cost, estimates ? overall.listCost : 0)
1974
+ };
1857
1975
  lines.push({
1858
- text: formatTableRow([
1859
- "total",
1860
- formatCount(totals.steps),
1861
- ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
1862
- formatTokens(overall.prompt),
1863
- formatTokens(overall.cached),
1864
- formatPercent(overall.hit, 0),
1865
- formatTokens(overall.output),
1866
- formatSpend(overall.cost, estimates ? overall.listCost : 0)
1867
- ], widths, aligns),
1976
+ text: formatTableRow(columns.map((column) => column.cell(total)), columns.map((column) => column.width), columns.map((column) => column.align)),
1868
1977
  tone: HEADER_TONE
1869
1978
  });
1870
1979
  if (rows.length === 0)
1871
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
1980
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
1872
1981
  return lines;
1873
1982
  }
1983
+ function latencyMetric(label, values, width) {
1984
+ const prefix = padCell(label, 11);
1985
+ let text = `${prefix}${values[0] ?? "\u2013"}`;
1986
+ for (let index = 1;index < values.length; index += 1) {
1987
+ const next = `${text} \xB7 ${values[index]}`;
1988
+ if (next.length > width)
1989
+ break;
1990
+ text = next;
1991
+ }
1992
+ return text;
1993
+ }
1874
1994
  function latencyLines(report, width, groups, limit = 12, estimates = true) {
1875
1995
  const lines = [];
1996
+ if (width >= 68) {
1997
+ lines.push({
1998
+ 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]),
1999
+ tone: "base"
2000
+ });
2001
+ lines.push({
2002
+ 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]),
2003
+ tone: "base"
2004
+ });
2005
+ lines.push({
2006
+ 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]),
2007
+ tone: "base"
2008
+ });
2009
+ lines.push({
2010
+ 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]),
2011
+ tone: "base"
2012
+ });
2013
+ lines.push({
2014
+ 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]),
2015
+ tone: "base"
2016
+ });
2017
+ } else {
2018
+ lines.push({
2019
+ text: latencyMetric("wall", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),
2020
+ tone: "base"
2021
+ });
2022
+ lines.push({
2023
+ text: latencyMetric("stream", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),
2024
+ tone: "base"
2025
+ });
2026
+ lines.push({
2027
+ text: latencyMetric("ttft", [`p50 ${formatMs(report.ttft.p50)}`, `p90 ${formatMs(report.ttft.p90)}`, `p99 ${formatMs(report.ttft.p99)}`], width),
2028
+ tone: "base"
2029
+ });
2030
+ lines.push({
2031
+ text: latencyMetric("tps", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
2032
+ tone: "base"
2033
+ });
2034
+ lines.push({
2035
+ text: latencyMetric("rtps", [`p50 ${formatTps(report.requestTps.p50)}`, `p90 ${formatTps(report.requestTps.p90)}`, `p99 ${formatTps(report.requestTps.p99)}`], width),
2036
+ tone: "base"
2037
+ });
2038
+ }
2039
+ lines.push({ text: "", tone: "muted" });
1876
2040
  lines.push({
1877
- 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]),
1878
- tone: "base"
1879
- });
1880
- lines.push({
1881
- 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]),
1882
- tone: "base"
1883
- });
1884
- lines.push({
1885
- 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]),
1886
- tone: "base"
2041
+ text: truncate("wall = request to completed \xB7 stream = request to last chunk", width),
2042
+ tone: "muted"
1887
2043
  });
1888
- lines.push({ text: "", tone: "muted" });
1889
2044
  lines.push({
1890
- text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
2045
+ text: truncate("ttft = request to first token \xB7 tps = first token to last chunk \xB7 rtps = request to last chunk", width),
1891
2046
  tone: "muted"
1892
2047
  });
1893
2048
  if (report.wall.count === 0)
1894
- lines.push({ text: "no completed steps for this range", tone: "muted" });
2049
+ lines.push({ text: truncate("no completed steps for this range", width), tone: "muted" });
1895
2050
  if (groups !== undefined && groups.length > 0) {
1896
2051
  lines.push({ text: "", tone: "muted" });
1897
2052
  lines.push({ text: "by group", tone: HEADER_TONE });
1898
- const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
1899
- const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
1900
- lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
1901
- for (const row of groups.slice(0, limit)) {
1902
- const thin = row.count < 5;
1903
- lines.push({
1904
- text: formatTableRow([
1905
- row.label,
1906
- formatCount(row.count),
1907
- formatMs(row.wall.p50),
1908
- formatMs(row.wall.p90),
1909
- formatMs(row.stream.p50),
1910
- formatTps(row.tps.p50),
1911
- formatTps(row.tps.p90),
1912
- formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
1913
- ], widths, aligns),
1914
- tone: thin ? "muted" : "base",
1915
- row: { kind: "model", value: row.key }
1916
- });
2053
+ const columns = fitTable([
2054
+ { header: "group", width: 8, max: 32, cell: (row) => row.label },
2055
+ { header: "n", width: 4, align: "right", cell: (row) => formatCount(row.count) },
2056
+ { header: "wall p50", width: 8, align: "right", cell: (row) => formatMs(row.wall.p50) },
2057
+ { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
2058
+ { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
2059
+ { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
2060
+ { header: "tps p90", width: 8, max: 9, align: "right", priority: 4, cell: (row) => formatTps(row.tps.p90) },
2061
+ { header: "ttft p50", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatMs(row.ttft.p50) },
2062
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2063
+ ], width);
2064
+ if (columns.length > 0) {
2065
+ lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: "muted" });
2066
+ for (const row of groups.slice(0, limit)) {
2067
+ const thin = row.count < 5;
2068
+ lines.push({
2069
+ text: formatTableRow(columns.map((column) => column.cell(row)), columns.map((column) => column.width), columns.map((column) => column.align)),
2070
+ tone: thin ? "muted" : "base",
2071
+ row: { kind: "model", value: row.key }
2072
+ });
2073
+ }
1917
2074
  }
1918
- lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
2075
+ lines.push({ text: truncate("n < 5 is dimmed: too few samples to compare", width), tone: "muted" });
1919
2076
  }
1920
2077
  return lines;
1921
2078
  }
1922
2079
  function sessionsLines(rows, width, options) {
1923
2080
  const limit = options?.limit ?? 20;
1924
2081
  const estimates = options?.estimates !== false;
1925
- const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
1926
- const aligns = ["left", "right", "right", "right", "right", "right", "right"];
2082
+ const columns = fitTable([
2083
+ { header: "title", width: 10, max: 48, cell: (row) => row.title },
2084
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
2085
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
2086
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
2087
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
2088
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
2089
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
2090
+ ], width);
1927
2091
  const lines = [
1928
- { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
2092
+ {
2093
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
2094
+ tone: HEADER_TONE
2095
+ }
1929
2096
  ];
1930
2097
  const byID = new Map(rows.map((row) => [row.sessionID, row]));
1931
2098
  const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
@@ -1933,18 +2100,18 @@ function sessionsLines(rows, width, options) {
1933
2100
  const orderedAll = [...ordered, ...children];
1934
2101
  for (const row of orderedAll.slice(0, limit)) {
1935
2102
  const child = row.parentID !== undefined && byID.has(row.parentID);
1936
- const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
1937
2103
  const buckets = usageBuckets(row);
2104
+ const view = {
2105
+ title: `${child ? "\u21B3 " : ""}${row.title ?? row.sessionID}`,
2106
+ steps: formatCount(buckets.steps),
2107
+ prompt: formatTokens(buckets.prompt),
2108
+ cached: formatTokens(buckets.cached),
2109
+ hit: formatPercent(buckets.hit, 0),
2110
+ output: formatTokens(buckets.output),
2111
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2112
+ };
1938
2113
  lines.push({
1939
- text: formatTableRow([
1940
- `${child ? "\u21B3 " : ""}${title}`,
1941
- formatCount(buckets.steps),
1942
- formatTokens(buckets.prompt),
1943
- formatTokens(buckets.cached),
1944
- formatPercent(buckets.hit, 0),
1945
- formatTokens(buckets.output),
1946
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1947
- ], widths, aligns),
2114
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
1948
2115
  tone: child ? "muted" : "base",
1949
2116
  row: { kind: "session", value: row.sessionID }
1950
2117
  });
@@ -1959,14 +2126,14 @@ function sessionsLines(rows, width, options) {
1959
2126
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
1960
2127
  lines.push({ text: "", tone: "muted" });
1961
2128
  lines.push({
1962
- 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)}`,
2129
+ 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),
1963
2130
  tone: "muted"
1964
2131
  });
1965
2132
  }
1966
2133
  if (rows.length > limit)
1967
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
2134
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, width), tone: "muted" });
1968
2135
  if (rows.length === 0)
1969
- lines.push({ text: "no sessions recorded for this range", tone: "muted" });
2136
+ lines.push({ text: truncate("no sessions recorded for this range", width), tone: "muted" });
1970
2137
  return lines;
1971
2138
  }
1972
2139
  function dbLines(data, width) {
@@ -1974,16 +2141,16 @@ function dbLines(data, width) {
1974
2141
  const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
1975
2142
  lines.push({ text: truncate(data.info.path, width), tone: "base" });
1976
2143
  lines.push({
1977
- text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
2144
+ text: truncate(`${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`, width),
1978
2145
  tone: "muted"
1979
2146
  });
1980
2147
  lines.push({ text: "", tone: "muted" });
1981
2148
  lines.push({ text: "what it holds", tone: HEADER_TONE });
1982
2149
  for (const table of data.info.tables) {
1983
- lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
2150
+ lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? "muted" : "base" });
1984
2151
  }
1985
2152
  lines.push({
1986
- 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")}`,
2153
+ 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),
1987
2154
  tone: "muted"
1988
2155
  });
1989
2156
  lines.push({ text: "", tone: "muted" });
@@ -1999,7 +2166,7 @@ function dbLines(data, width) {
1999
2166
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
2000
2167
  });
2001
2168
  }
2002
- const widths = [10, 13, 10];
2169
+ const widths = [9, 11, 10];
2003
2170
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
2004
2171
  for (const option of data.info.removable) {
2005
2172
  const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
@@ -2019,7 +2186,7 @@ function dbLines(data, width) {
2019
2186
  });
2020
2187
  if (data.busy === true) {
2021
2188
  lines.push({ text: "", tone: "muted" });
2022
- lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
2189
+ lines.push({ text: truncate("the recorder is writing: try the vacuum again in a moment", width), tone: "warning" });
2023
2190
  }
2024
2191
  return lines;
2025
2192
  }
@@ -2043,28 +2210,74 @@ function turnStats(turn) {
2043
2210
  steps: turn.steps
2044
2211
  };
2045
2212
  }
2213
+ function compactTurnLine(stats, width, options) {
2214
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
2215
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
2216
+ const estimates = options?.estimates !== false;
2217
+ const headParts = [];
2218
+ if (fields.clock && stats.endAt !== undefined)
2219
+ headParts.push(formatClock(stats.endAt));
2220
+ if (stats.providerID !== undefined) {
2221
+ let identity = stats.providerID;
2222
+ if (fields.model && stats.modelID !== undefined)
2223
+ identity += `/${stats.modelID}`;
2224
+ if (fields.variant && stats.variant)
2225
+ identity += ` ${stats.variant}`;
2226
+ headParts.push(identity);
2227
+ }
2228
+ let head = headParts.join(" ");
2229
+ const totals = options?.turnTotals === "sum" ? stats.totals : stats.latest;
2230
+ const display = displayTotals(totals);
2231
+ const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined;
2232
+ const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim();
2233
+ const warning = fields.cacheExpiry && stats.cacheExpired ? `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` \xD7${stats.drops.length}` : ""})` : undefined;
2234
+ let suffix = [warning, cost].filter((part) => part !== undefined).join(" \xB7 ");
2235
+ if (suffix !== "" && suffix.length + 3 > width)
2236
+ suffix = cost ?? suffix;
2237
+ head = truncate(head, Math.max(0, width - (suffix === "" ? 0 : suffix.length + 3)));
2238
+ if (!fields.turn || stats.totals.steps === 0)
2239
+ return [head, suffix].filter((part) => part !== "").join(" \xB7 ");
2240
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
2241
+ const volumes = [
2242
+ input,
2243
+ `${labels.cached} ${formatTokens(display.cached)}`,
2244
+ `${labels.output} ${formatTokens(display.output)}`,
2245
+ ...fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []
2246
+ ];
2247
+ let numbers = "";
2248
+ for (const volume of volumes) {
2249
+ const next = numbers === "" ? volume : `${numbers}, ${volume}`;
2250
+ if ([head, next, suffix].filter((part) => part !== "").join(" \xB7 ").length > width)
2251
+ break;
2252
+ numbers = next;
2253
+ }
2254
+ return [head, numbers, suffix].filter((part) => part !== "").join(" \xB7 ");
2255
+ }
2046
2256
  function turnsLines(rows, width, options) {
2047
2257
  const lines = [];
2048
2258
  const warning = rows.filter((turn) => turn.drops.length > 0).length;
2049
2259
  lines.push({
2050
- text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
2260
+ text: truncate(`${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`, width),
2051
2261
  tone: "muted"
2052
2262
  });
2053
2263
  const showSession = options?.sessionTitles !== undefined;
2054
2264
  for (const turn of rows) {
2055
- const line = formatLine(turnStats(turn), {
2265
+ const stats = turnStats(turn);
2266
+ const line = formatLine(stats, {
2056
2267
  ...options,
2057
2268
  fields: { ...options?.fields, session: false }
2058
2269
  });
2059
2270
  const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
2271
+ const available = Math.max(0, width - title.length);
2272
+ const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`;
2060
2273
  lines.push({
2061
- text: truncate(`${title}${line}`, width),
2274
+ text: truncate(text, width),
2062
2275
  tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
2063
2276
  row: { kind: "turn", value: turn.sessionID }
2064
2277
  });
2065
2278
  }
2066
2279
  if (rows.length === 0)
2067
- lines.push({ text: "no finished turns for this range", tone: "muted" });
2280
+ lines.push({ text: truncate("no finished turns for this range", width), tone: "muted" });
2068
2281
  return lines;
2069
2282
  }
2070
2283
  function sessionSummaryLines(usage, budget = 34, estimates = true) {
@@ -2074,7 +2287,9 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
2074
2287
  const cached = formatTokens(buckets.cached);
2075
2288
  const out = formatTokens(buckets.output);
2076
2289
  const hit = formatPercent(buckets.hit);
2077
- const tps = formatTpsCompact(usage.tps);
2290
+ const tps = usage.tps === undefined ? undefined : `${formatRateValue(usage.tps)} tps`;
2291
+ const rtps = usage.requestTps === undefined ? undefined : `${formatRateValue(usage.requestTps)} rtps`;
2292
+ const ttft = usage.ttft === undefined ? undefined : `ttft p50 ${formatMs(usage.ttft)}`;
2078
2293
  const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
2079
2294
  const first = [
2080
2295
  ` ${steps} steps \xB7 in ${input}`,
@@ -2084,16 +2299,22 @@ function sessionSummaryLines(usage, budget = 34, estimates = true) {
2084
2299
  ` cached ${cached} \xB7 out ${out}`,
2085
2300
  ` cached ${cached}`
2086
2301
  ].find((text) => text.length <= budget);
2087
- const last = [
2088
- ` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
2089
- ` hit ${hit} \xB7 ${cost}`,
2090
- ` ${cost}`
2302
+ const rates = [tps, rtps].filter((part) => part !== undefined);
2303
+ const rateLine = [
2304
+ ` hit ${hit}${rates.length > 0 ? ` \xB7 ${rates.join(" \xB7 ")}` : ""}`,
2305
+ ` hit ${hit}${rates[0] !== undefined ? ` \xB7 ${rates[0]}` : ""}`,
2306
+ ` hit ${hit}`
2091
2307
  ].find((text) => text.length <= budget);
2308
+ const tail = [
2309
+ ttft === undefined ? undefined : ` ${ttft} \xB7 ${cost}`,
2310
+ ` ${cost}`
2311
+ ].filter((text) => text !== undefined).find((text) => text.length <= budget);
2092
2312
  return [
2093
2313
  { text: truncate("session", budget), tone: HEADER_TONE },
2094
2314
  { text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
2095
2315
  { text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
2096
- { text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
2316
+ { text: truncate(rateLine ?? ` hit ${hit}`, budget), tone: "base" },
2317
+ { text: truncate(tail ?? ` ${cost}`, budget), tone: "base" },
2097
2318
  { text: "", tone: "muted" }
2098
2319
  ];
2099
2320
  }
@@ -2110,20 +2331,28 @@ function sidebarLines(rows, options) {
2110
2331
  const output = formatTokens(display.output);
2111
2332
  const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
2112
2333
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
2113
- const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
2334
+ const tps = turn.tps === undefined ? undefined : `${formatRateValue(turn.tps)} tps`;
2335
+ const ttft = turn.ttft === undefined ? undefined : `${formatMs(turn.ttft)} ttft`;
2336
+ const rate = [tps, ttft].filter((part) => part !== undefined).join(" \xB7 ");
2114
2337
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
2115
2338
  const header = `${clock} ${provider}`;
2116
2339
  const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
2340
+ const join = (...parts) => parts.filter((part) => part !== undefined && part !== "").join(" \xB7 ");
2117
2341
  const volumes = [
2118
- ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
2342
+ ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
2343
+ ` ${labels.input} ${input} \xB7 ${labels.output} ${output} \xB7 hit ${hit}`,
2119
2344
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
2120
2345
  ` ${labels.input} ${input}`
2121
2346
  ];
2347
+ const volume = volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1];
2348
+ const hitPart = volume.includes(`hit ${hit}`) ? undefined : `hit ${hit}`;
2122
2349
  const facts = [
2123
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
2124
- ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
2125
- ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
2126
- ` hit ${hit}${suffix}`
2350
+ ` ${join(hitPart, rate, `${cost}${suffix}`)}`,
2351
+ ` ${join(hitPart, tps, `${cost}${suffix}`)}`,
2352
+ ` ${join(tps, `${cost}${suffix}`)}`,
2353
+ ` ${join(tps)}`,
2354
+ ` ${join(hitPart, `${cost}${suffix}`)}`,
2355
+ ` ${join(`${cost}${suffix}`)}`
2127
2356
  ];
2128
2357
  lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
2129
2358
  const edge = index === 0 || index === rows.length - 1;
@@ -2131,10 +2360,7 @@ function sidebarLines(rows, options) {
2131
2360
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
2132
2361
  lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
2133
2362
  }
2134
- lines.push({
2135
- text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
2136
- tone: "muted"
2137
- });
2363
+ lines.push({ text: truncate(volume, budget), tone: "muted" });
2138
2364
  lines.push({
2139
2365
  text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
2140
2366
  tone: turn.drops.length > 0 ? "warning" : "muted"
@@ -2157,6 +2383,21 @@ import { createElement as _$createElement } from "@opentui/solid";
2157
2383
  import { TextAttributes } from "@opentui/core";
2158
2384
  import { For, Show, createEffect, createMemo, createRenderEffect, createSignal } from "solid-js";
2159
2385
 
2386
+ // src/limits.ts
2387
+ var MAX_PANEL_WIDTH = 200;
2388
+ var MAX_HISTORY_WIDTH = 120;
2389
+ var MAX_TURNS = 50;
2390
+ function clampPanelWidth(value) {
2391
+ if (!Number.isFinite(value))
2392
+ return 20;
2393
+ return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
2394
+ }
2395
+ function clampTurnsLimit(value) {
2396
+ if (!Number.isFinite(value))
2397
+ return 1;
2398
+ return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
2399
+ }
2400
+
2160
2401
  // src/rpc.ts
2161
2402
  import { Rpc } from "@opencode/plugin/rpc";
2162
2403
  var Tone = { type: "string", enum: ["base", "muted", "warning", "accent"] };
@@ -2240,10 +2481,10 @@ var PruneResultSchema = {
2240
2481
  properties: {
2241
2482
  steps: { type: "number" },
2242
2483
  prompts: { type: "number" },
2243
- events: { type: "number" },
2484
+ compactions: { type: "number" },
2244
2485
  usage: { type: "number" }
2245
2486
  },
2246
- required: ["steps", "prompts", "events", "usage"],
2487
+ required: ["steps", "prompts", "compactions", "usage"],
2247
2488
  additionalProperties: false
2248
2489
  };
2249
2490
  var WipeResultSchema = {
@@ -2251,11 +2492,11 @@ var WipeResultSchema = {
2251
2492
  properties: {
2252
2493
  steps: { type: "number" },
2253
2494
  prompts: { type: "number" },
2254
- events: { type: "number" },
2495
+ compactions: { type: "number" },
2255
2496
  usage: { type: "number" },
2256
2497
  sessions: { type: "number" }
2257
2498
  },
2258
- required: ["steps", "prompts", "events", "usage", "sessions"],
2499
+ required: ["steps", "prompts", "compactions", "usage", "sessions"],
2259
2500
  additionalProperties: false
2260
2501
  };
2261
2502
  var BackfillResultSchema = {
@@ -2322,7 +2563,7 @@ var UsageInsights = Rpc.define({
2322
2563
  properties: {
2323
2564
  sessionID: { type: "string", maxLength: 200 },
2324
2565
  limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
2325
- width: { type: "number", minimum: 20, maximum: 120 }
2566
+ width: { type: "number", minimum: 20, maximum: MAX_HISTORY_WIDTH }
2326
2567
  },
2327
2568
  required: ["sessionID", "limit", "width"],
2328
2569
  additionalProperties: false
@@ -2655,7 +2896,7 @@ function Panel(props) {
2655
2896
  confirm: true
2656
2897
  });
2657
2898
  props.ctx.ui.toast.show({
2658
- message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
2899
+ message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.compactions} compactions \xB7 ${result.usage} other usage`,
2659
2900
  variant: "success"
2660
2901
  });
2661
2902
  } catch (cause) {
@@ -2701,7 +2942,7 @@ function Panel(props) {
2701
2942
  confirm: true
2702
2943
  });
2703
2944
  props.ctx.ui.toast.show({
2704
- message: `wiped ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage \xB7 ${result.sessions} sessions`,
2945
+ message: `wiped ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.compactions} compactions \xB7 ${result.usage} other usage \xB7 ${result.sessions} sessions`,
2705
2946
  variant: "success"
2706
2947
  });
2707
2948
  } catch (cause) {
@@ -3150,6 +3391,383 @@ async function fetchGoQuota(client, location, signal) {
3150
3391
  return normalizeQuota(data, Date.now());
3151
3392
  }
3152
3393
 
3394
+ // src/settings-rpc.ts
3395
+ import { Rpc as Rpc2 } from "@opencode/plugin/rpc";
3396
+
3397
+ // src/settings.ts
3398
+ var SETTINGS_STORAGE_KEY = "settings";
3399
+ var MAX_LABEL_LENGTH = 80;
3400
+ var MAX_QUOTA_NAME_LENGTH = 120;
3401
+ var DEFAULT_SIDEBAR_TURNS = 8;
3402
+ var TURN_TOTALS = ["latest", "sum"];
3403
+ var FIELD_KEYS = Object.keys(DEFAULT_FIELDS);
3404
+ var LABEL_KEYS = Object.keys(DEFAULT_LABELS);
3405
+ var DEFAULT_SERVER_POLICY = {
3406
+ maintenance: true,
3407
+ exposePaths: false
3408
+ };
3409
+ var DEFAULT_USAGE_SETTINGS = {
3410
+ pricing: true,
3411
+ turnTotals: "latest",
3412
+ fields: { ...DEFAULT_FIELDS },
3413
+ labels: { ...DEFAULT_LABELS },
3414
+ panel: true,
3415
+ sidebar: true,
3416
+ sidebarTurns: DEFAULT_SIDEBAR_TURNS,
3417
+ quota: true,
3418
+ quotaName: ""
3419
+ };
3420
+ function defaultUsageSettings() {
3421
+ return {
3422
+ ...DEFAULT_USAGE_SETTINGS,
3423
+ fields: { ...DEFAULT_USAGE_SETTINGS.fields },
3424
+ labels: { ...DEFAULT_USAGE_SETTINGS.labels }
3425
+ };
3426
+ }
3427
+ function defaultSettingsEnvelope(policy = DEFAULT_SERVER_POLICY) {
3428
+ return { settings: defaultUsageSettings(), policy: { ...policy } };
3429
+ }
3430
+ function isRecord(value) {
3431
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3432
+ }
3433
+ function sanitizeSidebarTurns(value) {
3434
+ if (typeof value === "number" && Number.isFinite(value))
3435
+ return clampTurnsLimit(value);
3436
+ if (typeof value === "string" && value.trim() !== "") {
3437
+ const parsed = Number(value);
3438
+ if (Number.isFinite(parsed))
3439
+ return clampTurnsLimit(parsed);
3440
+ }
3441
+ return DEFAULT_SIDEBAR_TURNS;
3442
+ }
3443
+ function sanitizeLabels(value) {
3444
+ const labels = { ...DEFAULT_LABELS };
3445
+ if (!isRecord(value))
3446
+ return labels;
3447
+ for (const key of LABEL_KEYS) {
3448
+ const entry = value[key];
3449
+ if (typeof entry === "string")
3450
+ labels[key] = sanitizeText(entry, MAX_LABEL_LENGTH);
3451
+ }
3452
+ return labels;
3453
+ }
3454
+ function sanitizeFields(value) {
3455
+ const fields = { ...DEFAULT_FIELDS };
3456
+ if (!isRecord(value))
3457
+ return fields;
3458
+ for (const key of FIELD_KEYS) {
3459
+ const entry = value[key];
3460
+ if (typeof entry === "boolean")
3461
+ fields[key] = entry;
3462
+ }
3463
+ return fields;
3464
+ }
3465
+ function sanitizeUsageSettings(value) {
3466
+ if (!isRecord(value))
3467
+ return defaultUsageSettings();
3468
+ return {
3469
+ pricing: typeof value.pricing === "boolean" ? value.pricing : DEFAULT_USAGE_SETTINGS.pricing,
3470
+ turnTotals: TURN_TOTALS.includes(value.turnTotals) ? value.turnTotals : DEFAULT_USAGE_SETTINGS.turnTotals,
3471
+ fields: sanitizeFields(value.fields),
3472
+ labels: sanitizeLabels(value.labels),
3473
+ panel: typeof value.panel === "boolean" ? value.panel : DEFAULT_USAGE_SETTINGS.panel,
3474
+ sidebar: typeof value.sidebar === "boolean" ? value.sidebar : DEFAULT_USAGE_SETTINGS.sidebar,
3475
+ sidebarTurns: sanitizeSidebarTurns(value.sidebarTurns),
3476
+ quota: typeof value.quota === "boolean" ? value.quota : DEFAULT_USAGE_SETTINGS.quota,
3477
+ quotaName: typeof value.quotaName === "string" ? sanitizeText(value.quotaName.trim(), MAX_QUOTA_NAME_LENGTH) : DEFAULT_USAGE_SETTINGS.quotaName
3478
+ };
3479
+ }
3480
+ function sanitizeServerPolicy(value) {
3481
+ if (!isRecord(value))
3482
+ return { ...DEFAULT_SERVER_POLICY };
3483
+ return {
3484
+ maintenance: typeof value.maintenance === "boolean" ? value.maintenance : DEFAULT_SERVER_POLICY.maintenance,
3485
+ exposePaths: typeof value.exposePaths === "boolean" ? value.exposePaths : DEFAULT_SERVER_POLICY.exposePaths
3486
+ };
3487
+ }
3488
+ function sanitizeSettingsEnvelope(value) {
3489
+ return {
3490
+ settings: sanitizeUsageSettings(isRecord(value) ? value.settings : undefined),
3491
+ policy: sanitizeServerPolicy(isRecord(value) ? value.policy : undefined)
3492
+ };
3493
+ }
3494
+ function mergeUsageSettings(current, patch) {
3495
+ const next = {
3496
+ ...current,
3497
+ ...typeof patch.pricing === "boolean" ? { pricing: patch.pricing } : {},
3498
+ ...TURN_TOTALS.includes(patch.turnTotals) ? { turnTotals: patch.turnTotals } : {},
3499
+ ...isRecord(patch.fields) ? { fields: { ...current.fields, ...patch.fields } } : {},
3500
+ ...isRecord(patch.labels) ? { labels: { ...current.labels, ...patch.labels } } : {},
3501
+ ...typeof patch.panel === "boolean" ? { panel: patch.panel } : {},
3502
+ ...typeof patch.sidebar === "boolean" ? { sidebar: patch.sidebar } : {},
3503
+ ...patch.sidebarTurns !== undefined ? { sidebarTurns: patch.sidebarTurns } : {},
3504
+ ...typeof patch.quota === "boolean" ? { quota: patch.quota } : {},
3505
+ ...typeof patch.quotaName === "string" ? { quotaName: patch.quotaName } : {}
3506
+ };
3507
+ return sanitizeUsageSettings(next);
3508
+ }
3509
+ function resolveUsageSettings(settings) {
3510
+ return {
3511
+ format: {
3512
+ labels: settings.labels,
3513
+ fields: settings.fields,
3514
+ turnTotals: settings.turnTotals,
3515
+ estimates: settings.pricing
3516
+ },
3517
+ sidebarTurns: clampTurnsLimit(settings.sidebarTurns),
3518
+ quotaName: settings.quotaName.trim() || undefined
3519
+ };
3520
+ }
3521
+ function isValidSidebarTurns(raw) {
3522
+ const value = Number(raw);
3523
+ return raw.trim() !== "" && Number.isInteger(value) && value >= 1 && value <= 50;
3524
+ }
3525
+ function parseSidebarTurns(raw) {
3526
+ if (!isValidSidebarTurns(raw))
3527
+ return;
3528
+ return clampTurnsLimit(Number(raw));
3529
+ }
3530
+ var TRUE_VALUES = new Set(["1", "true", "on", "yes", "y"]);
3531
+ var FALSE_VALUES = new Set(["0", "false", "off", "no", "n"]);
3532
+ function envFlag(value, fallback) {
3533
+ if (value === undefined || value.trim() === "")
3534
+ return fallback;
3535
+ const normalized = value.trim().toLowerCase();
3536
+ if (TRUE_VALUES.has(normalized))
3537
+ return true;
3538
+ if (FALSE_VALUES.has(normalized))
3539
+ return false;
3540
+ return fallback;
3541
+ }
3542
+ function serverPolicy(env = process.env) {
3543
+ return {
3544
+ maintenance: envFlag(env.OPENCODE_USAGE_INSIGHTS_MAINTENANCE, true),
3545
+ exposePaths: envFlag(env.OPENCODE_USAGE_INSIGHTS_EXPOSE_PATHS, false)
3546
+ };
3547
+ }
3548
+
3549
+ // src/settings-rpc.ts
3550
+ var LineFields = {
3551
+ type: "object",
3552
+ properties: {
3553
+ clock: { type: "boolean" },
3554
+ delta: { type: "boolean" },
3555
+ model: { type: "boolean" },
3556
+ variant: { type: "boolean" },
3557
+ turn: { type: "boolean" },
3558
+ session: { type: "boolean" },
3559
+ reasoning: { type: "boolean" },
3560
+ cost: { type: "boolean" },
3561
+ cacheExpiry: { type: "boolean" }
3562
+ },
3563
+ additionalProperties: false
3564
+ };
3565
+ var LineLabels = {
3566
+ type: "object",
3567
+ properties: {
3568
+ delta: { type: "string", maxLength: MAX_LABEL_LENGTH },
3569
+ turn: { type: "string", maxLength: MAX_LABEL_LENGTH },
3570
+ session: { type: "string", maxLength: MAX_LABEL_LENGTH },
3571
+ step: { type: "string", maxLength: MAX_LABEL_LENGTH },
3572
+ steps: { type: "string", maxLength: MAX_LABEL_LENGTH },
3573
+ input: { type: "string", maxLength: MAX_LABEL_LENGTH },
3574
+ cached: { type: "string", maxLength: MAX_LABEL_LENGTH },
3575
+ output: { type: "string", maxLength: MAX_LABEL_LENGTH },
3576
+ reasoning: { type: "string", maxLength: MAX_LABEL_LENGTH },
3577
+ cost: { type: "string", maxLength: MAX_LABEL_LENGTH },
3578
+ estimate: { type: "string", maxLength: MAX_LABEL_LENGTH },
3579
+ cacheExpired: { type: "string", maxLength: MAX_LABEL_LENGTH },
3580
+ providerChanged: { type: "string", maxLength: MAX_LABEL_LENGTH },
3581
+ modelChanged: { type: "string", maxLength: MAX_LABEL_LENGTH }
3582
+ },
3583
+ additionalProperties: false
3584
+ };
3585
+ var Settings = {
3586
+ type: "object",
3587
+ properties: {
3588
+ pricing: { type: "boolean" },
3589
+ turnTotals: { type: "string", enum: ["latest", "sum"] },
3590
+ fields: LineFields,
3591
+ labels: LineLabels,
3592
+ panel: { type: "boolean" },
3593
+ sidebar: { type: "boolean" },
3594
+ sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
3595
+ quota: { type: "boolean" },
3596
+ quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
3597
+ },
3598
+ required: ["pricing", "turnTotals", "fields", "labels", "panel", "sidebar", "sidebarTurns", "quota", "quotaName"],
3599
+ additionalProperties: false
3600
+ };
3601
+ var Patch = {
3602
+ type: "object",
3603
+ properties: {
3604
+ pricing: { type: "boolean" },
3605
+ turnTotals: { type: "string", enum: ["latest", "sum"] },
3606
+ fields: LineFields,
3607
+ labels: LineLabels,
3608
+ panel: { type: "boolean" },
3609
+ sidebar: { type: "boolean" },
3610
+ sidebarTurns: { type: "number", minimum: 1, maximum: 50 },
3611
+ quota: { type: "boolean" },
3612
+ quotaName: { type: "string", maxLength: MAX_QUOTA_NAME_LENGTH }
3613
+ },
3614
+ additionalProperties: false
3615
+ };
3616
+ var Policy = {
3617
+ type: "object",
3618
+ properties: {
3619
+ maintenance: { type: "boolean" },
3620
+ exposePaths: { type: "boolean" }
3621
+ },
3622
+ required: ["maintenance", "exposePaths"],
3623
+ additionalProperties: false
3624
+ };
3625
+ var Envelope = {
3626
+ type: "object",
3627
+ properties: {
3628
+ settings: Settings,
3629
+ policy: Policy
3630
+ },
3631
+ required: ["settings", "policy"],
3632
+ additionalProperties: false
3633
+ };
3634
+ var Empty = { type: "object", properties: {}, additionalProperties: false };
3635
+ var SetInput = {
3636
+ type: "object",
3637
+ properties: { patch: Patch },
3638
+ required: ["patch"],
3639
+ additionalProperties: false
3640
+ };
3641
+ var UsageInsightsSettings = Rpc2.define({
3642
+ id: "usage-insights.settings",
3643
+ methods: {
3644
+ get: { input: Empty, output: Envelope },
3645
+ set: { input: SetInput, output: Envelope },
3646
+ reset: { input: Empty, output: Envelope }
3647
+ },
3648
+ events: {
3649
+ updated: { schema: Envelope }
3650
+ }
3651
+ });
3652
+
3653
+ // src/settings-client.ts
3654
+ function settingsError(cause) {
3655
+ return cause instanceof Error ? cause.message : String(cause);
3656
+ }
3657
+ function createSettingsSync(options) {
3658
+ let stopEvents;
3659
+ let stopped = false;
3660
+ function rpc() {
3661
+ const client = options.client();
3662
+ if (typeof client.rpc !== "function")
3663
+ return;
3664
+ try {
3665
+ return client.rpc(UsageInsightsSettings);
3666
+ } catch {
3667
+ return;
3668
+ }
3669
+ }
3670
+ async function refresh(force = false) {
3671
+ const client = rpc();
3672
+ if (!client) {
3673
+ if (!stopped)
3674
+ options.onLoadError?.("the settings service is unavailable");
3675
+ return;
3676
+ }
3677
+ try {
3678
+ const next = sanitizeSettingsEnvelope(await client.get({}));
3679
+ if (stopped)
3680
+ return;
3681
+ if (!force && options.canApply && !options.canApply(next))
3682
+ return;
3683
+ options.set(next);
3684
+ } catch (cause) {
3685
+ if (!stopped)
3686
+ options.onLoadError?.(settingsError(cause));
3687
+ }
3688
+ }
3689
+ function connect() {
3690
+ stopped = false;
3691
+ stopEvents?.();
3692
+ stopEvents = undefined;
3693
+ const client = rpc();
3694
+ if (client) {
3695
+ try {
3696
+ stopEvents = client.events.on("updated", (event) => {
3697
+ if (stopped)
3698
+ return;
3699
+ try {
3700
+ const next = sanitizeSettingsEnvelope(event.data);
3701
+ if (options.acceptEvent) {
3702
+ if (!options.acceptEvent(next))
3703
+ return;
3704
+ } else if (options.canApply && !options.canApply(next)) {
3705
+ return;
3706
+ }
3707
+ if (!stopped)
3708
+ options.set(next);
3709
+ } catch (cause) {
3710
+ if (!stopped)
3711
+ options.onLoadError?.(settingsError(cause));
3712
+ }
3713
+ });
3714
+ } catch (cause) {
3715
+ options.onLoadError?.(settingsError(cause));
3716
+ }
3717
+ }
3718
+ refresh();
3719
+ }
3720
+ async function update(patch) {
3721
+ if (stopped)
3722
+ return;
3723
+ const client = rpc();
3724
+ if (!client) {
3725
+ options.onSaveError?.("the settings service is unavailable");
3726
+ return;
3727
+ }
3728
+ try {
3729
+ const saved = sanitizeSettingsEnvelope(await client.set({ patch }));
3730
+ if (!stopped)
3731
+ options.set(saved);
3732
+ } catch (cause) {
3733
+ if (stopped)
3734
+ return;
3735
+ options.onSaveError?.(settingsError(cause));
3736
+ await refresh(true);
3737
+ }
3738
+ }
3739
+ async function reset() {
3740
+ if (stopped)
3741
+ return;
3742
+ const client = rpc();
3743
+ if (!client) {
3744
+ options.onSaveError?.("the settings service is unavailable");
3745
+ return;
3746
+ }
3747
+ try {
3748
+ const saved = sanitizeSettingsEnvelope(await client.reset({}));
3749
+ if (!stopped)
3750
+ options.set(saved);
3751
+ } catch (cause) {
3752
+ if (stopped)
3753
+ return;
3754
+ options.onSaveError?.(settingsError(cause));
3755
+ await refresh(true);
3756
+ }
3757
+ }
3758
+ return {
3759
+ connect,
3760
+ refresh,
3761
+ update,
3762
+ reset,
3763
+ stop: () => {
3764
+ stopped = true;
3765
+ stopEvents?.();
3766
+ stopEvents = undefined;
3767
+ }
3768
+ };
3769
+ }
3770
+
3153
3771
  // src/sidebar.tsx
3154
3772
  import { insert as _$insert2 } from "@opentui/solid";
3155
3773
  import { effect as _$effect2 } from "@opentui/solid";
@@ -3181,7 +3799,7 @@ function TurnsSidebar(props) {
3181
3799
  props.deps.refresh();
3182
3800
  const input = {
3183
3801
  sessionID: props.sessionID,
3184
- limit: props.deps.limit,
3802
+ limit: props.deps.limit(),
3185
3803
  width: props.deps.budget ?? 34
3186
3804
  };
3187
3805
  const current = ++generation;
@@ -3253,6 +3871,294 @@ function TurnsSidebar(props) {
3253
3871
  })();
3254
3872
  }
3255
3873
 
3874
+ // src/tui-settings.ts
3875
+ var FIELD_TITLES = {
3876
+ clock: "Clock",
3877
+ delta: "Time since previous prompt",
3878
+ model: "Provider and model",
3879
+ variant: "Model variant",
3880
+ turn: "Turn label prefix",
3881
+ session: "Session totals",
3882
+ reasoning: "Reasoning tokens",
3883
+ cost: "Cost",
3884
+ cacheExpiry: "Cache expiry warning"
3885
+ };
3886
+ var LABEL_TITLES = {
3887
+ delta: "Time since previous prompt",
3888
+ turn: "Turn prefix",
3889
+ session: "Session prefix",
3890
+ step: "Single step",
3891
+ steps: "Several steps",
3892
+ input: "Uncached input",
3893
+ cached: "Cached input",
3894
+ output: "Output",
3895
+ reasoning: "Reasoning",
3896
+ cost: "Cost",
3897
+ estimate: "Estimate marker",
3898
+ cacheExpired: "Cache expired warning",
3899
+ providerChanged: "Provider changed warning",
3900
+ modelChanged: "Model changed warning"
3901
+ };
3902
+ function onOff(value) {
3903
+ return value ? "on" : "off";
3904
+ }
3905
+ function fieldsSummary(settings) {
3906
+ const enabled = Object.keys(DEFAULT_FIELDS).filter((key) => settings.fields[key]).length;
3907
+ return `${enabled}/${Object.keys(DEFAULT_FIELDS).length} on`;
3908
+ }
3909
+ function labelsSummary(settings) {
3910
+ const custom = Object.keys(DEFAULT_LABELS).filter((key) => {
3911
+ const name = key;
3912
+ return settings.labels[name] !== DEFAULT_LABELS[name];
3913
+ }).length;
3914
+ return custom === 0 ? "defaults" : `${custom} custom`;
3915
+ }
3916
+ async function openUsageInsightsSettings(ctx, state) {
3917
+ for (;; ) {
3918
+ const current = state.settings();
3919
+ const error = state.error();
3920
+ const choice = await ctx.ui.dialog.select({
3921
+ title: "Usage insights settings",
3922
+ placeholder: "Filter settings",
3923
+ options: [
3924
+ ...error === undefined ? [] : [
3925
+ {
3926
+ title: "Settings service unavailable",
3927
+ value: "done",
3928
+ description: error,
3929
+ category: "Connection",
3930
+ disabled: true
3931
+ },
3932
+ {
3933
+ title: "Retry connection",
3934
+ value: "retry",
3935
+ description: "Reload the shared settings",
3936
+ category: "Connection"
3937
+ }
3938
+ ],
3939
+ {
3940
+ title: "List-price estimates",
3941
+ value: "pricing",
3942
+ description: onOff(current.pricing),
3943
+ category: "Recording"
3944
+ },
3945
+ {
3946
+ title: "Turn totals",
3947
+ value: "turnTotals",
3948
+ description: current.turnTotals === "sum" ? "sum every step" : "latest step",
3949
+ category: "Line"
3950
+ },
3951
+ {
3952
+ title: "Fields",
3953
+ value: "fields",
3954
+ description: fieldsSummary(current),
3955
+ category: "Line"
3956
+ },
3957
+ {
3958
+ title: "Labels",
3959
+ value: "labels",
3960
+ description: labelsSummary(current),
3961
+ category: "Line"
3962
+ },
3963
+ {
3964
+ title: "Panel",
3965
+ value: "panel",
3966
+ description: onOff(current.panel),
3967
+ category: "Surfaces"
3968
+ },
3969
+ {
3970
+ title: "Sidebar history",
3971
+ value: "sidebar",
3972
+ description: onOff(current.sidebar),
3973
+ category: "Surfaces"
3974
+ },
3975
+ {
3976
+ title: "Sidebar turns",
3977
+ value: "sidebarTurns",
3978
+ description: String(current.sidebarTurns),
3979
+ category: "Surfaces"
3980
+ },
3981
+ {
3982
+ title: "OpenCode Go allowance",
3983
+ value: "quota",
3984
+ description: onOff(current.quota),
3985
+ category: "Allowance"
3986
+ },
3987
+ {
3988
+ title: "Allowance label",
3989
+ value: "quotaName",
3990
+ description: current.quotaName || "provider default",
3991
+ category: "Allowance"
3992
+ },
3993
+ {
3994
+ title: "Server maintenance",
3995
+ value: "done",
3996
+ description: state.policy().maintenance ? "allowed" : "disabled by the server policy",
3997
+ category: "Server policy",
3998
+ disabled: true
3999
+ },
4000
+ {
4001
+ title: "Expose database paths",
4002
+ value: "done",
4003
+ description: state.policy().exposePaths ? "yes" : "no",
4004
+ category: "Server policy",
4005
+ disabled: true
4006
+ },
4007
+ {
4008
+ title: "Database path",
4009
+ value: "done",
4010
+ description: "OPENCODE_USAGE_INSIGHTS_DB",
4011
+ category: "Server policy",
4012
+ disabled: true
4013
+ },
4014
+ {
4015
+ title: "Reset to defaults",
4016
+ value: "reset",
4017
+ description: "Restore every shared setting",
4018
+ category: "Reset"
4019
+ },
4020
+ { title: "Done", value: "done", category: "Actions" }
4021
+ ]
4022
+ });
4023
+ if (choice === undefined || choice === "done")
4024
+ return;
4025
+ switch (choice) {
4026
+ case "pricing":
4027
+ await state.update({ pricing: !current.pricing });
4028
+ break;
4029
+ case "turnTotals":
4030
+ await editTurnTotals(ctx, state, current);
4031
+ break;
4032
+ case "fields":
4033
+ await editFields(ctx, state, current);
4034
+ break;
4035
+ case "labels":
4036
+ await editLabels(ctx, state, current);
4037
+ break;
4038
+ case "panel":
4039
+ await state.update({ panel: !current.panel });
4040
+ break;
4041
+ case "sidebar":
4042
+ await state.update({ sidebar: !current.sidebar });
4043
+ break;
4044
+ case "sidebarTurns":
4045
+ await editSidebarTurns(ctx, state, current);
4046
+ break;
4047
+ case "quota":
4048
+ await state.update({ quota: !current.quota });
4049
+ break;
4050
+ case "quotaName":
4051
+ await editQuotaName(ctx, state, current);
4052
+ break;
4053
+ case "retry":
4054
+ await state.refresh();
4055
+ break;
4056
+ case "reset":
4057
+ await reset(ctx, state);
4058
+ break;
4059
+ }
4060
+ }
4061
+ }
4062
+ async function editTurnTotals(ctx, state, current) {
4063
+ const value = await ctx.ui.dialog.select({
4064
+ title: "Turn totals",
4065
+ current: current.turnTotals,
4066
+ options: [
4067
+ {
4068
+ title: "Latest step",
4069
+ value: "latest",
4070
+ description: "The prompt size the turn ended with",
4071
+ category: "Current"
4072
+ },
4073
+ {
4074
+ title: "Sum every step",
4075
+ value: "sum",
4076
+ description: "Add the prompt of each step in the turn",
4077
+ category: "Current"
4078
+ }
4079
+ ]
4080
+ });
4081
+ if (value === undefined)
4082
+ return;
4083
+ await state.update({ turnTotals: value });
4084
+ }
4085
+ async function editFields(ctx, state, current) {
4086
+ const key = await ctx.ui.dialog.select({
4087
+ title: "Line fields",
4088
+ current: undefined,
4089
+ options: Object.keys(DEFAULT_FIELDS).map((name) => ({
4090
+ title: FIELD_TITLES[name],
4091
+ value: name,
4092
+ description: onOff(current.fields[name]),
4093
+ category: "Current"
4094
+ }))
4095
+ });
4096
+ if (key === undefined)
4097
+ return;
4098
+ await state.update({ fields: { [key]: !current.fields[key] } });
4099
+ }
4100
+ async function editLabels(ctx, state, current) {
4101
+ const key = await ctx.ui.dialog.select({
4102
+ title: "Line labels",
4103
+ placeholder: "Filter labels",
4104
+ current: undefined,
4105
+ options: Object.keys(DEFAULT_LABELS).map((name) => ({
4106
+ title: LABEL_TITLES[name],
4107
+ value: name,
4108
+ description: current.labels[name] || "(empty)",
4109
+ category: "Current"
4110
+ }))
4111
+ });
4112
+ if (key === undefined)
4113
+ return;
4114
+ const value = await ctx.ui.dialog.prompt({
4115
+ title: LABEL_TITLES[key],
4116
+ description: "Text shown on the line. Leave it empty to hide the label.",
4117
+ value: current.labels[key]
4118
+ });
4119
+ if (value === undefined)
4120
+ return;
4121
+ await state.update({ labels: { [key]: sanitizeText(value, MAX_LABEL_LENGTH) } });
4122
+ }
4123
+ async function editSidebarTurns(ctx, state, current) {
4124
+ const value = await ctx.ui.dialog.prompt({
4125
+ title: "Sidebar turns",
4126
+ description: "How many turns the TUI sidebar and the Desktop Turns tab show (1-50).",
4127
+ value: String(current.sidebarTurns)
4128
+ });
4129
+ if (value === undefined)
4130
+ return;
4131
+ const turns = parseSidebarTurns(value);
4132
+ if (turns === undefined) {
4133
+ await ctx.ui.dialog.alert({
4134
+ title: "Invalid number of turns",
4135
+ message: "Use a whole number from 1 to 50. No change was saved."
4136
+ });
4137
+ return;
4138
+ }
4139
+ await state.update({ sidebarTurns: turns });
4140
+ }
4141
+ async function editQuotaName(ctx, state, current) {
4142
+ const value = await ctx.ui.dialog.prompt({
4143
+ title: "Allowance label",
4144
+ description: "Shown above the Go meters. Leave it empty for the provider name or OpenCode Go.",
4145
+ value: current.quotaName
4146
+ });
4147
+ if (value === undefined)
4148
+ return;
4149
+ await state.update({ quotaName: sanitizeText(value.trim(), MAX_QUOTA_NAME_LENGTH) });
4150
+ }
4151
+ async function reset(ctx, state) {
4152
+ const current = state.policy();
4153
+ const confirmed = await ctx.ui.dialog.confirm({
4154
+ title: "Reset Usage insights settings",
4155
+ message: `Restore the built-in line, panel and allowance settings${current.maintenance ? "" : " (server maintenance is disabled)"}?`,
4156
+ label: { confirm: "Reset", cancel: "Cancel" }
4157
+ });
4158
+ if (confirmed)
4159
+ await state.reset();
4160
+ }
4161
+
3256
4162
  // src/tui.tsx
3257
4163
  var REFRESH_THROTTLE_MS = 300;
3258
4164
  var __test = {
@@ -3264,14 +4170,81 @@ var __test = {
3264
4170
  var tui_default = Plugin.define({
3265
4171
  id: "usage-insights",
3266
4172
  setup(ctx) {
3267
- const options = ctx.options ?? {};
3268
- if (options.enabled === false)
3269
- return;
3270
- const panelEnabled = options.panel !== false;
3271
- const pricing = options.pricing !== "off";
3272
- const quotaEnabled = options.quota !== "off";
3273
- const quotaActive = quotaEnabled && (options.sidebar !== false || panelEnabled);
3274
- const views = quotaEnabled ? CLIENT_VIEWS : PANEL_VIEWS;
4173
+ const [usageSettings, setUsageSettings] = createSignal3(defaultUsageSettings());
4174
+ const [policy, setPolicy] = createSignal3(defaultSettingsEnvelope().policy);
4175
+ const [settingsError, setSettingsError] = createSignal3(undefined);
4176
+ const [settingsLoaded, setSettingsLoaded] = createSignal3(false);
4177
+ let firstSettings = true;
4178
+ let saving = false;
4179
+ const envelope = () => ({
4180
+ settings: usageSettings(),
4181
+ policy: policy()
4182
+ });
4183
+ const sync = createSettingsSync({
4184
+ client: () => ctx.client,
4185
+ set: (next) => {
4186
+ setUsageSettings(next.settings);
4187
+ setPolicy(next.policy);
4188
+ setSettingsError(undefined);
4189
+ setSettingsLoaded(true);
4190
+ if (!firstSettings)
4191
+ bumpRefresh();
4192
+ firstSettings = false;
4193
+ },
4194
+ canApply: () => !saving,
4195
+ acceptEvent: (next) => {
4196
+ if (saving)
4197
+ return false;
4198
+ return JSON.stringify(next) !== JSON.stringify(envelope());
4199
+ },
4200
+ onLoadError: (message) => {
4201
+ setSettingsError(message);
4202
+ setSettingsLoaded(true);
4203
+ firstSettings = false;
4204
+ },
4205
+ onSaveError: (message) => {
4206
+ setSettingsError(message);
4207
+ ctx.ui.toast.show({
4208
+ message: `Usage insights settings: ${message}`,
4209
+ variant: "error"
4210
+ });
4211
+ }
4212
+ });
4213
+ sync.connect();
4214
+ const panelEnabled = () => usageSettings().panel;
4215
+ const pricing = () => usageSettings().pricing;
4216
+ const quotaEnabled = () => usageSettings().quota;
4217
+ const quotaActive = () => settingsLoaded() && quotaEnabled() && (usageSettings().sidebar || panelEnabled());
4218
+ const views = createMemo3(() => quotaEnabled() ? CLIENT_VIEWS : PANEL_VIEWS);
4219
+ const resolved = createMemo3(() => resolveUsageSettings(usageSettings()));
4220
+ async function saveSettings(patch) {
4221
+ setUsageSettings((current) => mergeUsageSettings(current, patch));
4222
+ saving = true;
4223
+ try {
4224
+ await sync.update(patch);
4225
+ bumpRefresh();
4226
+ } finally {
4227
+ saving = false;
4228
+ }
4229
+ }
4230
+ async function resetSettings() {
4231
+ setUsageSettings(defaultUsageSettings());
4232
+ saving = true;
4233
+ try {
4234
+ await sync.reset();
4235
+ bumpRefresh();
4236
+ } finally {
4237
+ saving = false;
4238
+ }
4239
+ }
4240
+ const settingsState = {
4241
+ settings: usageSettings,
4242
+ policy,
4243
+ error: settingsError,
4244
+ refresh: () => sync.refresh(true),
4245
+ update: saveSettings,
4246
+ reset: resetSettings
4247
+ };
3275
4248
  function providerName() {
3276
4249
  try {
3277
4250
  const providers = ctx.data.location?.provider?.list(ctx.location);
@@ -3280,7 +4253,7 @@ var tui_default = Plugin.define({
3280
4253
  return;
3281
4254
  }
3282
4255
  }
3283
- const quotaName = quotaNameOf(options.quotaName, providerName());
4256
+ const quotaName = () => quotaNameOf(resolved().quotaName, providerName());
3284
4257
  const PRICE_TTL_MS = 5 * 60 * 1000;
3285
4258
  let priceCache;
3286
4259
  function errorMessage(cause) {
@@ -3292,16 +4265,16 @@ var tui_default = Plugin.define({
3292
4265
  return "the usage limits request failed";
3293
4266
  }
3294
4267
  const [quotaState, setQuotaState] = createSignal3(undefined);
3295
- const [quotaLoading, setQuotaLoading] = createSignal3(quotaActive);
4268
+ const [quotaLoading, setQuotaLoading] = createSignal3(quotaActive());
3296
4269
  const [quotaError, setQuotaError] = createSignal3(undefined);
3297
4270
  const [quotaTick, setQuotaTick] = createSignal3(0);
3298
4271
  let quotaGeneration = 0;
3299
4272
  const refreshQuota = () => {
3300
- if (quotaActive)
4273
+ if (quotaActive())
3301
4274
  setQuotaTick((value) => value + 1);
3302
4275
  };
3303
4276
  createEffect3(() => {
3304
- if (!quotaActive)
4277
+ if (!quotaActive())
3305
4278
  return;
3306
4279
  quotaTick();
3307
4280
  const generation = ++quotaGeneration;
@@ -3323,7 +4296,7 @@ var tui_default = Plugin.define({
3323
4296
  });
3324
4297
  });
3325
4298
  createEffect3(() => {
3326
- if (!quotaActive)
4299
+ if (!quotaActive())
3327
4300
  return;
3328
4301
  const timer = setInterval(() => setQuotaTick((value) => value + 1), QUOTA_POLL_MS);
3329
4302
  onCleanup2(() => clearInterval(timer));
@@ -3335,7 +4308,7 @@ var tui_default = Plugin.define({
3335
4308
  refresh: refreshQuota
3336
4309
  };
3337
4310
  function priceTableFor() {
3338
- if (!pricing)
4311
+ if (!pricing())
3339
4312
  return;
3340
4313
  const now = Date.now();
3341
4314
  if (priceCache !== undefined && now - priceCache.at < PRICE_TTL_MS)
@@ -3356,11 +4329,11 @@ var tui_default = Plugin.define({
3356
4329
  const table = priceTableFor();
3357
4330
  return table === undefined ? undefined : (ref, tokens) => costOf(table, ref, tokens);
3358
4331
  }
3359
- const [settings, updateSettings] = ctx.storage.store("panel", {
4332
+ const [panelSettings, updatePanelSettings] = ctx.storage.store("panel", {
3360
4333
  initial: DEFAULT_SETTINGS
3361
4334
  });
3362
- const patchSettings = (mutation) => {
3363
- updateSettings(mutation);
4335
+ const patchPanelSettings = (mutation) => {
4336
+ updatePanelSettings(mutation);
3364
4337
  };
3365
4338
  const [refresh, setRefresh] = createSignal3(0);
3366
4339
  const [listCosts, setListCosts] = createSignal3({});
@@ -3387,12 +4360,12 @@ var tui_default = Plugin.define({
3387
4360
  refreshTimer.unref?.();
3388
4361
  }
3389
4362
  function listCostFor(sessionID) {
3390
- if (!pricing)
4363
+ if (!pricing())
3391
4364
  return 0;
3392
4365
  return listCosts()[sessionID] ?? 0;
3393
4366
  }
3394
4367
  async function loadListCost(sessionID) {
3395
- if (!pricing)
4368
+ if (!pricing())
3396
4369
  return;
3397
4370
  if (pendingListCost.has(sessionID)) {
3398
4371
  dirtyListCost.add(sessionID);
@@ -3430,7 +4403,7 @@ var tui_default = Plugin.define({
3430
4403
  function lineFor(sessionID) {
3431
4404
  if (!sessionIdle(sessionID))
3432
4405
  return;
3433
- if (pricing)
4406
+ if (pricing())
3434
4407
  refresh();
3435
4408
  const messages = ctx.data.session.message.list(sessionID);
3436
4409
  const info = ctx.data.session.get(sessionID);
@@ -3445,12 +4418,7 @@ var tui_default = Plugin.define({
3445
4418
  return ctx.theme.text.base;
3446
4419
  }
3447
4420
  function Line(props) {
3448
- const parts = createMemo3(() => lineParts(lineFor(props.sessionID), {
3449
- labels: options.labels,
3450
- fields: options.fields,
3451
- turnTotals: options.turnTotals,
3452
- estimates: pricing
3453
- }));
4421
+ const parts = createMemo3(() => lineParts(lineFor(props.sessionID), resolved().format));
3454
4422
  createEffect3(() => {
3455
4423
  props.sessionID;
3456
4424
  refresh();
@@ -3488,46 +4456,50 @@ var tui_default = Plugin.define({
3488
4456
  }
3489
4457
  })
3490
4458
  });
3491
- const disposePanel = panelEnabled ? ctx.ui.slot({
4459
+ const disposePanel = ctx.ui.slot({
3492
4460
  append: "session.panel",
3493
- render: (input) => input.name === PANEL_NAME ? _$createComponent3(Panel, {
4461
+ render: (input) => input.name === PANEL_NAME && panelEnabled() ? _$createComponent3(Panel, {
3494
4462
  input,
3495
4463
  ctx,
3496
4464
  deps: {
3497
4465
  refresh,
3498
4466
  bump: bumpRefresh
3499
4467
  },
3500
- settings,
3501
- update: patchSettings,
4468
+ settings: panelSettings,
4469
+ update: patchPanelSettings,
3502
4470
  get maintenance() {
3503
- return options.maintenance !== false;
4471
+ return policy().maintenance;
4472
+ },
4473
+ get views() {
4474
+ return views();
3504
4475
  },
3505
- views,
3506
4476
  quota: quotaResource,
3507
- quotaName
4477
+ get quotaName() {
4478
+ return quotaName();
4479
+ }
3508
4480
  }) : null
3509
- }) : () => {};
4481
+ });
3510
4482
  const disposeSidebar = ctx.ui.slot({
3511
4483
  append: "sidebar.content",
3512
- render: (input) => options.sidebar === false ? null : _$createComponent3(TurnsSidebar, {
4484
+ render: (input) => usageSettings().sidebar ? _$createComponent3(TurnsSidebar, {
3513
4485
  get sessionID() {
3514
4486
  return input.sessionID;
3515
4487
  },
3516
4488
  ctx,
3517
- get deps() {
3518
- return {
3519
- refresh,
3520
- limit: clampTurnsLimit(options.sidebarTurns ?? 8)
3521
- };
4489
+ deps: {
4490
+ refresh,
4491
+ limit: () => resolved().sidebarTurns
3522
4492
  },
3523
- quota: quotaEnabled ? quotaState : undefined,
3524
- quotaName
3525
- })
4493
+ quota: () => quotaEnabled() ? quotaState() : undefined,
4494
+ get quotaName() {
4495
+ return quotaName();
4496
+ }
4497
+ }) : null
3526
4498
  });
3527
4499
  function open(input) {
3528
- const parsed = parseArgs(input, views);
4500
+ const parsed = parseArgs(input, views());
3529
4501
  if (parsed.view !== undefined || parsed.range !== undefined) {
3530
- patchSettings((draft) => {
4502
+ patchPanelSettings((draft) => {
3531
4503
  if (parsed.view !== undefined)
3532
4504
  draft.view = parsed.view;
3533
4505
  if (parsed.range !== undefined)
@@ -3541,34 +4513,45 @@ var tui_default = Plugin.define({
3541
4513
  }
3542
4514
  return ctx.ui.panel.open(PANEL_NAME);
3543
4515
  }
3544
- if (panelEnabled) {
3545
- ctx.keymap.layer(() => {
3546
- return {
3547
- mode: "global",
3548
- commands: [{
3549
- id: "usage-insights.stats",
3550
- title: "Usage insights",
3551
- description: "Open the usage statistics panel",
3552
- group: "Usage insights",
3553
- bind: false,
3554
- palette: true,
3555
- slash: {
3556
- name: "usage-insights",
3557
- aliases: ["insights"],
3558
- arguments: true
3559
- },
3560
- run: (input) => {
3561
- if (!open(input)) {
3562
- ctx.ui.toast.show({
3563
- message: "Open a session first, then run /usage-insights",
3564
- variant: "warning"
3565
- });
3566
- }
4516
+ ctx.keymap.layer(() => {
4517
+ return {
4518
+ mode: "global",
4519
+ commands: [{
4520
+ id: "usage-insights.stats",
4521
+ title: "Usage insights",
4522
+ description: "Open the usage statistics panel",
4523
+ group: "Usage insights",
4524
+ bind: false,
4525
+ palette: true,
4526
+ enabled: () => panelEnabled(),
4527
+ slash: {
4528
+ name: "usage-insights",
4529
+ aliases: ["insights"],
4530
+ arguments: true
4531
+ },
4532
+ run: (input) => {
4533
+ if (!open(input)) {
4534
+ ctx.ui.toast.show({
4535
+ message: "Open a session first, then run /usage-insights",
4536
+ variant: "warning"
4537
+ });
3567
4538
  }
3568
- }]
3569
- };
3570
- });
3571
- }
4539
+ }
4540
+ }, {
4541
+ id: "usage-insights.settings",
4542
+ title: "Usage insights settings",
4543
+ description: "Line, panel and allowance settings shared with the Desktop",
4544
+ group: "Usage insights",
4545
+ bind: false,
4546
+ palette: true,
4547
+ slash: {
4548
+ name: "insights-settings",
4549
+ aliases: ["usage-insights-settings"]
4550
+ },
4551
+ run: () => void openUsageInsightsSettings(ctx, settingsState)
4552
+ }]
4553
+ };
4554
+ });
3572
4555
  const watchRecorded = () => {
3573
4556
  try {
3574
4557
  return api.onRecorded(() => bumpRefresh());
@@ -3585,21 +4568,17 @@ var tui_default = Plugin.define({
3585
4568
  ctx.data.on("session.compaction.ended", () => bumpRefresh()),
3586
4569
  ctx.data.on("model.updated", () => {
3587
4570
  priceCache = undefined;
3588
- })
4571
+ }),
4572
+ ctx.data.on("server.connected", () => sync.connect())
3589
4573
  ];
3590
4574
  __test.line = lineFor;
3591
4575
  __test.lineText = (sessionID) => {
3592
4576
  loadListCost(sessionID);
3593
- return lineText(lineParts(lineFor(sessionID), {
3594
- labels: options.labels,
3595
- fields: options.fields,
3596
- turnTotals: options.turnTotals,
3597
- estimates: pricing
3598
- }));
4577
+ return lineText(lineParts(lineFor(sessionID), resolved().format));
3599
4578
  };
3600
4579
  __test.open = open;
3601
4580
  __test.state = () => {
3602
- const current = sanitizeSettings(settings, views);
4581
+ const current = sanitizeSettings(panelSettings, views());
3603
4582
  return {
3604
4583
  view: current.view,
3605
4584
  range: current.range
@@ -3608,6 +4587,7 @@ var tui_default = Plugin.define({
3608
4587
  return () => {
3609
4588
  if (refreshTimer !== undefined)
3610
4589
  clearTimeout(refreshTimer);
4590
+ sync.stop();
3611
4591
  for (const dispose of disposeEvents)
3612
4592
  dispose();
3613
4593
  disposeLine();
@@ -3621,4 +4601,4 @@ export {
3621
4601
  tui_default as default
3622
4602
  };
3623
4603
 
3624
- //# debugId=7F05368FEEAF73BE64756E2164756E21
4604
+ //# debugId=7CDA7A48D491D99D64756E2164756E21