opencode-usage-insights 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { Rpc } from "@opencode/plugin/rpc";
7
7
 
8
8
  // src/limits.ts
9
9
  var MAX_PANEL_WIDTH = 200;
10
+ var MAX_HISTORY_WIDTH = 120;
10
11
  var MAX_TURNS = 50;
11
12
  function clampPanelWidth(value) {
12
13
  if (!Number.isFinite(value))
@@ -45,7 +46,7 @@ var PanelLineSchema = {
45
46
  var PanelSettingsSchema = {
46
47
  type: "object",
47
48
  properties: {
48
- view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"] },
49
+ view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db", "go"] },
49
50
  range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
50
51
  sort: { type: "string", maxLength: 40 },
51
52
  sortDesc: { type: "boolean" },
@@ -183,7 +184,7 @@ var UsageInsights = Rpc.define({
183
184
  properties: {
184
185
  sessionID: { type: "string", maxLength: 200 },
185
186
  limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
186
- width: { type: "number", minimum: 20, maximum: 120 }
187
+ width: { type: "number", minimum: 20, maximum: MAX_HISTORY_WIDTH }
187
188
  },
188
189
  required: ["sessionID", "limit", "width"],
189
190
  additionalProperties: false
@@ -2098,7 +2099,10 @@ var GAP_BUCKETS = [
2098
2099
  ["<1m", 0, 60000],
2099
2100
  ["1\u20135m", 60000, 5 * 60000],
2100
2101
  ["5\u201315m", 5 * 60000, 15 * 60000],
2101
- ["15\u201360m", 15 * 60000, 60 * 60000],
2102
+ ["15\u201320m", 15 * 60000, 20 * 60000],
2103
+ ["20\u201330m", 20 * 60000, 30 * 60000],
2104
+ ["30\u201345m", 30 * 60000, 45 * 60000],
2105
+ ["45\u201360m", 45 * 60000, 60 * 60000],
2102
2106
  ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
2103
2107
  [">6h", 6 * 60 * 60000, undefined]
2104
2108
  ];
@@ -2349,9 +2353,128 @@ function periodsOf(rows, granularity, otherRows = []) {
2349
2353
  return [...byKey.values()].sort((left, right) => left.at - right.at);
2350
2354
  }
2351
2355
 
2356
+ // src/quota.ts
2357
+ var QUOTA_VIEW = "go";
2358
+ var QUOTA_POLL_MS = 60000;
2359
+ var DEFAULT_QUOTA_NAME = "OpenCode Go";
2360
+ var DAY_MS = 24 * 60 * 60 * 1000;
2361
+ var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
2362
+ function quotaNameOf(explicit, providerName) {
2363
+ const custom = explicit?.trim();
2364
+ if (custom !== undefined && custom !== "")
2365
+ return custom;
2366
+ const provider = providerName?.trim();
2367
+ if (provider !== undefined && provider !== "")
2368
+ return provider;
2369
+ return DEFAULT_QUOTA_NAME;
2370
+ }
2371
+ function finite2(value) {
2372
+ return typeof value === "number" && Number.isFinite(value);
2373
+ }
2374
+ function clamp(value, minimum, maximum) {
2375
+ return Math.min(maximum, Math.max(minimum, value));
2376
+ }
2377
+ function previousCycleStart(endAt) {
2378
+ if (!finite2(endAt))
2379
+ return endAt;
2380
+ const end = new Date(endAt);
2381
+ const year = end.getUTCFullYear();
2382
+ const month = end.getUTCMonth();
2383
+ const day = end.getUTCDate();
2384
+ const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
2385
+ const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
2386
+ start.setUTCDate(Math.min(day, lastDay));
2387
+ return start.getTime();
2388
+ }
2389
+ function forecastMonthly(meter, now) {
2390
+ const endAt = finite2(meter.resetsAt) ? meter.resetsAt : now;
2391
+ const startAt = previousCycleStart(endAt);
2392
+ const total = Math.max(1, endAt - startAt);
2393
+ const elapsedMs = clamp(now - startAt, 0, total);
2394
+ const remainingMs = Math.max(0, endAt - now);
2395
+ const percent = clamp(finite2(meter.percent) ? meter.percent : 0, 0, 100);
2396
+ const reached = meter.limited === true || percent >= 100;
2397
+ const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
2398
+ const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
2399
+ const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
2400
+ const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
2401
+ const willExhaust = exhaustAt !== undefined;
2402
+ const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
2403
+ return {
2404
+ startAt,
2405
+ endAt,
2406
+ elapsedMs,
2407
+ remainingMs,
2408
+ ratePerDay,
2409
+ projectedPercent,
2410
+ ...exhaustAt !== undefined ? { exhaustAt } : {},
2411
+ reached,
2412
+ available,
2413
+ willExhaust
2414
+ };
2415
+ }
2416
+ function quotaBar(percent, width = 10) {
2417
+ const value = clamp(finite2(percent) ? percent : 0, 0, 100);
2418
+ const cells = Math.max(1, Math.round(width));
2419
+ const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
2420
+ return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
2421
+ }
2422
+ function formatRenewal(at, timeZone) {
2423
+ if (!finite2(at))
2424
+ return "\u2013";
2425
+ try {
2426
+ return new Intl.DateTimeFormat("en-GB", {
2427
+ day: "2-digit",
2428
+ month: "short",
2429
+ year: "numeric",
2430
+ hour: "2-digit",
2431
+ minute: "2-digit",
2432
+ hour12: false,
2433
+ ...timeZone !== undefined ? { timeZone } : {}
2434
+ }).format(new Date(at)).replace(/,/g, "");
2435
+ } catch {
2436
+ return "\u2013";
2437
+ }
2438
+ }
2439
+ function formatRenewalCompact(at, timeZone) {
2440
+ if (!finite2(at))
2441
+ return "\u2013";
2442
+ try {
2443
+ return new Intl.DateTimeFormat("en-GB", {
2444
+ day: "2-digit",
2445
+ month: "short",
2446
+ hour: "2-digit",
2447
+ minute: "2-digit",
2448
+ hour12: false,
2449
+ ...timeZone !== undefined ? { timeZone } : {}
2450
+ }).format(new Date(at)).replace(/,/g, "");
2451
+ } catch {
2452
+ return "\u2013";
2453
+ }
2454
+ }
2455
+ function formatCountdown(at, now) {
2456
+ const remaining = at - now;
2457
+ if (!finite2(remaining))
2458
+ return "\u2013";
2459
+ if (remaining <= 0)
2460
+ return "due";
2461
+ return formatDuration(remaining);
2462
+ }
2463
+ function quotaStatus(quota) {
2464
+ const limited = [];
2465
+ if (quota.rolling.limited || quota.rolling.percent >= 100)
2466
+ limited.push("5-hour");
2467
+ if (quota.weekly.limited || quota.weekly.percent >= 100)
2468
+ limited.push("weekly");
2469
+ if (quota.monthly.limited || quota.monthly.percent >= 100)
2470
+ limited.push("monthly");
2471
+ return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
2472
+ }
2473
+
2352
2474
  // src/panel-data.ts
2353
2475
  var PANEL_NAME = "usage-insights";
2354
2476
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
2477
+ var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
2355
2478
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
2356
2479
  var GRANULARITIES = ["day", "week", "month"];
2357
2480
  var SORT_KEYS = {
@@ -2376,13 +2499,13 @@ function nextSort(view, current, step) {
2376
2499
  return keys[0];
2377
2500
  return keys[(index + step + keys.length) % keys.length];
2378
2501
  }
2379
- function parseArgs(input) {
2502
+ function parseArgs(input, views = CLIENT_VIEWS) {
2380
2503
  const parsed = {};
2381
2504
  for (const token of (input ?? "").split(/\s+/)) {
2382
2505
  const value = token.trim().toLowerCase();
2383
2506
  if (value === "")
2384
2507
  continue;
2385
- if (PANEL_VIEWS.includes(value))
2508
+ if (views.includes(value))
2386
2509
  parsed.view = value;
2387
2510
  else if (RANGE_KEYS.includes(value))
2388
2511
  parsed.range = value;
@@ -2419,10 +2542,10 @@ var DEFAULT_SETTINGS = {
2419
2542
  modelID: "",
2420
2543
  providerID: ""
2421
2544
  };
2422
- function sanitizeSettings(raw) {
2545
+ function sanitizeSettings(raw, views = CLIENT_VIEWS) {
2423
2546
  const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
2424
2547
  return {
2425
- view: PANEL_VIEWS.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
2548
+ view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
2426
2549
  range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
2427
2550
  sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
2428
2551
  sortDesc: settings.sortDesc === true,
@@ -2490,15 +2613,6 @@ function truncateMiddle(value, width) {
2490
2613
  const tail = width - 1 - head;
2491
2614
  return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
2492
2615
  }
2493
- function tableWidths(width, layouts) {
2494
- for (const layout of layouts) {
2495
- const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
2496
- if (total <= width)
2497
- return [...layout];
2498
- }
2499
- const last = layouts[layouts.length - 1];
2500
- return last === undefined ? [] : [...last];
2501
- }
2502
2616
  function modelCell(modelID, variant, width) {
2503
2617
  return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
2504
2618
  }
@@ -2517,6 +2631,47 @@ function formatTableRow(cells, widths, aligns) {
2517
2631
  }
2518
2632
  return parts.join(" ");
2519
2633
  }
2634
+ function fitTableColumns(columns, width) {
2635
+ const chosen = new Set;
2636
+ for (let index = 0;index < columns.length; index += 1) {
2637
+ if (columns[index].priority === undefined)
2638
+ chosen.add(index);
2639
+ }
2640
+ if (chosen.size === 0)
2641
+ return [];
2642
+ const total = () => {
2643
+ let sum = chosen.size - 1;
2644
+ for (const index of chosen)
2645
+ sum += columns[index].width;
2646
+ return sum;
2647
+ };
2648
+ 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);
2649
+ for (const { column, index } of optional) {
2650
+ if (total() + column.width + 1 + (column.reserve ?? 0) <= width)
2651
+ chosen.add(index);
2652
+ }
2653
+ while (chosen.size > 1 && total() > width)
2654
+ chosen.delete(Math.max(...chosen));
2655
+ const widths = new Map;
2656
+ let room = width - total();
2657
+ for (let index = 0;index < columns.length && room > 0; index += 1) {
2658
+ if (!chosen.has(index))
2659
+ continue;
2660
+ const column = columns[index];
2661
+ const grow = Math.min(room, (column.max ?? column.width) - column.width);
2662
+ if (grow <= 0)
2663
+ continue;
2664
+ widths.set(index, column.width + grow);
2665
+ room -= grow;
2666
+ }
2667
+ return [...chosen].sort((left, right) => left - right).map((index) => ({ index, width: widths.get(index) ?? columns[index].width }));
2668
+ }
2669
+ function fitTable(columns, width) {
2670
+ return fitTableColumns(columns, width).map(({ index, width: fitted }) => {
2671
+ const column = columns[index];
2672
+ return { index, header: column.header, width: fitted, align: column.align ?? "left", cell: column.cell };
2673
+ });
2674
+ }
2520
2675
  function count(n, singular, plural = `${singular}s`) {
2521
2676
  return `${formatCount(n)} ${n === 1 ? singular : plural}`;
2522
2677
  }
@@ -2524,21 +2679,30 @@ function kvGrid(pairs, width) {
2524
2679
  const lines = [];
2525
2680
  const label = 11;
2526
2681
  const column = Math.floor(width / 2);
2682
+ const pairLines = (pair) => {
2683
+ const text = `${padCell(pair[0], label)}${pair[1]}`;
2684
+ if (text.length <= width)
2685
+ return [text];
2686
+ return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width));
2687
+ };
2527
2688
  for (let index = 0;index < pairs.length; index += 2) {
2528
2689
  const left = pairs[index];
2529
2690
  const right = pairs[index + 1];
2530
- const leftText = `${padCell(left[0], label)}${left[1]}`;
2531
2691
  if (right === undefined) {
2532
- lines.push({ text: leftText, tone: "base" });
2692
+ for (const text of pairLines(left))
2693
+ lines.push({ text, tone: "base" });
2533
2694
  continue;
2534
2695
  }
2696
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
2535
2697
  const rightText = `${padCell(right[0], label)}${right[1]}`;
2536
2698
  const gap = Math.max(2, column - leftText.length);
2537
2699
  if (leftText.length + gap + rightText.length <= width) {
2538
2700
  lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
2539
2701
  } else {
2540
- lines.push({ text: leftText, tone: "base" });
2541
- lines.push({ text: rightText, tone: "base" });
2702
+ for (const text of pairLines(left))
2703
+ lines.push({ text, tone: "base" });
2704
+ for (const text of pairLines(right))
2705
+ lines.push({ text, tone: "base" });
2542
2706
  }
2543
2707
  }
2544
2708
  return lines;
@@ -2579,25 +2743,28 @@ function usageBuckets(usage) {
2579
2743
  hit: prompt > 0 ? usage.cached / prompt : undefined
2580
2744
  };
2581
2745
  }
2582
- function viewBar(view, width = 200) {
2746
+ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
2583
2747
  const key = (index) => String((index + 1) % 10);
2584
- const full = PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2585
- const candidates = [full, PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2748
+ const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2749
+ const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2586
2750
  for (const parts of candidates) {
2587
2751
  const text = parts.join(" ");
2588
2752
  if (text.length <= width)
2589
2753
  return { text, tone: "muted" };
2590
2754
  }
2591
- return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
2755
+ const index = views.indexOf(view);
2756
+ return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
2592
2757
  }
2593
2758
  function keysFor(of) {
2759
+ if (of === QUOTA_VIEW)
2760
+ return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
2594
2761
  if (of === "db")
2595
- return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
2762
+ return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 0 view \xB7 ? help";
2596
2763
  if (of === "periods")
2597
- return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2764
+ return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2598
2765
  if (of === "turns")
2599
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2600
- return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2766
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2767
+ return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2601
2768
  }
2602
2769
  function filterSummary(filters) {
2603
2770
  const parts = [];
@@ -2614,7 +2781,7 @@ function helpLines(width) {
2614
2781
  const lines = [
2615
2782
  { text: "keys", tone: HEADER_TONE },
2616
2783
  { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
2617
- { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
2784
+ { text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
2618
2785
  { text: " t shift+t previous / next range" },
2619
2786
  { text: " s shift+s cycle sort column \xB7 reverse" },
2620
2787
  { text: " b periods bucket: day \u2192 week \u2192 month" },
@@ -2623,6 +2790,13 @@ function helpLines(width) {
2623
2790
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
2624
2791
  { text: " e db: backfill list-price estimates for the $0 steps" },
2625
2792
  { text: "" },
2793
+ { text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
2794
+ { text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
2795
+ { text: " forecast the monthly percentage at its reset, from the" },
2796
+ { text: " cycle's average pace (not a sample history)" },
2797
+ { text: " renews the monthly reset reported by the host" },
2798
+ { text: " the plugin reads the host's local usage-limits endpoint;" },
2799
+ { text: " it never reads your API key and never talks to the Console." },
2626
2800
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
2627
2801
  { text: " prompt everything the provider saw: cached + fresh + writes" },
2628
2802
  { text: " in the uncached part: fresh input + cache writes" },
@@ -2657,6 +2831,101 @@ function helpLines(width) {
2657
2831
  ];
2658
2832
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2659
2833
  }
2834
+ function quotaMeterLine(label, meter, now) {
2835
+ const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
2836
+ const countdown = formatCountdown(meter.resetsAt, now);
2837
+ return {
2838
+ text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
2839
+ tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
2840
+ };
2841
+ }
2842
+ function goQuotaLines(state, options) {
2843
+ const { now, width, loading, error } = options;
2844
+ const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
2845
+ const lines = [];
2846
+ const push = (text, tone = "base") => {
2847
+ lines.push({ text, tone });
2848
+ };
2849
+ if (state === undefined) {
2850
+ if (error !== undefined && error !== "")
2851
+ push(`Go quota unavailable: ${error}`, "warning");
2852
+ else if (loading === true)
2853
+ push("reading OpenCode Go quota\u2026", "muted");
2854
+ else
2855
+ push("OpenCode Go quota is unavailable", "muted");
2856
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2857
+ }
2858
+ if (state.kind === "none") {
2859
+ push(name, "accent");
2860
+ push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
2861
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2862
+ }
2863
+ const quota = state.quota;
2864
+ const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
2865
+ const status = quotaStatus(quota);
2866
+ const forecast = forecastMonthly(quota.monthly, now);
2867
+ push(`${name} \xB7 ${workspace}`, "accent");
2868
+ push(`status ${status}`, status === "active" ? "base" : "warning");
2869
+ lines.push(quotaMeterLine("rolling", quota.rolling, now));
2870
+ lines.push(quotaMeterLine("weekly", quota.weekly, now));
2871
+ lines.push(quotaMeterLine("monthly", quota.monthly, now));
2872
+ push("");
2873
+ if (forecast.reached || quota.monthly.limited) {
2874
+ push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
2875
+ } else if (now >= forecast.endAt) {
2876
+ push("forecast monthly reset due \xB7 refresh", "warning");
2877
+ } else if (!forecast.available) {
2878
+ push("forecast too early in the cycle to project a monthly pace", "muted");
2879
+ } else if (quota.monthly.percent === 0) {
2880
+ push("forecast no monthly usage yet this cycle", "muted");
2881
+ } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
2882
+ push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
2883
+ } else {
2884
+ const projected = Math.min(999, Math.round(forecast.projectedPercent));
2885
+ const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
2886
+ push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
2887
+ }
2888
+ const renewal = formatRenewal(quota.monthly.resetsAt);
2889
+ const countdown = formatCountdown(quota.monthly.resetsAt, now);
2890
+ push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
2891
+ if (quota.workspace?.usageURL !== undefined)
2892
+ push(`console ${quota.workspace.usageURL}`, "muted");
2893
+ const age = Math.max(0, now - quota.observedAt);
2894
+ push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
2895
+ if (loading === true)
2896
+ push("refreshing\u2026", "muted");
2897
+ if (error !== undefined && error !== "")
2898
+ push(`quota refresh failed: ${error}`, "warning");
2899
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2900
+ }
2901
+ function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
2902
+ if (state?.kind !== "ok" || width <= 0)
2903
+ return [];
2904
+ const quota = state.quota;
2905
+ const status = quotaStatus(quota);
2906
+ const forecast = forecastMonthly(quota.monthly, now);
2907
+ const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
2908
+ const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
2909
+ let forecastText = "forecast too early";
2910
+ let forecastTone = "muted";
2911
+ if (forecast.reached || quota.monthly.limited) {
2912
+ forecastText = "monthly limit reached";
2913
+ forecastTone = "warning";
2914
+ } else if (forecast.willExhaust) {
2915
+ forecastText = "limit before renewal";
2916
+ forecastTone = "warning";
2917
+ } else if (forecast.available && quota.monthly.percent > 0) {
2918
+ forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
2919
+ } else if (forecast.available && quota.monthly.percent === 0) {
2920
+ forecastText = "forecast no usage yet";
2921
+ }
2922
+ return [
2923
+ { text: truncate(name, width), tone: "accent" },
2924
+ { text: truncate(base, width), tone: baseTone },
2925
+ { text: truncate(forecastText, width), tone: forecastTone },
2926
+ { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
2927
+ ];
2928
+ }
2660
2929
  function usagePairs(usage, estimates = true) {
2661
2930
  if (usage === undefined)
2662
2931
  return [];
@@ -2684,14 +2953,16 @@ function overviewLines(data, width) {
2684
2953
  const lines = [];
2685
2954
  const estimates = data.estimates !== false;
2686
2955
  lines.push({
2687
- text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
2956
+ text: truncate(`${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`, width),
2688
2957
  tone: "muted"
2689
2958
  });
2690
2959
  lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
2691
2960
  if (data.activity !== undefined && data.activity.length > 1) {
2692
- const series = reduceSeries(data.activity);
2961
+ const suffix = ` ${count(data.activity.length, "bucket")}`;
2962
+ const bars = Math.max(4, width - "activity ".length - suffix.length);
2963
+ const series = reduceSeries(data.activity, bars);
2693
2964
  lines.push({ text: "", tone: "muted" });
2694
- lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
2965
+ lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: "muted" });
2695
2966
  }
2696
2967
  if (data.session !== undefined) {
2697
2968
  lines.push({ text: "", tone: "muted" });
@@ -2702,7 +2973,7 @@ function overviewLines(data, width) {
2702
2973
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
2703
2974
  const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
2704
2975
  lines.push({
2705
- text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
2976
+ text: truncate(` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`, width),
2706
2977
  tone: "muted"
2707
2978
  });
2708
2979
  }
@@ -2734,65 +3005,33 @@ function coveragePairs(coverage) {
2734
3005
  ]
2735
3006
  ];
2736
3007
  }
2737
- function modelColumns(width) {
2738
- const layouts = [
2739
- { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
2740
- { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
2741
- { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
2742
- { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
2743
- { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
2744
- ];
2745
- for (const layout of layouts) {
2746
- const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
2747
- if (total <= width)
2748
- return layout;
2749
- }
2750
- return layouts[layouts.length - 1];
2751
- }
2752
3008
  function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2753
- const columns = modelColumns(width);
2754
- const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
2755
- const aligns = ["left", "right", "right", "right"];
2756
- const header = ["model", "steps", "prompt", "cached"];
2757
- if (columns.hit > 0) {
2758
- widths.push(columns.hit);
2759
- aligns.push("right");
2760
- header.push("hit");
2761
- }
2762
- widths.push(columns.out);
2763
- aligns.push("right");
2764
- header.push("out");
2765
- if (columns.cost > 0) {
2766
- widths.push(columns.cost);
2767
- aligns.push("right");
2768
- header.push("cost");
2769
- }
2770
- if (columns.spread > 0) {
2771
- widths.push(columns.spread);
2772
- aligns.push("left");
2773
- header.push("providers");
2774
- }
2775
- const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
3009
+ let modelWidth = 14;
3010
+ const columns = fitTable([
3011
+ { header: "model", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },
3012
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
3013
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => row.prompt },
3014
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => row.cached },
3015
+ { header: "hit", width: 6, max: 7, priority: 2, reserve: 10, align: "right", cell: (row) => row.hit },
3016
+ { header: "out", width: 7, max: 9, priority: 3, reserve: 10, align: "right", cell: (row) => row.output },
3017
+ { header: "cost", width: 8, max: 9, priority: 1, align: "right", cell: (row) => row.cost },
3018
+ { header: "providers", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers }
3019
+ ], width);
3020
+ modelWidth = columns.find((column) => column.index === 0)?.width ?? 0;
3021
+ if (columns.length === 0)
3022
+ return [{ text: truncate("no room for a table at this width", width), tone: "muted" }];
3023
+ const lines = [
3024
+ {
3025
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
3026
+ tone: HEADER_TONE
3027
+ }
3028
+ ];
2776
3029
  for (const model of rows.slice(0, limit)) {
2777
3030
  const key = modelKey(model.modelID, model.variant);
2778
- const name = modelCell(model.modelID, model.variant, columns.model);
2779
3031
  const buckets = usageBuckets(model.totals);
2780
3032
  const providers = unique(model.providers.map((provider) => provider.providerID));
2781
3033
  const cache = extras?.cache?.get(key);
2782
3034
  const switches = extras?.switches?.get(key);
2783
- const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
2784
- if (columns.hit > 0)
2785
- cells.push(formatPercent(cache?.hit ?? buckets.hit));
2786
- cells.push(formatTokens(buckets.output));
2787
- if (columns.cost > 0)
2788
- cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
2789
- if (columns.spread > 0)
2790
- cells.push(providers.join(", "));
2791
- lines.push({
2792
- text: formatTableRow(cells, widths, aligns),
2793
- tone: "base",
2794
- row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
2795
- });
2796
3035
  const details = [];
2797
3036
  if (cache !== undefined)
2798
3037
  details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
@@ -2802,62 +3041,76 @@ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2802
3041
  if (switches.cacheLost > 0)
2803
3042
  details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
2804
3043
  }
2805
- if (details.length > 0) {
2806
- lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
3044
+ const view = {
3045
+ modelID: model.modelID,
3046
+ variant: model.variant,
3047
+ steps: formatCount(buckets.steps),
3048
+ prompt: formatTokens(buckets.prompt),
3049
+ cached: formatTokens(buckets.cached),
3050
+ hit: formatPercent(cache?.hit ?? buckets.hit),
3051
+ output: formatTokens(buckets.output),
3052
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),
3053
+ providers: providers.join(", "),
3054
+ detail: details.join(" \xB7 ")
3055
+ };
3056
+ lines.push({
3057
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
3058
+ tone: "base",
3059
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
3060
+ });
3061
+ if (view.detail !== "") {
3062
+ lines.push({ text: truncate(`${" ".repeat(modelWidth + 1)}${view.detail}`, width), tone: "muted" });
2807
3063
  }
2808
3064
  }
2809
3065
  if (rows.length > limit)
2810
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
3066
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, width), tone: "muted" });
2811
3067
  if (rows.length === 0)
2812
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
3068
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
2813
3069
  return lines;
2814
3070
  }
2815
3071
  function unique(values) {
2816
3072
  return [...new Set(values)];
2817
3073
  }
2818
- var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
2819
- function fitColumns(columns, width) {
2820
- const chosen = [...columns];
2821
- while (chosen.length > 1 && tableWidth(chosen) > width) {
2822
- const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
2823
- if (optional === -1)
2824
- break;
2825
- chosen.splice(chosen.length - 1 - optional, 1);
2826
- }
2827
- return chosen;
2828
- }
2829
3074
  function renderTable(rows, columns, width, options) {
2830
- const chosen = fitColumns(columns, width);
3075
+ const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {
3076
+ const column = columns[index];
3077
+ const align = column.align ?? "left";
3078
+ return { ...column, width: fitted, align };
3079
+ });
3080
+ if (chosen.length === 0)
3081
+ return [{ text: truncate(options.empty, width), tone: "muted" }];
2831
3082
  const widths = chosen.map((column) => column.width);
2832
- const aligns = chosen.map((column) => column.align ?? "left");
2833
- const alignsTyped = aligns;
2834
- const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
3083
+ const aligns = chosen.map((column) => column.align);
3084
+ const lines = [
3085
+ { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE }
3086
+ ];
2835
3087
  if (rows.length === 0)
2836
- lines.push({ text: options.empty, tone: "muted" });
3088
+ lines.push({ text: truncate(options.empty, width), tone: "muted" });
2837
3089
  for (const row of rows.slice(0, options.limit)) {
2838
3090
  const identity = options.row?.(row);
2839
3091
  lines.push({
2840
- text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
3092
+ text: formatTableRow(chosen.map((column) => column.cell(row, column.width)), widths, aligns),
2841
3093
  tone: options.tone?.(row) ?? "base",
2842
3094
  ...identity === undefined ? {} : { row: identity }
2843
3095
  });
2844
3096
  }
2845
- if (rows.length > options.limit)
2846
- lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
3097
+ if (rows.length > options.limit) {
3098
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - options.limit, "more row")}`, width), tone: "muted" });
3099
+ }
2847
3100
  return lines;
2848
3101
  }
2849
3102
  function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2850
3103
  const lines = renderTable(rows, [
2851
- { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
2852
- { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
3104
+ { header: "provider", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
3105
+ { header: "models", width: 6, align: "right", priority: 4, cell: (row) => formatCount(row.models.length) },
2853
3106
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2854
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2855
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2856
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2857
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2858
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2859
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2860
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3107
+ { header: "share", width: 6, align: "right", priority: 3, cell: (row) => formatPercent(row.share, 0) },
3108
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
3109
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
3110
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
3111
+ { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
3112
+ { header: "wall", width: 7, align: "right", priority: 6, cell: (row) => formatMs(row.wall) },
3113
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2861
3114
  ], width, {
2862
3115
  limit,
2863
3116
  empty: "no usage recorded for this range",
@@ -2868,16 +3121,16 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2868
3121
  }
2869
3122
  function providerLines(rows, width, limit = 40, estimates = true) {
2870
3123
  return renderTable(rows, [
2871
- { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
2872
- { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
3124
+ { header: "model", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },
3125
+ { header: "provider", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
2873
3126
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2874
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2875
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2876
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2877
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2878
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2879
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2880
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3127
+ { header: "share", width: 6, align: "right", priority: 5, cell: (row) => formatPercent(row.share, 0) },
3128
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },
3129
+ { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
3130
+ { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
3131
+ { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
3132
+ { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
3133
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2881
3134
  ], width, {
2882
3135
  limit,
2883
3136
  empty: "no usage recorded for this range",
@@ -2887,80 +3140,126 @@ function providerLines(rows, width, limit = 40, estimates = true) {
2887
3140
  }
2888
3141
  function cacheLines(data, width) {
2889
3142
  const lines = [];
3143
+ const push = (text, tone = "base") => {
3144
+ lines.push({ text: truncate(text, width), tone });
3145
+ };
2890
3146
  const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
2891
- lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
3147
+ push(`reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, total > 0 ? "warning" : "base");
2892
3148
  for (const reason of ["expired", "compaction", "unknown"]) {
2893
3149
  const group = data.drops.filter((drop) => drop.reason === reason);
2894
3150
  if (group.length === 0)
2895
3151
  continue;
2896
3152
  const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
2897
- lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
3153
+ push(` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, reason === "expired" ? "warning" : "muted");
2898
3154
  }
2899
3155
  if (data.drops.length === 0)
2900
- lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
3156
+ push(" none: prompt cache held through every gap", "muted");
2901
3157
  if (data.models !== undefined && data.models.length > 0) {
2902
3158
  lines.push({ text: "", tone: "muted" });
2903
- lines.push({ text: "reuse by model", tone: HEADER_TONE });
2904
- const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
2905
- lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
2906
- for (const row of data.models.slice(0, 10)) {
2907
- const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
2908
- lines.push({
2909
- 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"]),
2910
- tone: "base",
2911
- row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
2912
- });
3159
+ push("reuse by model", HEADER_TONE);
3160
+ let modelWidth = 12;
3161
+ const reuse = fitTable([
3162
+ { header: "model", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },
3163
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.cache.steps) },
3164
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
3165
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
3166
+ { header: "write", width: 6, max: 8, align: "right", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },
3167
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
3168
+ { header: "hit p50", width: 7, max: 9, align: "right", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) }
3169
+ ], width);
3170
+ modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0;
3171
+ if (reuse.length > 0) {
3172
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
3173
+ for (const row of data.models.slice(0, 10)) {
3174
+ lines.push({
3175
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
3176
+ tone: "base",
3177
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
3178
+ });
3179
+ }
2913
3180
  }
2914
3181
  }
2915
3182
  if (data.gap !== undefined && data.gap.samples > 0) {
2916
3183
  lines.push({ text: "", tone: "muted" });
2917
- lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
2918
- const widths = [9, 8, 9, 9, 10];
2919
- lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
2920
- for (const bucket of data.gap.buckets) {
2921
- if (bucket.samples === 0)
2922
- continue;
2923
- lines.push({
2924
- text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
2925
- tone: bucket.drops > 0 ? "warning" : "base"
2926
- });
3184
+ push("cache survival against idle time", HEADER_TONE);
3185
+ const buckets = data.gap.buckets;
3186
+ const survival = fitTable([
3187
+ { header: "gap", width: 8, max: 12, cell: (bucket) => bucket.label },
3188
+ { header: "pairs", width: 6, align: "right", cell: (bucket) => formatCount(bucket.samples) },
3189
+ { header: "kept", width: 7, align: "right", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },
3190
+ { header: "drops", width: 7, align: "right", cell: (bucket) => formatCount(bucket.drops) },
3191
+ { header: "lost", width: 8, align: "right", cell: (bucket) => formatTokens(bucket.lostTokens) }
3192
+ ], width);
3193
+ if (survival.length > 0) {
3194
+ lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: "muted" });
3195
+ for (const bucket of buckets) {
3196
+ if (bucket.samples === 0)
3197
+ continue;
3198
+ lines.push({
3199
+ text: formatTableRow(survival.map((column) => column.cell(bucket)), survival.map((column) => column.width), survival.map((column) => column.align)),
3200
+ tone: bucket.drops > 0 ? "warning" : "base"
3201
+ });
3202
+ }
2927
3203
  }
2928
3204
  if (data.gap.providers.length > 1) {
2929
3205
  lines.push({ text: "", tone: "muted" });
2930
- lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
2931
- const providerWidths = [26, 8, 9, 9];
2932
- lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
2933
- for (const row of data.gap.providers.slice(0, 8)) {
2934
- lines.push({
2935
- text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
2936
- tone: "base"
2937
- });
3206
+ push("reuse kept, by provider", HEADER_TONE);
3207
+ const providers = data.gap.providers;
3208
+ const reuse = fitTable([
3209
+ { header: "provider", width: 12, max: 30, cell: (row) => row.provider },
3210
+ { header: "pairs", width: 6, align: "right", cell: (row) => formatCount(row.samples) },
3211
+ { header: "kept", width: 7, align: "right", cell: (row) => formatPercent(row.retainedRatio, 0) },
3212
+ { header: "lost", width: 8, align: "right", cell: (row) => formatTokens(row.lostTokens) }
3213
+ ], width);
3214
+ if (reuse.length > 0) {
3215
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
3216
+ for (const row of providers.slice(0, 8)) {
3217
+ lines.push({
3218
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
3219
+ tone: "base"
3220
+ });
3221
+ }
2938
3222
  }
2939
3223
  }
2940
3224
  }
2941
3225
  lines.push({ text: "", tone: "muted" });
2942
- lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
3226
+ push("observed cache TTL bounds", HEADER_TONE);
2943
3227
  if (data.evidence.length === 0) {
2944
- lines.push({ text: " no comparable step pairs yet", tone: "muted" });
3228
+ push(" no comparable step pairs yet", "muted");
2945
3229
  } else {
2946
- const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
2947
- lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
2948
- for (const row of data.evidence.slice(0, 10)) {
2949
- lines.push({
2950
- text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
2951
- tone: "base"
2952
- });
3230
+ const evidence = fitTable([
3231
+ { header: "model", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },
3232
+ { header: "hits up to", width: 10, align: "right", cell: (row) => formatGap(row.maxHitGapMs) },
3233
+ { header: "drops from", width: 10, align: "right", cell: (row) => formatGap(row.minDropGapMs) },
3234
+ { header: "samples", width: 7, align: "right", priority: 1, cell: (row) => formatCount(row.samples) }
3235
+ ], width);
3236
+ if (evidence.length > 0) {
3237
+ lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: "muted" });
3238
+ for (const row of data.evidence.slice(0, 10)) {
3239
+ lines.push({
3240
+ text: formatTableRow(evidence.map((column) => column.cell(row)), evidence.map((column) => column.width), evidence.map((column) => column.align)),
3241
+ tone: "base"
3242
+ });
3243
+ }
2953
3244
  }
2954
3245
  }
2955
3246
  if (data.drops.length > 0) {
2956
3247
  lines.push({ text: "", tone: "muted" });
2957
- lines.push({ text: "recent losses", tone: HEADER_TONE });
2958
- for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
2959
- const when = new Date(drop.at).toLocaleTimeString("en-GB");
2960
- lines.push({
2961
- 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"]),
2962
- tone: drop.reason === "expired" ? "warning" : "base"
2963
- });
3248
+ push("recent losses", HEADER_TONE);
3249
+ const losses = fitTable([
3250
+ { header: "when", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString("en-GB") },
3251
+ { header: "provider/model", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? ""}/${drop.modelID ?? ""}` },
3252
+ { header: "tokens", width: 7, align: "right", cell: (drop) => `\u2212${formatTokens(drop.tokens)}` },
3253
+ { header: "idle", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}` }
3254
+ ], width);
3255
+ if (losses.length > 0) {
3256
+ lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: "muted" });
3257
+ for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {
3258
+ lines.push({
3259
+ text: formatTableRow(losses.map((column) => column.cell(drop)), losses.map((column) => column.width), losses.map((column) => column.align)),
3260
+ tone: drop.reason === "expired" ? "warning" : "base"
3261
+ });
3262
+ }
2964
3263
  }
2965
3264
  }
2966
3265
  return lines;
@@ -2981,110 +3280,162 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true, tot
2981
3280
  }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
2982
3281
  const overall = usageBuckets(totals);
2983
3282
  lines.push({
2984
- text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
3283
+ text: truncate(`${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`, width),
2985
3284
  tone: "muted"
2986
3285
  });
2987
3286
  if (rows.length > 1) {
2988
- lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
2989
- lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
3287
+ const bars = Math.max(4, width - 8);
3288
+ lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: "muted" });
3289
+ lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: "muted" });
2990
3290
  lines.push({
2991
- text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
3291
+ text: truncate(`cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)), bars)}`, width),
2992
3292
  tone: "muted"
2993
3293
  });
2994
3294
  }
2995
- const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
2996
- const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
2997
- const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
2998
- const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
2999
- lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
3295
+ const columns = fitTable([
3296
+ { header: "period", width: 10, max: 24, cell: (row) => row.label },
3297
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
3298
+ { header: "sess", width: 6, align: "right", priority: 5, cell: (row) => row.sessions },
3299
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
3300
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
3301
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
3302
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
3303
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
3304
+ ], width);
3305
+ if (columns.length === 0)
3306
+ return [...lines, { text: truncate("no room for a table at this width", width), tone: "muted" }];
3307
+ const header = formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align));
3308
+ lines.push({ text: header, tone: HEADER_TONE });
3000
3309
  const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
3001
3310
  for (const row of newest) {
3002
3311
  const buckets = usageBuckets(row.usage);
3003
- const cells = [
3004
- row.label,
3005
- formatCount(row.steps),
3006
- ...withSessions ? [formatCount(row.sessions)] : [],
3007
- formatTokens(buckets.prompt),
3008
- formatTokens(buckets.cached),
3009
- formatPercent(buckets.hit, 0),
3010
- formatTokens(buckets.output),
3011
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3012
- ];
3013
- lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
3312
+ const view = {
3313
+ label: row.label,
3314
+ steps: formatCount(row.steps),
3315
+ sessions: formatCount(row.sessions),
3316
+ prompt: formatTokens(buckets.prompt),
3317
+ cached: formatTokens(buckets.cached),
3318
+ hit: formatPercent(buckets.hit, 0),
3319
+ output: formatTokens(buckets.output),
3320
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3321
+ };
3322
+ lines.push({
3323
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
3324
+ tone: "base",
3325
+ row: { kind: "period", value: row.key }
3326
+ });
3014
3327
  }
3015
3328
  lines.push({ text: "", tone: "muted" });
3329
+ const total = {
3330
+ label: "total",
3331
+ steps: formatCount(totals.steps),
3332
+ sessions: formatCount(totalSessions ?? totals.sessions),
3333
+ prompt: formatTokens(overall.prompt),
3334
+ cached: formatTokens(overall.cached),
3335
+ hit: formatPercent(overall.hit, 0),
3336
+ output: formatTokens(overall.output),
3337
+ cost: formatSpend(overall.cost, estimates ? overall.listCost : 0)
3338
+ };
3016
3339
  lines.push({
3017
- text: formatTableRow([
3018
- "total",
3019
- formatCount(totals.steps),
3020
- ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
3021
- formatTokens(overall.prompt),
3022
- formatTokens(overall.cached),
3023
- formatPercent(overall.hit, 0),
3024
- formatTokens(overall.output),
3025
- formatSpend(overall.cost, estimates ? overall.listCost : 0)
3026
- ], widths, aligns),
3340
+ text: formatTableRow(columns.map((column) => column.cell(total)), columns.map((column) => column.width), columns.map((column) => column.align)),
3027
3341
  tone: HEADER_TONE
3028
3342
  });
3029
3343
  if (rows.length === 0)
3030
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
3344
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
3031
3345
  return lines;
3032
3346
  }
3347
+ function latencyMetric(label, values, width) {
3348
+ const prefix = padCell(label, 11);
3349
+ let text = `${prefix}${values[0] ?? "\u2013"}`;
3350
+ for (let index = 1;index < values.length; index += 1) {
3351
+ const next = `${text} \xB7 ${values[index]}`;
3352
+ if (next.length > width)
3353
+ break;
3354
+ text = next;
3355
+ }
3356
+ return text;
3357
+ }
3033
3358
  function latencyLines(report, width, groups, limit = 12, estimates = true) {
3034
3359
  const lines = [];
3035
- lines.push({
3036
- 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]),
3037
- tone: "base"
3038
- });
3039
- lines.push({
3040
- 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]),
3041
- tone: "base"
3042
- });
3043
- lines.push({
3044
- 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]),
3045
- tone: "base"
3046
- });
3360
+ if (width >= 68) {
3361
+ lines.push({
3362
+ 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]),
3363
+ tone: "base"
3364
+ });
3365
+ lines.push({
3366
+ 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]),
3367
+ tone: "base"
3368
+ });
3369
+ lines.push({
3370
+ 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]),
3371
+ tone: "base"
3372
+ });
3373
+ } else {
3374
+ lines.push({
3375
+ text: latencyMetric("wall", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),
3376
+ tone: "base"
3377
+ });
3378
+ lines.push({
3379
+ text: latencyMetric("stream", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),
3380
+ tone: "base"
3381
+ });
3382
+ lines.push({
3383
+ text: latencyMetric("throughput", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
3384
+ tone: "base"
3385
+ });
3386
+ }
3047
3387
  lines.push({ text: "", tone: "muted" });
3048
3388
  lines.push({
3049
3389
  text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
3050
3390
  tone: "muted"
3051
3391
  });
3052
3392
  if (report.wall.count === 0)
3053
- lines.push({ text: "no completed steps for this range", tone: "muted" });
3393
+ lines.push({ text: truncate("no completed steps for this range", width), tone: "muted" });
3054
3394
  if (groups !== undefined && groups.length > 0) {
3055
3395
  lines.push({ text: "", tone: "muted" });
3056
3396
  lines.push({ text: "by group", tone: HEADER_TONE });
3057
- const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
3058
- const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
3059
- lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
3060
- for (const row of groups.slice(0, limit)) {
3061
- const thin = row.count < 5;
3062
- lines.push({
3063
- text: formatTableRow([
3064
- row.label,
3065
- formatCount(row.count),
3066
- formatMs(row.wall.p50),
3067
- formatMs(row.wall.p90),
3068
- formatMs(row.stream.p50),
3069
- formatTps(row.tps.p50),
3070
- formatTps(row.tps.p90),
3071
- formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
3072
- ], widths, aligns),
3073
- tone: thin ? "muted" : "base",
3074
- row: { kind: "model", value: row.key }
3075
- });
3397
+ const columns = fitTable([
3398
+ { header: "group", width: 8, max: 32, cell: (row) => row.label },
3399
+ { header: "n", width: 4, align: "right", cell: (row) => formatCount(row.count) },
3400
+ { header: "wall p50", width: 8, align: "right", cell: (row) => formatMs(row.wall.p50) },
3401
+ { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
3402
+ { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
3403
+ { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
3404
+ { header: "tps p90", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatTps(row.tps.p90) },
3405
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
3406
+ ], width);
3407
+ if (columns.length > 0) {
3408
+ lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: "muted" });
3409
+ for (const row of groups.slice(0, limit)) {
3410
+ const thin = row.count < 5;
3411
+ lines.push({
3412
+ text: formatTableRow(columns.map((column) => column.cell(row)), columns.map((column) => column.width), columns.map((column) => column.align)),
3413
+ tone: thin ? "muted" : "base",
3414
+ row: { kind: "model", value: row.key }
3415
+ });
3416
+ }
3076
3417
  }
3077
- lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
3418
+ lines.push({ text: truncate("n < 5 is dimmed: too few samples to compare", width), tone: "muted" });
3078
3419
  }
3079
3420
  return lines;
3080
3421
  }
3081
3422
  function sessionsLines(rows, width, options) {
3082
3423
  const limit = options?.limit ?? 20;
3083
3424
  const estimates = options?.estimates !== false;
3084
- const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
3085
- const aligns = ["left", "right", "right", "right", "right", "right", "right"];
3425
+ const columns = fitTable([
3426
+ { header: "title", width: 10, max: 48, cell: (row) => row.title },
3427
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
3428
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
3429
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
3430
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
3431
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
3432
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
3433
+ ], width);
3086
3434
  const lines = [
3087
- { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
3435
+ {
3436
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
3437
+ tone: HEADER_TONE
3438
+ }
3088
3439
  ];
3089
3440
  const byID = new Map(rows.map((row) => [row.sessionID, row]));
3090
3441
  const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
@@ -3092,18 +3443,18 @@ function sessionsLines(rows, width, options) {
3092
3443
  const orderedAll = [...ordered, ...children];
3093
3444
  for (const row of orderedAll.slice(0, limit)) {
3094
3445
  const child = row.parentID !== undefined && byID.has(row.parentID);
3095
- const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
3096
3446
  const buckets = usageBuckets(row);
3447
+ const view = {
3448
+ title: `${child ? "\u21B3 " : ""}${row.title ?? row.sessionID}`,
3449
+ steps: formatCount(buckets.steps),
3450
+ prompt: formatTokens(buckets.prompt),
3451
+ cached: formatTokens(buckets.cached),
3452
+ hit: formatPercent(buckets.hit, 0),
3453
+ output: formatTokens(buckets.output),
3454
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3455
+ };
3097
3456
  lines.push({
3098
- text: formatTableRow([
3099
- `${child ? "\u21B3 " : ""}${title}`,
3100
- formatCount(buckets.steps),
3101
- formatTokens(buckets.prompt),
3102
- formatTokens(buckets.cached),
3103
- formatPercent(buckets.hit, 0),
3104
- formatTokens(buckets.output),
3105
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3106
- ], widths, aligns),
3457
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
3107
3458
  tone: child ? "muted" : "base",
3108
3459
  row: { kind: "session", value: row.sessionID }
3109
3460
  });
@@ -3118,14 +3469,14 @@ function sessionsLines(rows, width, options) {
3118
3469
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
3119
3470
  lines.push({ text: "", tone: "muted" });
3120
3471
  lines.push({
3121
- 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)}`,
3472
+ 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),
3122
3473
  tone: "muted"
3123
3474
  });
3124
3475
  }
3125
3476
  if (rows.length > limit)
3126
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
3477
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, width), tone: "muted" });
3127
3478
  if (rows.length === 0)
3128
- lines.push({ text: "no sessions recorded for this range", tone: "muted" });
3479
+ lines.push({ text: truncate("no sessions recorded for this range", width), tone: "muted" });
3129
3480
  return lines;
3130
3481
  }
3131
3482
  function dbLines(data, width) {
@@ -3133,16 +3484,16 @@ function dbLines(data, width) {
3133
3484
  const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
3134
3485
  lines.push({ text: truncate(data.info.path, width), tone: "base" });
3135
3486
  lines.push({
3136
- text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
3487
+ text: truncate(`${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`, width),
3137
3488
  tone: "muted"
3138
3489
  });
3139
3490
  lines.push({ text: "", tone: "muted" });
3140
3491
  lines.push({ text: "what it holds", tone: HEADER_TONE });
3141
3492
  for (const table of data.info.tables) {
3142
- lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
3493
+ lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? "muted" : "base" });
3143
3494
  }
3144
3495
  lines.push({
3145
- 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")}`,
3496
+ 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),
3146
3497
  tone: "muted"
3147
3498
  });
3148
3499
  lines.push({ text: "", tone: "muted" });
@@ -3158,7 +3509,7 @@ function dbLines(data, width) {
3158
3509
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
3159
3510
  });
3160
3511
  }
3161
- const widths = [10, 13, 10];
3512
+ const widths = [9, 11, 10];
3162
3513
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
3163
3514
  for (const option of data.info.removable) {
3164
3515
  const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
@@ -3178,7 +3529,7 @@ function dbLines(data, width) {
3178
3529
  });
3179
3530
  if (data.busy === true) {
3180
3531
  lines.push({ text: "", tone: "muted" });
3181
- lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
3532
+ lines.push({ text: truncate("the recorder is writing: try the vacuum again in a moment", width), tone: "warning" });
3182
3533
  }
3183
3534
  return lines;
3184
3535
  }
@@ -3202,28 +3553,74 @@ function turnStats(turn) {
3202
3553
  steps: turn.steps
3203
3554
  };
3204
3555
  }
3556
+ function compactTurnLine(stats, width, options) {
3557
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
3558
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
3559
+ const estimates = options?.estimates !== false;
3560
+ const headParts = [];
3561
+ if (fields.clock && stats.endAt !== undefined)
3562
+ headParts.push(formatClock(stats.endAt));
3563
+ if (stats.providerID !== undefined) {
3564
+ let identity = stats.providerID;
3565
+ if (fields.model && stats.modelID !== undefined)
3566
+ identity += `/${stats.modelID}`;
3567
+ if (fields.variant && stats.variant)
3568
+ identity += ` ${stats.variant}`;
3569
+ headParts.push(identity);
3570
+ }
3571
+ let head = headParts.join(" ");
3572
+ const totals = options?.turnTotals === "sum" ? stats.totals : stats.latest;
3573
+ const display = displayTotals(totals);
3574
+ const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined;
3575
+ const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim();
3576
+ const warning = fields.cacheExpiry && stats.cacheExpired ? `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` \xD7${stats.drops.length}` : ""})` : undefined;
3577
+ let suffix = [warning, cost].filter((part) => part !== undefined).join(" \xB7 ");
3578
+ if (suffix !== "" && suffix.length + 3 > width)
3579
+ suffix = cost ?? suffix;
3580
+ head = truncate(head, Math.max(0, width - (suffix === "" ? 0 : suffix.length + 3)));
3581
+ if (!fields.turn || stats.totals.steps === 0)
3582
+ return [head, suffix].filter((part) => part !== "").join(" \xB7 ");
3583
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
3584
+ const volumes = [
3585
+ input,
3586
+ `${labels.cached} ${formatTokens(display.cached)}`,
3587
+ `${labels.output} ${formatTokens(display.output)}`,
3588
+ ...fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []
3589
+ ];
3590
+ let numbers = "";
3591
+ for (const volume of volumes) {
3592
+ const next = numbers === "" ? volume : `${numbers}, ${volume}`;
3593
+ if ([head, next, suffix].filter((part) => part !== "").join(" \xB7 ").length > width)
3594
+ break;
3595
+ numbers = next;
3596
+ }
3597
+ return [head, numbers, suffix].filter((part) => part !== "").join(" \xB7 ");
3598
+ }
3205
3599
  function turnsLines(rows, width, options) {
3206
3600
  const lines = [];
3207
3601
  const warning = rows.filter((turn) => turn.drops.length > 0).length;
3208
3602
  lines.push({
3209
- text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
3603
+ text: truncate(`${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`, width),
3210
3604
  tone: "muted"
3211
3605
  });
3212
3606
  const showSession = options?.sessionTitles !== undefined;
3213
3607
  for (const turn of rows) {
3214
- const line = formatLine(turnStats(turn), {
3608
+ const stats = turnStats(turn);
3609
+ const line = formatLine(stats, {
3215
3610
  ...options,
3216
3611
  fields: { ...options?.fields, session: false }
3217
3612
  });
3218
3613
  const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
3614
+ const available = Math.max(0, width - title.length);
3615
+ const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`;
3219
3616
  lines.push({
3220
- text: truncate(`${title}${line}`, width),
3617
+ text: truncate(text, width),
3221
3618
  tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
3222
3619
  row: { kind: "turn", value: turn.sessionID }
3223
3620
  });
3224
3621
  }
3225
3622
  if (rows.length === 0)
3226
- lines.push({ text: "no finished turns for this range", tone: "muted" });
3623
+ lines.push({ text: truncate("no finished turns for this range", width), tone: "muted" });
3227
3624
  return lines;
3228
3625
  }
3229
3626
  function sessionSummaryLines(usage, budget = 34, estimates = true) {
@@ -3323,11 +3720,12 @@ function detailLabel(row) {
3323
3720
  }
3324
3721
  }
3325
3722
  function buildPanel(request) {
3723
+ const width = clampPanelWidth(request.width);
3326
3724
  try {
3327
- return build(request);
3725
+ return build({ ...request, width }).map((line) => line.text.length <= width ? line : { ...line, text: truncate(line.text, width) });
3328
3726
  } catch (error) {
3329
3727
  const message = error instanceof Error ? error.message : String(error);
3330
- return [{ text: `stats query failed: ${message}`, tone: "warning" }];
3728
+ return [{ text: truncate(`stats query failed: ${message}`, width), tone: "warning" }];
3331
3729
  }
3332
3730
  }
3333
3731
  function build(request) {
@@ -3399,6 +3797,13 @@ function build(request) {
3399
3797
  }
3400
3798
  case "db":
3401
3799
  return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now, estimates }, width);
3800
+ case "go":
3801
+ return [
3802
+ {
3803
+ text: "OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.",
3804
+ tone: "muted"
3805
+ }
3806
+ ];
3402
3807
  case "turns": {
3403
3808
  const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
3404
3809
  const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
@@ -3434,10 +3839,15 @@ function buildDetail(request, range, filters, estimates) {
3434
3839
  const steps = stepRows(db, { range, filters: scoped });
3435
3840
  return [
3436
3841
  head,
3437
- {
3438
- text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 write ${formatTokens(stats.cacheWrite)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3439
- tone: "muted"
3440
- },
3842
+ ...kvGrid([
3843
+ ["steps", formatCount(stats.steps)],
3844
+ ["in", formatTokens(stats.prompt - stats.cached)],
3845
+ ["prompt", formatTokens(stats.prompt)],
3846
+ ["cached", formatTokens(stats.cached)],
3847
+ ["write", formatTokens(stats.cacheWrite)],
3848
+ ["hit", percent(stats.hit)],
3849
+ ["p50", percent(stats.hitP50)]
3850
+ ], width),
3441
3851
  { text: "", tone: "muted" },
3442
3852
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3443
3853
  { text: "", tone: "muted" },
@@ -3456,10 +3866,14 @@ function buildDetail(request, range, filters, estimates) {
3456
3866
  const stats = cacheStatsOf(db, { range, filters: scoped });
3457
3867
  return [
3458
3868
  head,
3459
- {
3460
- text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3461
- tone: "muted"
3462
- },
3869
+ ...kvGrid([
3870
+ ["steps", formatCount(stats.steps)],
3871
+ ["in", formatTokens(stats.prompt - stats.cached)],
3872
+ ["prompt", formatTokens(stats.prompt)],
3873
+ ["cached", formatTokens(stats.cached)],
3874
+ ["hit", percent(stats.hit)],
3875
+ ["p50", percent(stats.hitP50)]
3876
+ ], width),
3463
3877
  { text: "", tone: "muted" },
3464
3878
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3465
3879
  { text: "", tone: "muted" },
@@ -3754,7 +4168,7 @@ class ServiceError extends Error {
3754
4168
  this.code = code;
3755
4169
  }
3756
4170
  }
3757
- function clamp(value, minimum, maximum) {
4171
+ function clamp2(value, minimum, maximum) {
3758
4172
  if (!Number.isFinite(value))
3759
4173
  return minimum;
3760
4174
  return Math.min(maximum, Math.max(minimum, Math.round(value)));
@@ -3823,7 +4237,7 @@ function createService(db, options) {
3823
4237
  }
3824
4238
  function turnHistory(input) {
3825
4239
  const handle = db();
3826
- const width = clamp(input.width, 20, 120);
4240
+ const width = clamp2(input.width, 20, MAX_HISTORY_WIDTH);
3827
4241
  const limit = clampTurnsLimit(input.limit);
3828
4242
  const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
3829
4243
  const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
@@ -3852,7 +4266,7 @@ function createService(db, options) {
3852
4266
  function prune(input) {
3853
4267
  requireMaintenance();
3854
4268
  requireConfirm(input.confirm);
3855
- const days = clamp(input.days, 1, MAX_DAYS);
4269
+ const days = clamp2(input.days, 1, MAX_DAYS);
3856
4270
  return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY2));
3857
4271
  }
3858
4272
  function wipe(input) {
@@ -4350,4 +4764,4 @@ export {
4350
4764
  src_default as default
4351
4765
  };
4352
4766
 
4353
- //# debugId=15B300D932EB268164756E2164756E21
4767
+ //# debugId=C871242EEDE4D90F64756E2164756E21