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/tui.js CHANGED
@@ -5,7 +5,7 @@ import { createElement as _$createElement3 } from "@opentui/solid";
5
5
  import { createComponent as _$createComponent3 } from "@opentui/solid";
6
6
  import { Plugin } from "@opencode/plugin/tui";
7
7
  import { StyledText, fg } from "@opentui/core";
8
- import { Show as Show3, createEffect as createEffect3, createMemo as createMemo3, createRenderEffect as createRenderEffect2, createSignal as createSignal3 } from "solid-js";
8
+ import { Show as Show3, createEffect as createEffect3, createMemo as createMemo3, createRenderEffect as createRenderEffect2, createSignal as createSignal3, onCleanup as onCleanup2 } from "solid-js";
9
9
 
10
10
  // src/core.ts
11
11
  var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
@@ -353,6 +353,7 @@ function formatLine(stats, options) {
353
353
 
354
354
  // src/limits.ts
355
355
  var MAX_PANEL_WIDTH = 200;
356
+ var MAX_HISTORY_WIDTH = 120;
356
357
  var MAX_TURNS = 50;
357
358
  function clampPanelWidth(value) {
358
359
  if (!Number.isFinite(value))
@@ -966,9 +967,128 @@ function filterOptions(db) {
966
967
  return { models: pick("model_id"), providers: pick("provider_id") };
967
968
  }
968
969
 
970
+ // src/quota.ts
971
+ var QUOTA_VIEW = "go";
972
+ var QUOTA_POLL_MS = 60000;
973
+ var DEFAULT_QUOTA_NAME = "OpenCode Go";
974
+ var DAY_MS = 24 * 60 * 60 * 1000;
975
+ var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
976
+ function quotaNameOf(explicit, providerName) {
977
+ const custom = explicit?.trim();
978
+ if (custom !== undefined && custom !== "")
979
+ return custom;
980
+ const provider = providerName?.trim();
981
+ if (provider !== undefined && provider !== "")
982
+ return provider;
983
+ return DEFAULT_QUOTA_NAME;
984
+ }
985
+ function finite(value) {
986
+ return typeof value === "number" && Number.isFinite(value);
987
+ }
988
+ function clamp(value, minimum, maximum) {
989
+ return Math.min(maximum, Math.max(minimum, value));
990
+ }
991
+ function previousCycleStart(endAt) {
992
+ if (!finite(endAt))
993
+ return endAt;
994
+ const end = new Date(endAt);
995
+ const year = end.getUTCFullYear();
996
+ const month = end.getUTCMonth();
997
+ const day = end.getUTCDate();
998
+ const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
999
+ const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
1000
+ start.setUTCDate(Math.min(day, lastDay));
1001
+ return start.getTime();
1002
+ }
1003
+ function forecastMonthly(meter, now) {
1004
+ const endAt = finite(meter.resetsAt) ? meter.resetsAt : now;
1005
+ const startAt = previousCycleStart(endAt);
1006
+ const total = Math.max(1, endAt - startAt);
1007
+ const elapsedMs = clamp(now - startAt, 0, total);
1008
+ const remainingMs = Math.max(0, endAt - now);
1009
+ const percent = clamp(finite(meter.percent) ? meter.percent : 0, 0, 100);
1010
+ const reached = meter.limited === true || percent >= 100;
1011
+ const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
1012
+ const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
1013
+ const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
1014
+ const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
1015
+ const willExhaust = exhaustAt !== undefined;
1016
+ const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
1017
+ return {
1018
+ startAt,
1019
+ endAt,
1020
+ elapsedMs,
1021
+ remainingMs,
1022
+ ratePerDay,
1023
+ projectedPercent,
1024
+ ...exhaustAt !== undefined ? { exhaustAt } : {},
1025
+ reached,
1026
+ available,
1027
+ willExhaust
1028
+ };
1029
+ }
1030
+ function quotaBar(percent, width = 10) {
1031
+ const value = clamp(finite(percent) ? percent : 0, 0, 100);
1032
+ const cells = Math.max(1, Math.round(width));
1033
+ const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
1034
+ return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
1035
+ }
1036
+ function formatRenewal(at, timeZone) {
1037
+ if (!finite(at))
1038
+ return "\u2013";
1039
+ try {
1040
+ return new Intl.DateTimeFormat("en-GB", {
1041
+ day: "2-digit",
1042
+ month: "short",
1043
+ year: "numeric",
1044
+ hour: "2-digit",
1045
+ minute: "2-digit",
1046
+ hour12: false,
1047
+ ...timeZone !== undefined ? { timeZone } : {}
1048
+ }).format(new Date(at)).replace(/,/g, "");
1049
+ } catch {
1050
+ return "\u2013";
1051
+ }
1052
+ }
1053
+ function formatRenewalCompact(at, timeZone) {
1054
+ if (!finite(at))
1055
+ return "\u2013";
1056
+ try {
1057
+ return new Intl.DateTimeFormat("en-GB", {
1058
+ day: "2-digit",
1059
+ month: "short",
1060
+ hour: "2-digit",
1061
+ minute: "2-digit",
1062
+ hour12: false,
1063
+ ...timeZone !== undefined ? { timeZone } : {}
1064
+ }).format(new Date(at)).replace(/,/g, "");
1065
+ } catch {
1066
+ return "\u2013";
1067
+ }
1068
+ }
1069
+ function formatCountdown(at, now) {
1070
+ const remaining = at - now;
1071
+ if (!finite(remaining))
1072
+ return "\u2013";
1073
+ if (remaining <= 0)
1074
+ return "due";
1075
+ return formatDuration(remaining);
1076
+ }
1077
+ function quotaStatus(quota) {
1078
+ const limited = [];
1079
+ if (quota.rolling.limited || quota.rolling.percent >= 100)
1080
+ limited.push("5-hour");
1081
+ if (quota.weekly.limited || quota.weekly.percent >= 100)
1082
+ limited.push("weekly");
1083
+ if (quota.monthly.limited || quota.monthly.percent >= 100)
1084
+ limited.push("monthly");
1085
+ return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
1086
+ }
1087
+
969
1088
  // src/panel-data.ts
970
1089
  var PANEL_NAME = "usage-insights";
971
1090
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
1091
+ var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
972
1092
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
973
1093
  var GRANULARITIES = ["day", "week", "month"];
974
1094
  var SORT_KEYS = {
@@ -993,13 +1113,13 @@ function nextSort(view, current, step) {
993
1113
  return keys[0];
994
1114
  return keys[(index + step + keys.length) % keys.length];
995
1115
  }
996
- function parseArgs(input) {
1116
+ function parseArgs(input, views = CLIENT_VIEWS) {
997
1117
  const parsed = {};
998
1118
  for (const token of (input ?? "").split(/\s+/)) {
999
1119
  const value = token.trim().toLowerCase();
1000
1120
  if (value === "")
1001
1121
  continue;
1002
- if (PANEL_VIEWS.includes(value))
1122
+ if (views.includes(value))
1003
1123
  parsed.view = value;
1004
1124
  else if (RANGE_KEYS.includes(value))
1005
1125
  parsed.range = value;
@@ -1036,10 +1156,10 @@ var DEFAULT_SETTINGS = {
1036
1156
  modelID: "",
1037
1157
  providerID: ""
1038
1158
  };
1039
- function sanitizeSettings(raw) {
1159
+ function sanitizeSettings(raw, views = CLIENT_VIEWS) {
1040
1160
  const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
1041
1161
  return {
1042
- view: PANEL_VIEWS.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1162
+ view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1043
1163
  range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
1044
1164
  sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
1045
1165
  sortDesc: settings.sortDesc === true,
@@ -1107,15 +1227,6 @@ function truncateMiddle(value, width) {
1107
1227
  const tail = width - 1 - head;
1108
1228
  return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
1109
1229
  }
1110
- function tableWidths(width, layouts) {
1111
- for (const layout of layouts) {
1112
- const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
1113
- if (total <= width)
1114
- return [...layout];
1115
- }
1116
- const last = layouts[layouts.length - 1];
1117
- return last === undefined ? [] : [...last];
1118
- }
1119
1230
  function modelCell(modelID, variant, width) {
1120
1231
  return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
1121
1232
  }
@@ -1134,6 +1245,47 @@ function formatTableRow(cells, widths, aligns) {
1134
1245
  }
1135
1246
  return parts.join(" ");
1136
1247
  }
1248
+ function fitTableColumns(columns, width) {
1249
+ const chosen = new Set;
1250
+ for (let index = 0;index < columns.length; index += 1) {
1251
+ if (columns[index].priority === undefined)
1252
+ chosen.add(index);
1253
+ }
1254
+ if (chosen.size === 0)
1255
+ return [];
1256
+ const total = () => {
1257
+ let sum = chosen.size - 1;
1258
+ for (const index of chosen)
1259
+ sum += columns[index].width;
1260
+ return sum;
1261
+ };
1262
+ 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);
1263
+ for (const { column, index } of optional) {
1264
+ if (total() + column.width + 1 + (column.reserve ?? 0) <= width)
1265
+ chosen.add(index);
1266
+ }
1267
+ while (chosen.size > 1 && total() > width)
1268
+ chosen.delete(Math.max(...chosen));
1269
+ const widths = new Map;
1270
+ let room = width - total();
1271
+ for (let index = 0;index < columns.length && room > 0; index += 1) {
1272
+ if (!chosen.has(index))
1273
+ continue;
1274
+ const column = columns[index];
1275
+ const grow = Math.min(room, (column.max ?? column.width) - column.width);
1276
+ if (grow <= 0)
1277
+ continue;
1278
+ widths.set(index, column.width + grow);
1279
+ room -= grow;
1280
+ }
1281
+ return [...chosen].sort((left, right) => left - right).map((index) => ({ index, width: widths.get(index) ?? columns[index].width }));
1282
+ }
1283
+ function fitTable(columns, width) {
1284
+ return fitTableColumns(columns, width).map(({ index, width: fitted }) => {
1285
+ const column = columns[index];
1286
+ return { index, header: column.header, width: fitted, align: column.align ?? "left", cell: column.cell };
1287
+ });
1288
+ }
1137
1289
  function count(n, singular, plural = `${singular}s`) {
1138
1290
  return `${formatCount(n)} ${n === 1 ? singular : plural}`;
1139
1291
  }
@@ -1141,21 +1293,30 @@ function kvGrid(pairs, width) {
1141
1293
  const lines = [];
1142
1294
  const label = 11;
1143
1295
  const column = Math.floor(width / 2);
1296
+ const pairLines = (pair) => {
1297
+ const text = `${padCell(pair[0], label)}${pair[1]}`;
1298
+ if (text.length <= width)
1299
+ return [text];
1300
+ return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width));
1301
+ };
1144
1302
  for (let index = 0;index < pairs.length; index += 2) {
1145
1303
  const left = pairs[index];
1146
1304
  const right = pairs[index + 1];
1147
- const leftText = `${padCell(left[0], label)}${left[1]}`;
1148
1305
  if (right === undefined) {
1149
- lines.push({ text: leftText, tone: "base" });
1306
+ for (const text of pairLines(left))
1307
+ lines.push({ text, tone: "base" });
1150
1308
  continue;
1151
1309
  }
1310
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
1152
1311
  const rightText = `${padCell(right[0], label)}${right[1]}`;
1153
1312
  const gap = Math.max(2, column - leftText.length);
1154
1313
  if (leftText.length + gap + rightText.length <= width) {
1155
1314
  lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
1156
1315
  } else {
1157
- lines.push({ text: leftText, tone: "base" });
1158
- lines.push({ text: rightText, tone: "base" });
1316
+ for (const text of pairLines(left))
1317
+ lines.push({ text, tone: "base" });
1318
+ for (const text of pairLines(right))
1319
+ lines.push({ text, tone: "base" });
1159
1320
  }
1160
1321
  }
1161
1322
  return lines;
@@ -1196,25 +1357,28 @@ function usageBuckets(usage) {
1196
1357
  hit: prompt > 0 ? usage.cached / prompt : undefined
1197
1358
  };
1198
1359
  }
1199
- function viewBar(view, width = 200) {
1360
+ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
1200
1361
  const key = (index) => String((index + 1) % 10);
1201
- const full = PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
1202
- const candidates = [full, PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
1362
+ const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
1363
+ const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
1203
1364
  for (const parts of candidates) {
1204
1365
  const text = parts.join(" ");
1205
1366
  if (text.length <= width)
1206
1367
  return { text, tone: "muted" };
1207
1368
  }
1208
- return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
1369
+ const index = views.indexOf(view);
1370
+ return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
1209
1371
  }
1210
1372
  function keysFor(of) {
1373
+ if (of === QUOTA_VIEW)
1374
+ return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
1211
1375
  if (of === "db")
1212
- 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";
1376
+ 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";
1213
1377
  if (of === "periods")
1214
- 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";
1378
+ 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";
1215
1379
  if (of === "turns")
1216
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1217
- 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";
1380
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
1381
+ 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";
1218
1382
  }
1219
1383
  function filterSummary(filters) {
1220
1384
  const parts = [];
@@ -1231,7 +1395,7 @@ function helpLines(width) {
1231
1395
  const lines = [
1232
1396
  { text: "keys", tone: HEADER_TONE },
1233
1397
  { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
1234
- { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
1398
+ { text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
1235
1399
  { text: " t shift+t previous / next range" },
1236
1400
  { text: " s shift+s cycle sort column \xB7 reverse" },
1237
1401
  { text: " b periods bucket: day \u2192 week \u2192 month" },
@@ -1240,6 +1404,13 @@ function helpLines(width) {
1240
1404
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
1241
1405
  { text: " e db: backfill list-price estimates for the $0 steps" },
1242
1406
  { text: "" },
1407
+ { text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
1408
+ { text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
1409
+ { text: " forecast the monthly percentage at its reset, from the" },
1410
+ { text: " cycle's average pace (not a sample history)" },
1411
+ { text: " renews the monthly reset reported by the host" },
1412
+ { text: " the plugin reads the host's local usage-limits endpoint;" },
1413
+ { text: " it never reads your API key and never talks to the Console." },
1243
1414
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
1244
1415
  { text: " prompt everything the provider saw: cached + fresh + writes" },
1245
1416
  { text: " in the uncached part: fresh input + cache writes" },
@@ -1274,6 +1445,101 @@ function helpLines(width) {
1274
1445
  ];
1275
1446
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1276
1447
  }
1448
+ function quotaMeterLine(label, meter, now) {
1449
+ const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
1450
+ const countdown = formatCountdown(meter.resetsAt, now);
1451
+ return {
1452
+ text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
1453
+ tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
1454
+ };
1455
+ }
1456
+ function goQuotaLines(state, options) {
1457
+ const { now, width, loading, error } = options;
1458
+ const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
1459
+ const lines = [];
1460
+ const push = (text, tone = "base") => {
1461
+ lines.push({ text, tone });
1462
+ };
1463
+ if (state === undefined) {
1464
+ if (error !== undefined && error !== "")
1465
+ push(`Go quota unavailable: ${error}`, "warning");
1466
+ else if (loading === true)
1467
+ push("reading OpenCode Go quota\u2026", "muted");
1468
+ else
1469
+ push("OpenCode Go quota is unavailable", "muted");
1470
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1471
+ }
1472
+ if (state.kind === "none") {
1473
+ push(name, "accent");
1474
+ push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
1475
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1476
+ }
1477
+ const quota = state.quota;
1478
+ const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
1479
+ const status = quotaStatus(quota);
1480
+ const forecast = forecastMonthly(quota.monthly, now);
1481
+ push(`${name} \xB7 ${workspace}`, "accent");
1482
+ push(`status ${status}`, status === "active" ? "base" : "warning");
1483
+ lines.push(quotaMeterLine("rolling", quota.rolling, now));
1484
+ lines.push(quotaMeterLine("weekly", quota.weekly, now));
1485
+ lines.push(quotaMeterLine("monthly", quota.monthly, now));
1486
+ push("");
1487
+ if (forecast.reached || quota.monthly.limited) {
1488
+ push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
1489
+ } else if (now >= forecast.endAt) {
1490
+ push("forecast monthly reset due \xB7 refresh", "warning");
1491
+ } else if (!forecast.available) {
1492
+ push("forecast too early in the cycle to project a monthly pace", "muted");
1493
+ } else if (quota.monthly.percent === 0) {
1494
+ push("forecast no monthly usage yet this cycle", "muted");
1495
+ } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
1496
+ push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
1497
+ } else {
1498
+ const projected = Math.min(999, Math.round(forecast.projectedPercent));
1499
+ const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
1500
+ push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
1501
+ }
1502
+ const renewal = formatRenewal(quota.monthly.resetsAt);
1503
+ const countdown = formatCountdown(quota.monthly.resetsAt, now);
1504
+ push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
1505
+ if (quota.workspace?.usageURL !== undefined)
1506
+ push(`console ${quota.workspace.usageURL}`, "muted");
1507
+ const age = Math.max(0, now - quota.observedAt);
1508
+ push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
1509
+ if (loading === true)
1510
+ push("refreshing\u2026", "muted");
1511
+ if (error !== undefined && error !== "")
1512
+ push(`quota refresh failed: ${error}`, "warning");
1513
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1514
+ }
1515
+ function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
1516
+ if (state?.kind !== "ok" || width <= 0)
1517
+ return [];
1518
+ const quota = state.quota;
1519
+ const status = quotaStatus(quota);
1520
+ const forecast = forecastMonthly(quota.monthly, now);
1521
+ const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
1522
+ const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
1523
+ let forecastText = "forecast too early";
1524
+ let forecastTone = "muted";
1525
+ if (forecast.reached || quota.monthly.limited) {
1526
+ forecastText = "monthly limit reached";
1527
+ forecastTone = "warning";
1528
+ } else if (forecast.willExhaust) {
1529
+ forecastText = "limit before renewal";
1530
+ forecastTone = "warning";
1531
+ } else if (forecast.available && quota.monthly.percent > 0) {
1532
+ forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
1533
+ } else if (forecast.available && quota.monthly.percent === 0) {
1534
+ forecastText = "forecast no usage yet";
1535
+ }
1536
+ return [
1537
+ { text: truncate(name, width), tone: "accent" },
1538
+ { text: truncate(base, width), tone: baseTone },
1539
+ { text: truncate(forecastText, width), tone: forecastTone },
1540
+ { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
1541
+ ];
1542
+ }
1277
1543
  function usagePairs(usage, estimates = true) {
1278
1544
  if (usage === undefined)
1279
1545
  return [];
@@ -1301,14 +1567,16 @@ function overviewLines(data, width) {
1301
1567
  const lines = [];
1302
1568
  const estimates = data.estimates !== false;
1303
1569
  lines.push({
1304
- text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
1570
+ text: truncate(`${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`, width),
1305
1571
  tone: "muted"
1306
1572
  });
1307
1573
  lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
1308
1574
  if (data.activity !== undefined && data.activity.length > 1) {
1309
- const series = reduceSeries(data.activity);
1575
+ const suffix = ` ${count(data.activity.length, "bucket")}`;
1576
+ const bars = Math.max(4, width - "activity ".length - suffix.length);
1577
+ const series = reduceSeries(data.activity, bars);
1310
1578
  lines.push({ text: "", tone: "muted" });
1311
- lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
1579
+ lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: "muted" });
1312
1580
  }
1313
1581
  if (data.session !== undefined) {
1314
1582
  lines.push({ text: "", tone: "muted" });
@@ -1319,7 +1587,7 @@ function overviewLines(data, width) {
1319
1587
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
1320
1588
  const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
1321
1589
  lines.push({
1322
- text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
1590
+ text: truncate(` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`, width),
1323
1591
  tone: "muted"
1324
1592
  });
1325
1593
  }
@@ -1351,65 +1619,33 @@ function coveragePairs(coverage) {
1351
1619
  ]
1352
1620
  ];
1353
1621
  }
1354
- function modelColumns(width) {
1355
- const layouts = [
1356
- { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
1357
- { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
1358
- { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
1359
- { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
1360
- { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
1361
- ];
1362
- for (const layout of layouts) {
1363
- const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
1364
- if (total <= width)
1365
- return layout;
1366
- }
1367
- return layouts[layouts.length - 1];
1368
- }
1369
1622
  function modelsLines(rows, width, extras, limit = 40, estimates = true) {
1370
- const columns = modelColumns(width);
1371
- const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
1372
- const aligns = ["left", "right", "right", "right"];
1373
- const header = ["model", "steps", "prompt", "cached"];
1374
- if (columns.hit > 0) {
1375
- widths.push(columns.hit);
1376
- aligns.push("right");
1377
- header.push("hit");
1378
- }
1379
- widths.push(columns.out);
1380
- aligns.push("right");
1381
- header.push("out");
1382
- if (columns.cost > 0) {
1383
- widths.push(columns.cost);
1384
- aligns.push("right");
1385
- header.push("cost");
1386
- }
1387
- if (columns.spread > 0) {
1388
- widths.push(columns.spread);
1389
- aligns.push("left");
1390
- header.push("providers");
1391
- }
1392
- const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
1623
+ let modelWidth = 14;
1624
+ const columns = fitTable([
1625
+ { header: "model", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },
1626
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
1627
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => row.prompt },
1628
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => row.cached },
1629
+ { header: "hit", width: 6, max: 7, priority: 2, reserve: 10, align: "right", cell: (row) => row.hit },
1630
+ { header: "out", width: 7, max: 9, priority: 3, reserve: 10, align: "right", cell: (row) => row.output },
1631
+ { header: "cost", width: 8, max: 9, priority: 1, align: "right", cell: (row) => row.cost },
1632
+ { header: "providers", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers }
1633
+ ], width);
1634
+ modelWidth = columns.find((column) => column.index === 0)?.width ?? 0;
1635
+ if (columns.length === 0)
1636
+ return [{ text: truncate("no room for a table at this width", width), tone: "muted" }];
1637
+ const lines = [
1638
+ {
1639
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
1640
+ tone: HEADER_TONE
1641
+ }
1642
+ ];
1393
1643
  for (const model of rows.slice(0, limit)) {
1394
1644
  const key = modelKey(model.modelID, model.variant);
1395
- const name = modelCell(model.modelID, model.variant, columns.model);
1396
1645
  const buckets = usageBuckets(model.totals);
1397
1646
  const providers = unique(model.providers.map((provider) => provider.providerID));
1398
1647
  const cache = extras?.cache?.get(key);
1399
1648
  const switches = extras?.switches?.get(key);
1400
- const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
1401
- if (columns.hit > 0)
1402
- cells.push(formatPercent(cache?.hit ?? buckets.hit));
1403
- cells.push(formatTokens(buckets.output));
1404
- if (columns.cost > 0)
1405
- cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
1406
- if (columns.spread > 0)
1407
- cells.push(providers.join(", "));
1408
- lines.push({
1409
- text: formatTableRow(cells, widths, aligns),
1410
- tone: "base",
1411
- row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
1412
- });
1413
1649
  const details = [];
1414
1650
  if (cache !== undefined)
1415
1651
  details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
@@ -1419,62 +1655,76 @@ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
1419
1655
  if (switches.cacheLost > 0)
1420
1656
  details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
1421
1657
  }
1422
- if (details.length > 0) {
1423
- lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
1658
+ const view = {
1659
+ modelID: model.modelID,
1660
+ variant: model.variant,
1661
+ steps: formatCount(buckets.steps),
1662
+ prompt: formatTokens(buckets.prompt),
1663
+ cached: formatTokens(buckets.cached),
1664
+ hit: formatPercent(cache?.hit ?? buckets.hit),
1665
+ output: formatTokens(buckets.output),
1666
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),
1667
+ providers: providers.join(", "),
1668
+ detail: details.join(" \xB7 ")
1669
+ };
1670
+ lines.push({
1671
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
1672
+ tone: "base",
1673
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
1674
+ });
1675
+ if (view.detail !== "") {
1676
+ lines.push({ text: truncate(`${" ".repeat(modelWidth + 1)}${view.detail}`, width), tone: "muted" });
1424
1677
  }
1425
1678
  }
1426
1679
  if (rows.length > limit)
1427
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
1680
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, width), tone: "muted" });
1428
1681
  if (rows.length === 0)
1429
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
1682
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
1430
1683
  return lines;
1431
1684
  }
1432
1685
  function unique(values) {
1433
1686
  return [...new Set(values)];
1434
1687
  }
1435
- var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
1436
- function fitColumns(columns, width) {
1437
- const chosen = [...columns];
1438
- while (chosen.length > 1 && tableWidth(chosen) > width) {
1439
- const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
1440
- if (optional === -1)
1441
- break;
1442
- chosen.splice(chosen.length - 1 - optional, 1);
1443
- }
1444
- return chosen;
1445
- }
1446
1688
  function renderTable(rows, columns, width, options) {
1447
- const chosen = fitColumns(columns, width);
1689
+ const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {
1690
+ const column = columns[index];
1691
+ const align = column.align ?? "left";
1692
+ return { ...column, width: fitted, align };
1693
+ });
1694
+ if (chosen.length === 0)
1695
+ return [{ text: truncate(options.empty, width), tone: "muted" }];
1448
1696
  const widths = chosen.map((column) => column.width);
1449
- const aligns = chosen.map((column) => column.align ?? "left");
1450
- const alignsTyped = aligns;
1451
- const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
1697
+ const aligns = chosen.map((column) => column.align);
1698
+ const lines = [
1699
+ { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE }
1700
+ ];
1452
1701
  if (rows.length === 0)
1453
- lines.push({ text: options.empty, tone: "muted" });
1702
+ lines.push({ text: truncate(options.empty, width), tone: "muted" });
1454
1703
  for (const row of rows.slice(0, options.limit)) {
1455
1704
  const identity = options.row?.(row);
1456
1705
  lines.push({
1457
- text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
1706
+ text: formatTableRow(chosen.map((column) => column.cell(row, column.width)), widths, aligns),
1458
1707
  tone: options.tone?.(row) ?? "base",
1459
1708
  ...identity === undefined ? {} : { row: identity }
1460
1709
  });
1461
1710
  }
1462
- if (rows.length > options.limit)
1463
- lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
1711
+ if (rows.length > options.limit) {
1712
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - options.limit, "more row")}`, width), tone: "muted" });
1713
+ }
1464
1714
  return lines;
1465
1715
  }
1466
1716
  function providerSummaryLines(rows, width, limit = 40, estimates = true) {
1467
1717
  const lines = renderTable(rows, [
1468
- { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
1469
- { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
1718
+ { header: "provider", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
1719
+ { header: "models", width: 6, align: "right", priority: 4, cell: (row) => formatCount(row.models.length) },
1470
1720
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
1471
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
1472
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1473
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1474
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1475
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1476
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1477
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1721
+ { header: "share", width: 6, align: "right", priority: 3, cell: (row) => formatPercent(row.share, 0) },
1722
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1723
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1724
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
1725
+ { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
1726
+ { header: "wall", width: 7, align: "right", priority: 6, cell: (row) => formatMs(row.wall) },
1727
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1478
1728
  ], width, {
1479
1729
  limit,
1480
1730
  empty: "no usage recorded for this range",
@@ -1485,16 +1735,16 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
1485
1735
  }
1486
1736
  function providerLines(rows, width, limit = 40, estimates = true) {
1487
1737
  return renderTable(rows, [
1488
- { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
1489
- { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
1738
+ { header: "model", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },
1739
+ { header: "provider", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
1490
1740
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
1491
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
1492
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1493
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1494
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1495
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1496
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1497
- { 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: 5, cell: (row) => formatPercent(row.share, 0) },
1742
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },
1743
+ { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
1744
+ { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
1745
+ { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
1746
+ { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
1747
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1498
1748
  ], width, {
1499
1749
  limit,
1500
1750
  empty: "no usage recorded for this range",
@@ -1504,80 +1754,126 @@ function providerLines(rows, width, limit = 40, estimates = true) {
1504
1754
  }
1505
1755
  function cacheLines(data, width) {
1506
1756
  const lines = [];
1757
+ const push = (text, tone = "base") => {
1758
+ lines.push({ text: truncate(text, width), tone });
1759
+ };
1507
1760
  const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
1508
- lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
1761
+ push(`reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, total > 0 ? "warning" : "base");
1509
1762
  for (const reason of ["expired", "compaction", "unknown"]) {
1510
1763
  const group = data.drops.filter((drop) => drop.reason === reason);
1511
1764
  if (group.length === 0)
1512
1765
  continue;
1513
1766
  const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
1514
- lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
1767
+ push(` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, reason === "expired" ? "warning" : "muted");
1515
1768
  }
1516
1769
  if (data.drops.length === 0)
1517
- lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
1770
+ push(" none: prompt cache held through every gap", "muted");
1518
1771
  if (data.models !== undefined && data.models.length > 0) {
1519
1772
  lines.push({ text: "", tone: "muted" });
1520
- lines.push({ text: "reuse by model", tone: HEADER_TONE });
1521
- const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
1522
- lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
1523
- for (const row of data.models.slice(0, 10)) {
1524
- const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
1525
- lines.push({
1526
- 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"]),
1527
- tone: "base",
1528
- row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
1529
- });
1773
+ push("reuse by model", HEADER_TONE);
1774
+ let modelWidth = 12;
1775
+ const reuse = fitTable([
1776
+ { header: "model", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },
1777
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.cache.steps) },
1778
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
1779
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
1780
+ { header: "write", width: 6, max: 8, align: "right", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },
1781
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
1782
+ { header: "hit p50", width: 7, max: 9, align: "right", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) }
1783
+ ], width);
1784
+ modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0;
1785
+ if (reuse.length > 0) {
1786
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
1787
+ for (const row of data.models.slice(0, 10)) {
1788
+ lines.push({
1789
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
1790
+ tone: "base",
1791
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
1792
+ });
1793
+ }
1530
1794
  }
1531
1795
  }
1532
1796
  if (data.gap !== undefined && data.gap.samples > 0) {
1533
1797
  lines.push({ text: "", tone: "muted" });
1534
- lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
1535
- const widths = [9, 8, 9, 9, 10];
1536
- lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
1537
- for (const bucket of data.gap.buckets) {
1538
- if (bucket.samples === 0)
1539
- continue;
1540
- lines.push({
1541
- text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
1542
- tone: bucket.drops > 0 ? "warning" : "base"
1543
- });
1798
+ push("cache survival against idle time", HEADER_TONE);
1799
+ const buckets = data.gap.buckets;
1800
+ const survival = fitTable([
1801
+ { header: "gap", width: 8, max: 12, cell: (bucket) => bucket.label },
1802
+ { header: "pairs", width: 6, align: "right", cell: (bucket) => formatCount(bucket.samples) },
1803
+ { header: "kept", width: 7, align: "right", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },
1804
+ { header: "drops", width: 7, align: "right", cell: (bucket) => formatCount(bucket.drops) },
1805
+ { header: "lost", width: 8, align: "right", cell: (bucket) => formatTokens(bucket.lostTokens) }
1806
+ ], width);
1807
+ if (survival.length > 0) {
1808
+ lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: "muted" });
1809
+ for (const bucket of buckets) {
1810
+ if (bucket.samples === 0)
1811
+ continue;
1812
+ lines.push({
1813
+ text: formatTableRow(survival.map((column) => column.cell(bucket)), survival.map((column) => column.width), survival.map((column) => column.align)),
1814
+ tone: bucket.drops > 0 ? "warning" : "base"
1815
+ });
1816
+ }
1544
1817
  }
1545
1818
  if (data.gap.providers.length > 1) {
1546
1819
  lines.push({ text: "", tone: "muted" });
1547
- lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
1548
- const providerWidths = [26, 8, 9, 9];
1549
- lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
1550
- for (const row of data.gap.providers.slice(0, 8)) {
1551
- lines.push({
1552
- text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
1553
- tone: "base"
1554
- });
1820
+ push("reuse kept, by provider", HEADER_TONE);
1821
+ const providers = data.gap.providers;
1822
+ const reuse = fitTable([
1823
+ { header: "provider", width: 12, max: 30, cell: (row) => row.provider },
1824
+ { header: "pairs", width: 6, align: "right", cell: (row) => formatCount(row.samples) },
1825
+ { header: "kept", width: 7, align: "right", cell: (row) => formatPercent(row.retainedRatio, 0) },
1826
+ { header: "lost", width: 8, align: "right", cell: (row) => formatTokens(row.lostTokens) }
1827
+ ], width);
1828
+ if (reuse.length > 0) {
1829
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
1830
+ for (const row of providers.slice(0, 8)) {
1831
+ lines.push({
1832
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
1833
+ tone: "base"
1834
+ });
1835
+ }
1555
1836
  }
1556
1837
  }
1557
1838
  }
1558
1839
  lines.push({ text: "", tone: "muted" });
1559
- lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
1840
+ push("observed cache TTL bounds", HEADER_TONE);
1560
1841
  if (data.evidence.length === 0) {
1561
- lines.push({ text: " no comparable step pairs yet", tone: "muted" });
1842
+ push(" no comparable step pairs yet", "muted");
1562
1843
  } else {
1563
- const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
1564
- lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
1565
- for (const row of data.evidence.slice(0, 10)) {
1566
- lines.push({
1567
- text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
1568
- tone: "base"
1569
- });
1844
+ const evidence = fitTable([
1845
+ { header: "model", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },
1846
+ { header: "hits up to", width: 10, align: "right", cell: (row) => formatGap(row.maxHitGapMs) },
1847
+ { header: "drops from", width: 10, align: "right", cell: (row) => formatGap(row.minDropGapMs) },
1848
+ { header: "samples", width: 7, align: "right", priority: 1, cell: (row) => formatCount(row.samples) }
1849
+ ], width);
1850
+ if (evidence.length > 0) {
1851
+ lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: "muted" });
1852
+ for (const row of data.evidence.slice(0, 10)) {
1853
+ lines.push({
1854
+ text: formatTableRow(evidence.map((column) => column.cell(row)), evidence.map((column) => column.width), evidence.map((column) => column.align)),
1855
+ tone: "base"
1856
+ });
1857
+ }
1570
1858
  }
1571
1859
  }
1572
1860
  if (data.drops.length > 0) {
1573
1861
  lines.push({ text: "", tone: "muted" });
1574
- lines.push({ text: "recent losses", tone: HEADER_TONE });
1575
- for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
1576
- const when = new Date(drop.at).toLocaleTimeString("en-GB");
1577
- lines.push({
1578
- 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"]),
1579
- tone: drop.reason === "expired" ? "warning" : "base"
1580
- });
1862
+ push("recent losses", HEADER_TONE);
1863
+ const losses = fitTable([
1864
+ { header: "when", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString("en-GB") },
1865
+ { header: "provider/model", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? ""}/${drop.modelID ?? ""}` },
1866
+ { header: "tokens", width: 7, align: "right", cell: (drop) => `\u2212${formatTokens(drop.tokens)}` },
1867
+ { header: "idle", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}` }
1868
+ ], width);
1869
+ if (losses.length > 0) {
1870
+ lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: "muted" });
1871
+ for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {
1872
+ lines.push({
1873
+ text: formatTableRow(losses.map((column) => column.cell(drop)), losses.map((column) => column.width), losses.map((column) => column.align)),
1874
+ tone: drop.reason === "expired" ? "warning" : "base"
1875
+ });
1876
+ }
1581
1877
  }
1582
1878
  }
1583
1879
  return lines;
@@ -1598,110 +1894,162 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true, tot
1598
1894
  }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
1599
1895
  const overall = usageBuckets(totals);
1600
1896
  lines.push({
1601
- text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
1897
+ text: truncate(`${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`, width),
1602
1898
  tone: "muted"
1603
1899
  });
1604
1900
  if (rows.length > 1) {
1605
- lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
1606
- lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
1901
+ const bars = Math.max(4, width - 8);
1902
+ lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: "muted" });
1903
+ lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: "muted" });
1607
1904
  lines.push({
1608
- text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
1905
+ text: truncate(`cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)), bars)}`, width),
1609
1906
  tone: "muted"
1610
1907
  });
1611
1908
  }
1612
- const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
1613
- const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
1614
- const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
1615
- const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
1616
- lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
1909
+ const columns = fitTable([
1910
+ { header: "period", width: 10, max: 24, cell: (row) => row.label },
1911
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
1912
+ { header: "sess", width: 6, align: "right", priority: 5, cell: (row) => row.sessions },
1913
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
1914
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
1915
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
1916
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
1917
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
1918
+ ], width);
1919
+ if (columns.length === 0)
1920
+ return [...lines, { text: truncate("no room for a table at this width", width), tone: "muted" }];
1921
+ const header = formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align));
1922
+ lines.push({ text: header, tone: HEADER_TONE });
1617
1923
  const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
1618
1924
  for (const row of newest) {
1619
1925
  const buckets = usageBuckets(row.usage);
1620
- const cells = [
1621
- row.label,
1622
- formatCount(row.steps),
1623
- ...withSessions ? [formatCount(row.sessions)] : [],
1624
- formatTokens(buckets.prompt),
1625
- formatTokens(buckets.cached),
1626
- formatPercent(buckets.hit, 0),
1627
- formatTokens(buckets.output),
1628
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1629
- ];
1630
- lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
1926
+ const view = {
1927
+ label: row.label,
1928
+ steps: formatCount(row.steps),
1929
+ sessions: formatCount(row.sessions),
1930
+ prompt: formatTokens(buckets.prompt),
1931
+ cached: formatTokens(buckets.cached),
1932
+ hit: formatPercent(buckets.hit, 0),
1933
+ output: formatTokens(buckets.output),
1934
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1935
+ };
1936
+ lines.push({
1937
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
1938
+ tone: "base",
1939
+ row: { kind: "period", value: row.key }
1940
+ });
1631
1941
  }
1632
1942
  lines.push({ text: "", tone: "muted" });
1943
+ const total = {
1944
+ label: "total",
1945
+ steps: formatCount(totals.steps),
1946
+ sessions: formatCount(totalSessions ?? totals.sessions),
1947
+ prompt: formatTokens(overall.prompt),
1948
+ cached: formatTokens(overall.cached),
1949
+ hit: formatPercent(overall.hit, 0),
1950
+ output: formatTokens(overall.output),
1951
+ cost: formatSpend(overall.cost, estimates ? overall.listCost : 0)
1952
+ };
1633
1953
  lines.push({
1634
- text: formatTableRow([
1635
- "total",
1636
- formatCount(totals.steps),
1637
- ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
1638
- formatTokens(overall.prompt),
1639
- formatTokens(overall.cached),
1640
- formatPercent(overall.hit, 0),
1641
- formatTokens(overall.output),
1642
- formatSpend(overall.cost, estimates ? overall.listCost : 0)
1643
- ], widths, aligns),
1954
+ text: formatTableRow(columns.map((column) => column.cell(total)), columns.map((column) => column.width), columns.map((column) => column.align)),
1644
1955
  tone: HEADER_TONE
1645
1956
  });
1646
1957
  if (rows.length === 0)
1647
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
1958
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
1648
1959
  return lines;
1649
1960
  }
1961
+ function latencyMetric(label, values, width) {
1962
+ const prefix = padCell(label, 11);
1963
+ let text = `${prefix}${values[0] ?? "\u2013"}`;
1964
+ for (let index = 1;index < values.length; index += 1) {
1965
+ const next = `${text} \xB7 ${values[index]}`;
1966
+ if (next.length > width)
1967
+ break;
1968
+ text = next;
1969
+ }
1970
+ return text;
1971
+ }
1650
1972
  function latencyLines(report, width, groups, limit = 12, estimates = true) {
1651
1973
  const lines = [];
1652
- lines.push({
1653
- 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]),
1654
- tone: "base"
1655
- });
1656
- lines.push({
1657
- 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]),
1658
- tone: "base"
1659
- });
1660
- lines.push({
1661
- 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]),
1662
- tone: "base"
1663
- });
1974
+ if (width >= 68) {
1975
+ lines.push({
1976
+ 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]),
1977
+ tone: "base"
1978
+ });
1979
+ lines.push({
1980
+ 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]),
1981
+ tone: "base"
1982
+ });
1983
+ lines.push({
1984
+ 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]),
1985
+ tone: "base"
1986
+ });
1987
+ } else {
1988
+ lines.push({
1989
+ text: latencyMetric("wall", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),
1990
+ tone: "base"
1991
+ });
1992
+ lines.push({
1993
+ text: latencyMetric("stream", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),
1994
+ tone: "base"
1995
+ });
1996
+ lines.push({
1997
+ text: latencyMetric("throughput", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
1998
+ tone: "base"
1999
+ });
2000
+ }
1664
2001
  lines.push({ text: "", tone: "muted" });
1665
2002
  lines.push({
1666
2003
  text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
1667
2004
  tone: "muted"
1668
2005
  });
1669
2006
  if (report.wall.count === 0)
1670
- lines.push({ text: "no completed steps for this range", tone: "muted" });
2007
+ lines.push({ text: truncate("no completed steps for this range", width), tone: "muted" });
1671
2008
  if (groups !== undefined && groups.length > 0) {
1672
2009
  lines.push({ text: "", tone: "muted" });
1673
2010
  lines.push({ text: "by group", tone: HEADER_TONE });
1674
- const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
1675
- const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
1676
- lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
1677
- for (const row of groups.slice(0, limit)) {
1678
- const thin = row.count < 5;
1679
- lines.push({
1680
- text: formatTableRow([
1681
- row.label,
1682
- formatCount(row.count),
1683
- formatMs(row.wall.p50),
1684
- formatMs(row.wall.p90),
1685
- formatMs(row.stream.p50),
1686
- formatTps(row.tps.p50),
1687
- formatTps(row.tps.p90),
1688
- formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
1689
- ], widths, aligns),
1690
- tone: thin ? "muted" : "base",
1691
- row: { kind: "model", value: row.key }
1692
- });
2011
+ const columns = fitTable([
2012
+ { header: "group", width: 8, max: 32, cell: (row) => row.label },
2013
+ { header: "n", width: 4, align: "right", cell: (row) => formatCount(row.count) },
2014
+ { header: "wall p50", width: 8, align: "right", cell: (row) => formatMs(row.wall.p50) },
2015
+ { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
2016
+ { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
2017
+ { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
2018
+ { header: "tps p90", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatTps(row.tps.p90) },
2019
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2020
+ ], width);
2021
+ if (columns.length > 0) {
2022
+ lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: "muted" });
2023
+ for (const row of groups.slice(0, limit)) {
2024
+ const thin = row.count < 5;
2025
+ lines.push({
2026
+ text: formatTableRow(columns.map((column) => column.cell(row)), columns.map((column) => column.width), columns.map((column) => column.align)),
2027
+ tone: thin ? "muted" : "base",
2028
+ row: { kind: "model", value: row.key }
2029
+ });
2030
+ }
1693
2031
  }
1694
- lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
2032
+ lines.push({ text: truncate("n < 5 is dimmed: too few samples to compare", width), tone: "muted" });
1695
2033
  }
1696
2034
  return lines;
1697
2035
  }
1698
2036
  function sessionsLines(rows, width, options) {
1699
2037
  const limit = options?.limit ?? 20;
1700
2038
  const estimates = options?.estimates !== false;
1701
- const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
1702
- const aligns = ["left", "right", "right", "right", "right", "right", "right"];
2039
+ const columns = fitTable([
2040
+ { header: "title", width: 10, max: 48, cell: (row) => row.title },
2041
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
2042
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
2043
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
2044
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
2045
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
2046
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
2047
+ ], width);
1703
2048
  const lines = [
1704
- { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
2049
+ {
2050
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
2051
+ tone: HEADER_TONE
2052
+ }
1705
2053
  ];
1706
2054
  const byID = new Map(rows.map((row) => [row.sessionID, row]));
1707
2055
  const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
@@ -1709,18 +2057,18 @@ function sessionsLines(rows, width, options) {
1709
2057
  const orderedAll = [...ordered, ...children];
1710
2058
  for (const row of orderedAll.slice(0, limit)) {
1711
2059
  const child = row.parentID !== undefined && byID.has(row.parentID);
1712
- const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
1713
2060
  const buckets = usageBuckets(row);
2061
+ const view = {
2062
+ title: `${child ? "\u21B3 " : ""}${row.title ?? row.sessionID}`,
2063
+ steps: formatCount(buckets.steps),
2064
+ prompt: formatTokens(buckets.prompt),
2065
+ cached: formatTokens(buckets.cached),
2066
+ hit: formatPercent(buckets.hit, 0),
2067
+ output: formatTokens(buckets.output),
2068
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2069
+ };
1714
2070
  lines.push({
1715
- text: formatTableRow([
1716
- `${child ? "\u21B3 " : ""}${title}`,
1717
- formatCount(buckets.steps),
1718
- formatTokens(buckets.prompt),
1719
- formatTokens(buckets.cached),
1720
- formatPercent(buckets.hit, 0),
1721
- formatTokens(buckets.output),
1722
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1723
- ], widths, aligns),
2071
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
1724
2072
  tone: child ? "muted" : "base",
1725
2073
  row: { kind: "session", value: row.sessionID }
1726
2074
  });
@@ -1735,14 +2083,14 @@ function sessionsLines(rows, width, options) {
1735
2083
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
1736
2084
  lines.push({ text: "", tone: "muted" });
1737
2085
  lines.push({
1738
- 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)}`,
2086
+ 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),
1739
2087
  tone: "muted"
1740
2088
  });
1741
2089
  }
1742
2090
  if (rows.length > limit)
1743
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
2091
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, width), tone: "muted" });
1744
2092
  if (rows.length === 0)
1745
- lines.push({ text: "no sessions recorded for this range", tone: "muted" });
2093
+ lines.push({ text: truncate("no sessions recorded for this range", width), tone: "muted" });
1746
2094
  return lines;
1747
2095
  }
1748
2096
  function dbLines(data, width) {
@@ -1750,16 +2098,16 @@ function dbLines(data, width) {
1750
2098
  const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
1751
2099
  lines.push({ text: truncate(data.info.path, width), tone: "base" });
1752
2100
  lines.push({
1753
- text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
2101
+ text: truncate(`${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`, width),
1754
2102
  tone: "muted"
1755
2103
  });
1756
2104
  lines.push({ text: "", tone: "muted" });
1757
2105
  lines.push({ text: "what it holds", tone: HEADER_TONE });
1758
2106
  for (const table of data.info.tables) {
1759
- lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
2107
+ lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? "muted" : "base" });
1760
2108
  }
1761
2109
  lines.push({
1762
- 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")}`,
2110
+ 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),
1763
2111
  tone: "muted"
1764
2112
  });
1765
2113
  lines.push({ text: "", tone: "muted" });
@@ -1775,7 +2123,7 @@ function dbLines(data, width) {
1775
2123
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
1776
2124
  });
1777
2125
  }
1778
- const widths = [10, 13, 10];
2126
+ const widths = [9, 11, 10];
1779
2127
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
1780
2128
  for (const option of data.info.removable) {
1781
2129
  const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
@@ -1795,7 +2143,7 @@ function dbLines(data, width) {
1795
2143
  });
1796
2144
  if (data.busy === true) {
1797
2145
  lines.push({ text: "", tone: "muted" });
1798
- lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
2146
+ lines.push({ text: truncate("the recorder is writing: try the vacuum again in a moment", width), tone: "warning" });
1799
2147
  }
1800
2148
  return lines;
1801
2149
  }
@@ -1819,28 +2167,74 @@ function turnStats(turn) {
1819
2167
  steps: turn.steps
1820
2168
  };
1821
2169
  }
2170
+ function compactTurnLine(stats, width, options) {
2171
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
2172
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
2173
+ const estimates = options?.estimates !== false;
2174
+ const headParts = [];
2175
+ if (fields.clock && stats.endAt !== undefined)
2176
+ headParts.push(formatClock(stats.endAt));
2177
+ if (stats.providerID !== undefined) {
2178
+ let identity = stats.providerID;
2179
+ if (fields.model && stats.modelID !== undefined)
2180
+ identity += `/${stats.modelID}`;
2181
+ if (fields.variant && stats.variant)
2182
+ identity += ` ${stats.variant}`;
2183
+ headParts.push(identity);
2184
+ }
2185
+ let head = headParts.join(" ");
2186
+ const totals = options?.turnTotals === "sum" ? stats.totals : stats.latest;
2187
+ const display = displayTotals(totals);
2188
+ const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined;
2189
+ const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim();
2190
+ const warning = fields.cacheExpiry && stats.cacheExpired ? `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` \xD7${stats.drops.length}` : ""})` : undefined;
2191
+ let suffix = [warning, cost].filter((part) => part !== undefined).join(" \xB7 ");
2192
+ if (suffix !== "" && suffix.length + 3 > width)
2193
+ suffix = cost ?? suffix;
2194
+ head = truncate(head, Math.max(0, width - (suffix === "" ? 0 : suffix.length + 3)));
2195
+ if (!fields.turn || stats.totals.steps === 0)
2196
+ return [head, suffix].filter((part) => part !== "").join(" \xB7 ");
2197
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
2198
+ const volumes = [
2199
+ input,
2200
+ `${labels.cached} ${formatTokens(display.cached)}`,
2201
+ `${labels.output} ${formatTokens(display.output)}`,
2202
+ ...fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []
2203
+ ];
2204
+ let numbers = "";
2205
+ for (const volume of volumes) {
2206
+ const next = numbers === "" ? volume : `${numbers}, ${volume}`;
2207
+ if ([head, next, suffix].filter((part) => part !== "").join(" \xB7 ").length > width)
2208
+ break;
2209
+ numbers = next;
2210
+ }
2211
+ return [head, numbers, suffix].filter((part) => part !== "").join(" \xB7 ");
2212
+ }
1822
2213
  function turnsLines(rows, width, options) {
1823
2214
  const lines = [];
1824
2215
  const warning = rows.filter((turn) => turn.drops.length > 0).length;
1825
2216
  lines.push({
1826
- text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
2217
+ text: truncate(`${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`, width),
1827
2218
  tone: "muted"
1828
2219
  });
1829
2220
  const showSession = options?.sessionTitles !== undefined;
1830
2221
  for (const turn of rows) {
1831
- const line = formatLine(turnStats(turn), {
2222
+ const stats = turnStats(turn);
2223
+ const line = formatLine(stats, {
1832
2224
  ...options,
1833
2225
  fields: { ...options?.fields, session: false }
1834
2226
  });
1835
2227
  const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
2228
+ const available = Math.max(0, width - title.length);
2229
+ const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`;
1836
2230
  lines.push({
1837
- text: truncate(`${title}${line}`, width),
2231
+ text: truncate(text, width),
1838
2232
  tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
1839
2233
  row: { kind: "turn", value: turn.sessionID }
1840
2234
  });
1841
2235
  }
1842
2236
  if (rows.length === 0)
1843
- lines.push({ text: "no finished turns for this range", tone: "muted" });
2237
+ lines.push({ text: truncate("no finished turns for this range", width), tone: "muted" });
1844
2238
  return lines;
1845
2239
  }
1846
2240
  function sessionSummaryLines(usage, budget = 34, estimates = true) {
@@ -1960,7 +2354,7 @@ var PanelLineSchema = {
1960
2354
  var PanelSettingsSchema = {
1961
2355
  type: "object",
1962
2356
  properties: {
1963
- view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"] },
2357
+ view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db", "go"] },
1964
2358
  range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
1965
2359
  sort: { type: "string", maxLength: 40 },
1966
2360
  sortDesc: { type: "boolean" },
@@ -2098,7 +2492,7 @@ var UsageInsights = Rpc.define({
2098
2492
  properties: {
2099
2493
  sessionID: { type: "string", maxLength: 200 },
2100
2494
  limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
2101
- width: { type: "number", minimum: 20, maximum: 120 }
2495
+ width: { type: "number", minimum: 20, maximum: MAX_HISTORY_WIDTH }
2102
2496
  },
2103
2497
  required: ["sessionID", "limit", "width"],
2104
2498
  additionalProperties: false
@@ -2241,8 +2635,8 @@ function Panel(props) {
2241
2635
  let generation = 0;
2242
2636
  let scroller;
2243
2637
  const width = () => clampPanelWidth(Math.max(60, props.input.width - 4));
2244
- const view = () => sanitizeSettings(props.settings).view;
2245
- const settings = () => sanitizeSettings(props.settings);
2638
+ const view = () => sanitizeSettings(props.settings, props.views).view;
2639
+ const settings = () => sanitizeSettings(props.settings, props.views);
2246
2640
  const api = () => usageApi(props.ctx.client, props.ctx.location);
2247
2641
  function errorMessage(cause) {
2248
2642
  if (cause instanceof Error)
@@ -2255,7 +2649,7 @@ function Panel(props) {
2255
2649
  const request = createMemo(() => {
2256
2650
  tick();
2257
2651
  props.deps.refresh?.();
2258
- if (help())
2652
+ if (help() || view() === QUOTA_VIEW)
2259
2653
  return;
2260
2654
  const current = settings();
2261
2655
  return {
@@ -2272,7 +2666,7 @@ function Panel(props) {
2272
2666
  const input = request();
2273
2667
  const current = ++generation;
2274
2668
  if (input === undefined) {
2275
- setLines(helpLines(width()));
2669
+ setLines(view() === QUOTA_VIEW ? [] : helpLines(width()));
2276
2670
  setDatabase(undefined);
2277
2671
  setError(undefined);
2278
2672
  setLoading(false);
@@ -2297,6 +2691,17 @@ function Panel(props) {
2297
2691
  });
2298
2692
  });
2299
2693
  const content = createMemo(() => {
2694
+ if (help())
2695
+ return helpLines(width());
2696
+ if (view() === QUOTA_VIEW) {
2697
+ return goQuotaLines(props.quota.state(), {
2698
+ now: Date.now(),
2699
+ width: width(),
2700
+ loading: props.quota.loading(),
2701
+ error: props.quota.error(),
2702
+ name: props.quotaName
2703
+ });
2704
+ }
2300
2705
  if (error() !== undefined && lines().length === 0) {
2301
2706
  return [{
2302
2707
  text: `usage service unavailable: ${error()}`,
@@ -2309,11 +2714,11 @@ function Panel(props) {
2309
2714
  const header = createMemo(() => {
2310
2715
  const current = settings();
2311
2716
  const filters = filterSummary(current);
2312
- const where = detail() !== undefined ? " \xB7 backspace returns" : filters === undefined ? "" : ` \xB7 ${filters}`;
2717
+ const where = detail() !== undefined ? " \xB7 backspace returns" : current.view === QUOTA_VIEW ? "" : filters === undefined ? "" : ` \xB7 ${filters}`;
2313
2718
  return [{
2314
- text: `usage insights \xB7 ${rangeLabel(current.range)}${where}`,
2719
+ text: `usage insights \xB7 ${current.view === QUOTA_VIEW ? `${props.quotaName} \xB7 live` : rangeLabel(current.range)}${where}`,
2315
2720
  tone: "accent"
2316
- }, viewBar(current.view, width()), {
2721
+ }, viewBar(current.view, width(), props.views), {
2317
2722
  text: "",
2318
2723
  tone: "muted"
2319
2724
  }];
@@ -2634,12 +3039,12 @@ function Panel(props) {
2634
3039
  commands: [command("usage-insights.cursor.up", "Move up", "up", () => move(-1)), command("usage-insights.cursor.down", "Move down", "down", () => move(1)), command("usage-insights.cursor.up.alt", "Move up", "k", () => move(-1)), command("usage-insights.cursor.down.alt", "Move down", "j", () => move(1)), command("usage-insights.page.up", "Page up", "pageup", () => move(-10)), command("usage-insights.page.down", "Page down", "pagedown", () => move(10)), command("usage-insights.first", "First row", "home", () => moveEdge(false)), command("usage-insights.last", "Last row", "end", () => moveEdge(true)), command("usage-insights.drill", "Open the selected row", "return", () => drill()), command("usage-insights.back", "Go back", "backspace", () => back()), command("usage-insights.view.next", "Next view", "]", () => {
2635
3040
  setHelp(false);
2636
3041
  props.update((draft) => {
2637
- draft.view = nextIn(PANEL_VIEWS, sanitizeSettings(draft).view, 1);
3042
+ draft.view = nextIn(props.views, sanitizeSettings(draft, props.views).view, 1);
2638
3043
  });
2639
3044
  }), command("usage-insights.view.previous", "Previous view", "[", () => {
2640
3045
  setHelp(false);
2641
3046
  props.update((draft) => {
2642
- draft.view = nextIn(PANEL_VIEWS, sanitizeSettings(draft).view, -1);
3047
+ draft.view = nextIn(props.views, sanitizeSettings(draft, props.views).view, -1);
2643
3048
  });
2644
3049
  }), command("usage-insights.range.next", "Next range", "t", () => props.update((draft) => {
2645
3050
  draft.range = nextIn(RANGE_KEYS, sanitizeSettings(draft).range, 1);
@@ -2662,10 +3067,14 @@ function Panel(props) {
2662
3067
  draft.providerID = "";
2663
3068
  });
2664
3069
  setAnchor(undefined);
2665
- }), command("usage-insights.refresh", "Refresh", "r", () => setTick((value) => value + 1)), command("usage-insights.backfill", "Backfill list-price estimates", "e", () => {
3070
+ }), command("usage-insights.refresh", "Refresh", "r", () => {
3071
+ setTick((value) => value + 1);
3072
+ if (view() === QUOTA_VIEW)
3073
+ props.quota.refresh();
3074
+ }), command("usage-insights.backfill", "Backfill list-price estimates", "e", () => {
2666
3075
  if (view() === "db")
2667
3076
  backfillEstimates();
2668
- }), command("usage-insights.vacuum", "Compact the database", "v", () => void compact()), command("usage-insights.help", "Help", "?", () => setHelp((open) => !open)), command("usage-insights.fullscreen", "Toggle full screen", "f", () => props.input.toggleFullscreen()), command("usage-insights.close", "Close usage panel", "escape", () => props.input.close()), ...PANEL_VIEWS.map((name, index) => command(`usage-insights.view.${name}`, `View ${name}`, String((index + 1) % 10), () => {
3077
+ }), command("usage-insights.vacuum", "Compact the database", "v", () => void compact()), command("usage-insights.help", "Help", "?", () => setHelp((open) => !open)), command("usage-insights.fullscreen", "Toggle full screen", "f", () => props.input.toggleFullscreen()), command("usage-insights.close", "Close usage panel", "escape", () => props.input.close()), ...props.views.map((name, index) => command(`usage-insights.view.${name}`, `View ${name}`, String((index + 1) % 10), () => {
2669
3078
  setHelp(false);
2670
3079
  props.update((draft) => {
2671
3080
  draft.view = name;
@@ -2853,6 +3262,64 @@ function costOf(table, ref, usage) {
2853
3262
  return billed / 1e6;
2854
3263
  }
2855
3264
 
3265
+ // src/quota-client.ts
3266
+ function finite2(value) {
3267
+ return typeof value === "number" && Number.isFinite(value);
3268
+ }
3269
+ function meterOf(value) {
3270
+ if (value === undefined || !finite2(value.percent) || !finite2(value.resetsAt))
3271
+ return;
3272
+ return {
3273
+ percent: Math.min(100, Math.max(0, Math.round(value.percent))),
3274
+ limited: value.limited === true,
3275
+ resetsAt: value.resetsAt
3276
+ };
3277
+ }
3278
+ function workspaceOf(value) {
3279
+ const workspace = value?.workspace;
3280
+ if (workspace === undefined || workspace === null || typeof workspace.id !== "string" || workspace.id === "")
3281
+ return;
3282
+ return {
3283
+ id: workspace.id,
3284
+ ...typeof workspace.name === "string" && workspace.name !== "" ? { name: workspace.name } : {},
3285
+ ...typeof workspace.usageURL === "string" && workspace.usageURL !== "" ? { usageURL: workspace.usageURL } : {}
3286
+ };
3287
+ }
3288
+ function normalizeQuota(data, now = Date.now()) {
3289
+ if (data === null || data === undefined)
3290
+ return { kind: "none", reason: "console" };
3291
+ const value = data;
3292
+ const go = value?.go;
3293
+ if (go === undefined || go === null)
3294
+ return { kind: "none", reason: "subscription" };
3295
+ const rolling = meterOf(go.rolling);
3296
+ const weekly = meterOf(go.weekly);
3297
+ const monthly = meterOf(go.monthly);
3298
+ if (rolling === undefined || weekly === undefined || monthly === undefined) {
3299
+ return { kind: "none", reason: "subscription" };
3300
+ }
3301
+ const workspace = workspaceOf(value);
3302
+ return {
3303
+ kind: "ok",
3304
+ quota: {
3305
+ ...workspace !== undefined ? { workspace } : {},
3306
+ rolling,
3307
+ weekly,
3308
+ monthly,
3309
+ observedAt: now
3310
+ }
3311
+ };
3312
+ }
3313
+ async function fetchGoQuota(client, location, signal) {
3314
+ const usage = client.experimental?.usage;
3315
+ if (typeof usage?.limits !== "function") {
3316
+ throw new Error("this OpenCode build does not expose Go usage limits");
3317
+ }
3318
+ const payload = await usage.limits(location?.directory !== undefined ? { location: { directory: location.directory } } : undefined, signal !== undefined ? { signal } : undefined);
3319
+ const data = payload?.data;
3320
+ return normalizeQuota(data, Date.now());
3321
+ }
3322
+
2856
3323
  // src/sidebar.tsx
2857
3324
  import { insert as _$insert2 } from "@opentui/solid";
2858
3325
  import { effect as _$effect2 } from "@opentui/solid";
@@ -2906,16 +3373,21 @@ function TurnsSidebar(props) {
2906
3373
  });
2907
3374
  });
2908
3375
  const lines = createMemo2(() => {
3376
+ const budget = props.deps.budget ?? 34;
3377
+ const quotaLines = props.quota === undefined ? [] : goSidebarLines(props.quota(), Date.now(), budget, props.quotaName);
2909
3378
  const result = data();
2910
3379
  if (result === undefined) {
2911
3380
  if (error() !== undefined)
2912
- return [{
3381
+ return [...quotaLines, {
2913
3382
  text: "usage history unavailable",
2914
3383
  tone: "muted"
2915
3384
  }];
2916
- return [];
3385
+ return quotaLines;
2917
3386
  }
2918
- return [...result.summary, {
3387
+ return [...quotaLines.length > 0 ? [...quotaLines, {
3388
+ text: "",
3389
+ tone: "muted"
3390
+ }] : [], ...result.summary, {
2919
3391
  text: "turns",
2920
3392
  tone: "accent"
2921
3393
  }, ...result.history];
@@ -2967,8 +3439,71 @@ var tui_default = Plugin.define({
2967
3439
  return;
2968
3440
  const panelEnabled = options.panel !== false;
2969
3441
  const pricing = options.pricing !== "off";
3442
+ const quotaEnabled = options.quota !== "off";
3443
+ const quotaActive = quotaEnabled && (options.sidebar !== false || panelEnabled);
3444
+ const views = quotaEnabled ? CLIENT_VIEWS : PANEL_VIEWS;
3445
+ function providerName() {
3446
+ try {
3447
+ const providers = ctx.data.location?.provider?.list(ctx.location);
3448
+ return providers?.find((provider) => provider.id === "opencode-go")?.name;
3449
+ } catch {
3450
+ return;
3451
+ }
3452
+ }
3453
+ const quotaName = quotaNameOf(options.quotaName, providerName());
2970
3454
  const PRICE_TTL_MS = 5 * 60 * 1000;
2971
3455
  let priceCache;
3456
+ function errorMessage(cause) {
3457
+ if (cause instanceof Error)
3458
+ return cause.message;
3459
+ if (cause !== null && typeof cause === "object" && "message" in cause) {
3460
+ return String(cause.message);
3461
+ }
3462
+ return "the usage limits request failed";
3463
+ }
3464
+ const [quotaState, setQuotaState] = createSignal3(undefined);
3465
+ const [quotaLoading, setQuotaLoading] = createSignal3(quotaActive);
3466
+ const [quotaError, setQuotaError] = createSignal3(undefined);
3467
+ const [quotaTick, setQuotaTick] = createSignal3(0);
3468
+ let quotaGeneration = 0;
3469
+ const refreshQuota = () => {
3470
+ if (quotaActive)
3471
+ setQuotaTick((value) => value + 1);
3472
+ };
3473
+ createEffect3(() => {
3474
+ if (!quotaActive)
3475
+ return;
3476
+ quotaTick();
3477
+ const generation = ++quotaGeneration;
3478
+ const controller = new AbortController;
3479
+ onCleanup2(() => controller.abort());
3480
+ setQuotaLoading(true);
3481
+ fetchGoQuota(ctx.client, ctx.location, controller.signal).then((result) => {
3482
+ if (generation !== quotaGeneration)
3483
+ return;
3484
+ setQuotaState(result);
3485
+ setQuotaError(undefined);
3486
+ }).catch((cause) => {
3487
+ if (generation !== quotaGeneration)
3488
+ return;
3489
+ setQuotaError(errorMessage(cause));
3490
+ }).finally(() => {
3491
+ if (generation === quotaGeneration)
3492
+ setQuotaLoading(false);
3493
+ });
3494
+ });
3495
+ createEffect3(() => {
3496
+ if (!quotaActive)
3497
+ return;
3498
+ const timer = setInterval(() => setQuotaTick((value) => value + 1), QUOTA_POLL_MS);
3499
+ onCleanup2(() => clearInterval(timer));
3500
+ });
3501
+ const quotaResource = {
3502
+ state: quotaState,
3503
+ loading: quotaLoading,
3504
+ error: quotaError,
3505
+ refresh: refreshQuota
3506
+ };
2972
3507
  function priceTableFor() {
2973
3508
  if (!pricing)
2974
3509
  return;
@@ -3136,7 +3671,10 @@ var tui_default = Plugin.define({
3136
3671
  update: patchSettings,
3137
3672
  get maintenance() {
3138
3673
  return options.maintenance !== false;
3139
- }
3674
+ },
3675
+ views,
3676
+ quota: quotaResource,
3677
+ quotaName
3140
3678
  }) : null
3141
3679
  }) : () => {};
3142
3680
  const disposeSidebar = ctx.ui.slot({
@@ -3151,11 +3689,13 @@ var tui_default = Plugin.define({
3151
3689
  refresh,
3152
3690
  limit: clampTurnsLimit(options.sidebarTurns ?? 8)
3153
3691
  };
3154
- }
3692
+ },
3693
+ quota: quotaEnabled ? quotaState : undefined,
3694
+ quotaName
3155
3695
  })
3156
3696
  });
3157
3697
  function open(input) {
3158
- const parsed = parseArgs(input);
3698
+ const parsed = parseArgs(input, views);
3159
3699
  if (parsed.view !== undefined || parsed.range !== undefined) {
3160
3700
  patchSettings((draft) => {
3161
3701
  if (parsed.view !== undefined)
@@ -3183,14 +3723,14 @@ var tui_default = Plugin.define({
3183
3723
  bind: false,
3184
3724
  palette: true,
3185
3725
  slash: {
3186
- name: "usage",
3726
+ name: "usage-insights",
3187
3727
  aliases: ["insights"],
3188
3728
  arguments: true
3189
3729
  },
3190
3730
  run: (input) => {
3191
3731
  if (!open(input)) {
3192
3732
  ctx.ui.toast.show({
3193
- message: "Open a session first, then run /usage",
3733
+ message: "Open a session first, then run /usage-insights",
3194
3734
  variant: "warning"
3195
3735
  });
3196
3736
  }
@@ -3229,7 +3769,7 @@ var tui_default = Plugin.define({
3229
3769
  };
3230
3770
  __test.open = open;
3231
3771
  __test.state = () => {
3232
- const current = sanitizeSettings(settings);
3772
+ const current = sanitizeSettings(settings, views);
3233
3773
  return {
3234
3774
  view: current.view,
3235
3775
  range: current.range
@@ -3251,4 +3791,4 @@ export {
3251
3791
  tui_default as default
3252
3792
  };
3253
3793
 
3254
- //# debugId=3E4F6620631DC12564756E2164756E21
3794
+ //# debugId=42E094B28C9AC36E64756E2164756E21