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.
@@ -429,6 +429,7 @@ import { basename } from "path";
429
429
 
430
430
  // src/limits.ts
431
431
  var MAX_PANEL_WIDTH = 200;
432
+ var MAX_HISTORY_WIDTH = 120;
432
433
  var MAX_TURNS = 50;
433
434
  function clampPanelWidth(value) {
434
435
  if (!Number.isFinite(value))
@@ -1512,7 +1513,10 @@ var GAP_BUCKETS = [
1512
1513
  ["<1m", 0, 60000],
1513
1514
  ["1\u20135m", 60000, 5 * 60000],
1514
1515
  ["5\u201315m", 5 * 60000, 15 * 60000],
1515
- ["15\u201360m", 15 * 60000, 60 * 60000],
1516
+ ["15\u201320m", 15 * 60000, 20 * 60000],
1517
+ ["20\u201330m", 20 * 60000, 30 * 60000],
1518
+ ["30\u201345m", 30 * 60000, 45 * 60000],
1519
+ ["45\u201360m", 45 * 60000, 60 * 60000],
1516
1520
  ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
1517
1521
  [">6h", 6 * 60 * 60000, undefined]
1518
1522
  ];
@@ -1763,9 +1767,128 @@ function periodsOf(rows, granularity, otherRows = []) {
1763
1767
  return [...byKey.values()].sort((left, right) => left.at - right.at);
1764
1768
  }
1765
1769
 
1770
+ // src/quota.ts
1771
+ var QUOTA_VIEW = "go";
1772
+ var QUOTA_POLL_MS = 60000;
1773
+ var DEFAULT_QUOTA_NAME = "OpenCode Go";
1774
+ var DAY_MS = 24 * 60 * 60 * 1000;
1775
+ var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
1776
+ function quotaNameOf(explicit, providerName) {
1777
+ const custom = explicit?.trim();
1778
+ if (custom !== undefined && custom !== "")
1779
+ return custom;
1780
+ const provider = providerName?.trim();
1781
+ if (provider !== undefined && provider !== "")
1782
+ return provider;
1783
+ return DEFAULT_QUOTA_NAME;
1784
+ }
1785
+ function finite2(value) {
1786
+ return typeof value === "number" && Number.isFinite(value);
1787
+ }
1788
+ function clamp(value, minimum, maximum) {
1789
+ return Math.min(maximum, Math.max(minimum, value));
1790
+ }
1791
+ function previousCycleStart(endAt) {
1792
+ if (!finite2(endAt))
1793
+ return endAt;
1794
+ const end = new Date(endAt);
1795
+ const year = end.getUTCFullYear();
1796
+ const month = end.getUTCMonth();
1797
+ const day = end.getUTCDate();
1798
+ const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
1799
+ const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
1800
+ start.setUTCDate(Math.min(day, lastDay));
1801
+ return start.getTime();
1802
+ }
1803
+ function forecastMonthly(meter, now) {
1804
+ const endAt = finite2(meter.resetsAt) ? meter.resetsAt : now;
1805
+ const startAt = previousCycleStart(endAt);
1806
+ const total = Math.max(1, endAt - startAt);
1807
+ const elapsedMs = clamp(now - startAt, 0, total);
1808
+ const remainingMs = Math.max(0, endAt - now);
1809
+ const percent = clamp(finite2(meter.percent) ? meter.percent : 0, 0, 100);
1810
+ const reached = meter.limited === true || percent >= 100;
1811
+ const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
1812
+ const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
1813
+ const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
1814
+ const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
1815
+ const willExhaust = exhaustAt !== undefined;
1816
+ const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
1817
+ return {
1818
+ startAt,
1819
+ endAt,
1820
+ elapsedMs,
1821
+ remainingMs,
1822
+ ratePerDay,
1823
+ projectedPercent,
1824
+ ...exhaustAt !== undefined ? { exhaustAt } : {},
1825
+ reached,
1826
+ available,
1827
+ willExhaust
1828
+ };
1829
+ }
1830
+ function quotaBar(percent, width = 10) {
1831
+ const value = clamp(finite2(percent) ? percent : 0, 0, 100);
1832
+ const cells = Math.max(1, Math.round(width));
1833
+ const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
1834
+ return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
1835
+ }
1836
+ function formatRenewal(at, timeZone) {
1837
+ if (!finite2(at))
1838
+ return "\u2013";
1839
+ try {
1840
+ return new Intl.DateTimeFormat("en-GB", {
1841
+ day: "2-digit",
1842
+ month: "short",
1843
+ year: "numeric",
1844
+ hour: "2-digit",
1845
+ minute: "2-digit",
1846
+ hour12: false,
1847
+ ...timeZone !== undefined ? { timeZone } : {}
1848
+ }).format(new Date(at)).replace(/,/g, "");
1849
+ } catch {
1850
+ return "\u2013";
1851
+ }
1852
+ }
1853
+ function formatRenewalCompact(at, timeZone) {
1854
+ if (!finite2(at))
1855
+ return "\u2013";
1856
+ try {
1857
+ return new Intl.DateTimeFormat("en-GB", {
1858
+ day: "2-digit",
1859
+ month: "short",
1860
+ hour: "2-digit",
1861
+ minute: "2-digit",
1862
+ hour12: false,
1863
+ ...timeZone !== undefined ? { timeZone } : {}
1864
+ }).format(new Date(at)).replace(/,/g, "");
1865
+ } catch {
1866
+ return "\u2013";
1867
+ }
1868
+ }
1869
+ function formatCountdown(at, now) {
1870
+ const remaining = at - now;
1871
+ if (!finite2(remaining))
1872
+ return "\u2013";
1873
+ if (remaining <= 0)
1874
+ return "due";
1875
+ return formatDuration(remaining);
1876
+ }
1877
+ function quotaStatus(quota) {
1878
+ const limited = [];
1879
+ if (quota.rolling.limited || quota.rolling.percent >= 100)
1880
+ limited.push("5-hour");
1881
+ if (quota.weekly.limited || quota.weekly.percent >= 100)
1882
+ limited.push("weekly");
1883
+ if (quota.monthly.limited || quota.monthly.percent >= 100)
1884
+ limited.push("monthly");
1885
+ return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
1886
+ }
1887
+
1766
1888
  // src/panel-data.ts
1767
1889
  var PANEL_NAME = "usage-insights";
1768
1890
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
1891
+ var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
1769
1892
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
1770
1893
  var GRANULARITIES = ["day", "week", "month"];
1771
1894
  var SORT_KEYS = {
@@ -1790,13 +1913,13 @@ function nextSort(view, current, step) {
1790
1913
  return keys[0];
1791
1914
  return keys[(index + step + keys.length) % keys.length];
1792
1915
  }
1793
- function parseArgs(input) {
1916
+ function parseArgs(input, views = CLIENT_VIEWS) {
1794
1917
  const parsed = {};
1795
1918
  for (const token of (input ?? "").split(/\s+/)) {
1796
1919
  const value = token.trim().toLowerCase();
1797
1920
  if (value === "")
1798
1921
  continue;
1799
- if (PANEL_VIEWS.includes(value))
1922
+ if (views.includes(value))
1800
1923
  parsed.view = value;
1801
1924
  else if (RANGE_KEYS.includes(value))
1802
1925
  parsed.range = value;
@@ -1833,10 +1956,10 @@ var DEFAULT_SETTINGS = {
1833
1956
  modelID: "",
1834
1957
  providerID: ""
1835
1958
  };
1836
- function sanitizeSettings(raw) {
1959
+ function sanitizeSettings(raw, views = CLIENT_VIEWS) {
1837
1960
  const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
1838
1961
  return {
1839
- view: PANEL_VIEWS.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1962
+ view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1840
1963
  range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
1841
1964
  sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
1842
1965
  sortDesc: settings.sortDesc === true,
@@ -1904,15 +2027,6 @@ function truncateMiddle(value, width) {
1904
2027
  const tail = width - 1 - head;
1905
2028
  return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
1906
2029
  }
1907
- function tableWidths(width, layouts) {
1908
- for (const layout of layouts) {
1909
- const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
1910
- if (total <= width)
1911
- return [...layout];
1912
- }
1913
- const last = layouts[layouts.length - 1];
1914
- return last === undefined ? [] : [...last];
1915
- }
1916
2030
  function modelCell(modelID, variant, width) {
1917
2031
  return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
1918
2032
  }
@@ -1931,6 +2045,47 @@ function formatTableRow(cells, widths, aligns) {
1931
2045
  }
1932
2046
  return parts.join(" ");
1933
2047
  }
2048
+ function fitTableColumns(columns, width) {
2049
+ const chosen = new Set;
2050
+ for (let index = 0;index < columns.length; index += 1) {
2051
+ if (columns[index].priority === undefined)
2052
+ chosen.add(index);
2053
+ }
2054
+ if (chosen.size === 0)
2055
+ return [];
2056
+ const total = () => {
2057
+ let sum = chosen.size - 1;
2058
+ for (const index of chosen)
2059
+ sum += columns[index].width;
2060
+ return sum;
2061
+ };
2062
+ 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);
2063
+ for (const { column, index } of optional) {
2064
+ if (total() + column.width + 1 + (column.reserve ?? 0) <= width)
2065
+ chosen.add(index);
2066
+ }
2067
+ while (chosen.size > 1 && total() > width)
2068
+ chosen.delete(Math.max(...chosen));
2069
+ const widths = new Map;
2070
+ let room = width - total();
2071
+ for (let index = 0;index < columns.length && room > 0; index += 1) {
2072
+ if (!chosen.has(index))
2073
+ continue;
2074
+ const column = columns[index];
2075
+ const grow = Math.min(room, (column.max ?? column.width) - column.width);
2076
+ if (grow <= 0)
2077
+ continue;
2078
+ widths.set(index, column.width + grow);
2079
+ room -= grow;
2080
+ }
2081
+ return [...chosen].sort((left, right) => left - right).map((index) => ({ index, width: widths.get(index) ?? columns[index].width }));
2082
+ }
2083
+ function fitTable(columns, width) {
2084
+ return fitTableColumns(columns, width).map(({ index, width: fitted }) => {
2085
+ const column = columns[index];
2086
+ return { index, header: column.header, width: fitted, align: column.align ?? "left", cell: column.cell };
2087
+ });
2088
+ }
1934
2089
  function count(n, singular, plural = `${singular}s`) {
1935
2090
  return `${formatCount(n)} ${n === 1 ? singular : plural}`;
1936
2091
  }
@@ -1938,21 +2093,30 @@ function kvGrid(pairs, width) {
1938
2093
  const lines = [];
1939
2094
  const label = 11;
1940
2095
  const column = Math.floor(width / 2);
2096
+ const pairLines = (pair) => {
2097
+ const text = `${padCell(pair[0], label)}${pair[1]}`;
2098
+ if (text.length <= width)
2099
+ return [text];
2100
+ return [padCell(pair[0], label), ` ${pair[1]}`].map((line) => truncate(line, width));
2101
+ };
1941
2102
  for (let index = 0;index < pairs.length; index += 2) {
1942
2103
  const left = pairs[index];
1943
2104
  const right = pairs[index + 1];
1944
- const leftText = `${padCell(left[0], label)}${left[1]}`;
1945
2105
  if (right === undefined) {
1946
- lines.push({ text: leftText, tone: "base" });
2106
+ for (const text of pairLines(left))
2107
+ lines.push({ text, tone: "base" });
1947
2108
  continue;
1948
2109
  }
2110
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
1949
2111
  const rightText = `${padCell(right[0], label)}${right[1]}`;
1950
2112
  const gap = Math.max(2, column - leftText.length);
1951
2113
  if (leftText.length + gap + rightText.length <= width) {
1952
2114
  lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
1953
2115
  } else {
1954
- lines.push({ text: leftText, tone: "base" });
1955
- lines.push({ text: rightText, tone: "base" });
2116
+ for (const text of pairLines(left))
2117
+ lines.push({ text, tone: "base" });
2118
+ for (const text of pairLines(right))
2119
+ lines.push({ text, tone: "base" });
1956
2120
  }
1957
2121
  }
1958
2122
  return lines;
@@ -1993,25 +2157,28 @@ function usageBuckets(usage) {
1993
2157
  hit: prompt > 0 ? usage.cached / prompt : undefined
1994
2158
  };
1995
2159
  }
1996
- function viewBar(view, width = 200) {
2160
+ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
1997
2161
  const key = (index) => String((index + 1) % 10);
1998
- const full = PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
1999
- const candidates = [full, PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2162
+ const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2163
+ const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2000
2164
  for (const parts of candidates) {
2001
2165
  const text = parts.join(" ");
2002
2166
  if (text.length <= width)
2003
2167
  return { text, tone: "muted" };
2004
2168
  }
2005
- return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
2169
+ const index = views.indexOf(view);
2170
+ return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
2006
2171
  }
2007
2172
  function keysFor(of) {
2173
+ if (of === QUOTA_VIEW)
2174
+ return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
2008
2175
  if (of === "db")
2009
- 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";
2176
+ 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";
2010
2177
  if (of === "periods")
2011
- 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";
2178
+ 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";
2012
2179
  if (of === "turns")
2013
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2014
- 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";
2180
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
2181
+ 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";
2015
2182
  }
2016
2183
  function filterSummary(filters) {
2017
2184
  const parts = [];
@@ -2028,7 +2195,7 @@ function helpLines(width) {
2028
2195
  const lines = [
2029
2196
  { text: "keys", tone: HEADER_TONE },
2030
2197
  { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
2031
- { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
2198
+ { text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
2032
2199
  { text: " t shift+t previous / next range" },
2033
2200
  { text: " s shift+s cycle sort column \xB7 reverse" },
2034
2201
  { text: " b periods bucket: day \u2192 week \u2192 month" },
@@ -2037,6 +2204,13 @@ function helpLines(width) {
2037
2204
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
2038
2205
  { text: " e db: backfill list-price estimates for the $0 steps" },
2039
2206
  { text: "" },
2207
+ { text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
2208
+ { text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
2209
+ { text: " forecast the monthly percentage at its reset, from the" },
2210
+ { text: " cycle's average pace (not a sample history)" },
2211
+ { text: " renews the monthly reset reported by the host" },
2212
+ { text: " the plugin reads the host's local usage-limits endpoint;" },
2213
+ { text: " it never reads your API key and never talks to the Console." },
2040
2214
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
2041
2215
  { text: " prompt everything the provider saw: cached + fresh + writes" },
2042
2216
  { text: " in the uncached part: fresh input + cache writes" },
@@ -2071,6 +2245,101 @@ function helpLines(width) {
2071
2245
  ];
2072
2246
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2073
2247
  }
2248
+ function quotaMeterLine(label, meter, now) {
2249
+ const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
2250
+ const countdown = formatCountdown(meter.resetsAt, now);
2251
+ return {
2252
+ text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
2253
+ tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
2254
+ };
2255
+ }
2256
+ function goQuotaLines(state, options) {
2257
+ const { now, width, loading, error } = options;
2258
+ const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
2259
+ const lines = [];
2260
+ const push = (text, tone = "base") => {
2261
+ lines.push({ text, tone });
2262
+ };
2263
+ if (state === undefined) {
2264
+ if (error !== undefined && error !== "")
2265
+ push(`Go quota unavailable: ${error}`, "warning");
2266
+ else if (loading === true)
2267
+ push("reading OpenCode Go quota\u2026", "muted");
2268
+ else
2269
+ push("OpenCode Go quota is unavailable", "muted");
2270
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2271
+ }
2272
+ if (state.kind === "none") {
2273
+ push(name, "accent");
2274
+ push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
2275
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2276
+ }
2277
+ const quota = state.quota;
2278
+ const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
2279
+ const status = quotaStatus(quota);
2280
+ const forecast = forecastMonthly(quota.monthly, now);
2281
+ push(`${name} \xB7 ${workspace}`, "accent");
2282
+ push(`status ${status}`, status === "active" ? "base" : "warning");
2283
+ lines.push(quotaMeterLine("rolling", quota.rolling, now));
2284
+ lines.push(quotaMeterLine("weekly", quota.weekly, now));
2285
+ lines.push(quotaMeterLine("monthly", quota.monthly, now));
2286
+ push("");
2287
+ if (forecast.reached || quota.monthly.limited) {
2288
+ push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
2289
+ } else if (now >= forecast.endAt) {
2290
+ push("forecast monthly reset due \xB7 refresh", "warning");
2291
+ } else if (!forecast.available) {
2292
+ push("forecast too early in the cycle to project a monthly pace", "muted");
2293
+ } else if (quota.monthly.percent === 0) {
2294
+ push("forecast no monthly usage yet this cycle", "muted");
2295
+ } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
2296
+ push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
2297
+ } else {
2298
+ const projected = Math.min(999, Math.round(forecast.projectedPercent));
2299
+ const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
2300
+ push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
2301
+ }
2302
+ const renewal = formatRenewal(quota.monthly.resetsAt);
2303
+ const countdown = formatCountdown(quota.monthly.resetsAt, now);
2304
+ push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
2305
+ if (quota.workspace?.usageURL !== undefined)
2306
+ push(`console ${quota.workspace.usageURL}`, "muted");
2307
+ const age = Math.max(0, now - quota.observedAt);
2308
+ push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
2309
+ if (loading === true)
2310
+ push("refreshing\u2026", "muted");
2311
+ if (error !== undefined && error !== "")
2312
+ push(`quota refresh failed: ${error}`, "warning");
2313
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2314
+ }
2315
+ function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
2316
+ if (state?.kind !== "ok" || width <= 0)
2317
+ return [];
2318
+ const quota = state.quota;
2319
+ const status = quotaStatus(quota);
2320
+ const forecast = forecastMonthly(quota.monthly, now);
2321
+ const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
2322
+ const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
2323
+ let forecastText = "forecast too early";
2324
+ let forecastTone = "muted";
2325
+ if (forecast.reached || quota.monthly.limited) {
2326
+ forecastText = "monthly limit reached";
2327
+ forecastTone = "warning";
2328
+ } else if (forecast.willExhaust) {
2329
+ forecastText = "limit before renewal";
2330
+ forecastTone = "warning";
2331
+ } else if (forecast.available && quota.monthly.percent > 0) {
2332
+ forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
2333
+ } else if (forecast.available && quota.monthly.percent === 0) {
2334
+ forecastText = "forecast no usage yet";
2335
+ }
2336
+ return [
2337
+ { text: truncate(name, width), tone: "accent" },
2338
+ { text: truncate(base, width), tone: baseTone },
2339
+ { text: truncate(forecastText, width), tone: forecastTone },
2340
+ { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
2341
+ ];
2342
+ }
2074
2343
  function usagePairs(usage, estimates = true) {
2075
2344
  if (usage === undefined)
2076
2345
  return [];
@@ -2098,14 +2367,16 @@ function overviewLines(data, width) {
2098
2367
  const lines = [];
2099
2368
  const estimates = data.estimates !== false;
2100
2369
  lines.push({
2101
- text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
2370
+ text: truncate(`${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`, width),
2102
2371
  tone: "muted"
2103
2372
  });
2104
2373
  lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
2105
2374
  if (data.activity !== undefined && data.activity.length > 1) {
2106
- const series = reduceSeries(data.activity);
2375
+ const suffix = ` ${count(data.activity.length, "bucket")}`;
2376
+ const bars = Math.max(4, width - "activity ".length - suffix.length);
2377
+ const series = reduceSeries(data.activity, bars);
2107
2378
  lines.push({ text: "", tone: "muted" });
2108
- lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
2379
+ lines.push({ text: truncate(`activity ${sparkline(series)}${suffix}`, width), tone: "muted" });
2109
2380
  }
2110
2381
  if (data.session !== undefined) {
2111
2382
  lines.push({ text: "", tone: "muted" });
@@ -2116,7 +2387,7 @@ function overviewLines(data, width) {
2116
2387
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
2117
2388
  const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
2118
2389
  lines.push({
2119
- text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
2390
+ text: truncate(` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`, width),
2120
2391
  tone: "muted"
2121
2392
  });
2122
2393
  }
@@ -2148,65 +2419,33 @@ function coveragePairs(coverage) {
2148
2419
  ]
2149
2420
  ];
2150
2421
  }
2151
- function modelColumns(width) {
2152
- const layouts = [
2153
- { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
2154
- { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
2155
- { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
2156
- { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
2157
- { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
2158
- ];
2159
- for (const layout of layouts) {
2160
- const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
2161
- if (total <= width)
2162
- return layout;
2163
- }
2164
- return layouts[layouts.length - 1];
2165
- }
2166
2422
  function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2167
- const columns = modelColumns(width);
2168
- const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
2169
- const aligns = ["left", "right", "right", "right"];
2170
- const header = ["model", "steps", "prompt", "cached"];
2171
- if (columns.hit > 0) {
2172
- widths.push(columns.hit);
2173
- aligns.push("right");
2174
- header.push("hit");
2175
- }
2176
- widths.push(columns.out);
2177
- aligns.push("right");
2178
- header.push("out");
2179
- if (columns.cost > 0) {
2180
- widths.push(columns.cost);
2181
- aligns.push("right");
2182
- header.push("cost");
2183
- }
2184
- if (columns.spread > 0) {
2185
- widths.push(columns.spread);
2186
- aligns.push("left");
2187
- header.push("providers");
2188
- }
2189
- const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
2423
+ let modelWidth = 14;
2424
+ const columns = fitTable([
2425
+ { header: "model", width: 14, max: 36, cell: (row) => modelCell(row.modelID, row.variant, modelWidth) },
2426
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
2427
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => row.prompt },
2428
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => row.cached },
2429
+ { header: "hit", width: 6, max: 7, priority: 2, reserve: 10, align: "right", cell: (row) => row.hit },
2430
+ { header: "out", width: 7, max: 9, priority: 3, reserve: 10, align: "right", cell: (row) => row.output },
2431
+ { header: "cost", width: 8, max: 9, priority: 1, align: "right", cell: (row) => row.cost },
2432
+ { header: "providers", width: 18, max: 24, priority: 4, reserve: 22, cell: (row) => row.providers }
2433
+ ], width);
2434
+ modelWidth = columns.find((column) => column.index === 0)?.width ?? 0;
2435
+ if (columns.length === 0)
2436
+ return [{ text: truncate("no room for a table at this width", width), tone: "muted" }];
2437
+ const lines = [
2438
+ {
2439
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
2440
+ tone: HEADER_TONE
2441
+ }
2442
+ ];
2190
2443
  for (const model of rows.slice(0, limit)) {
2191
2444
  const key = modelKey(model.modelID, model.variant);
2192
- const name = modelCell(model.modelID, model.variant, columns.model);
2193
2445
  const buckets = usageBuckets(model.totals);
2194
2446
  const providers = unique(model.providers.map((provider) => provider.providerID));
2195
2447
  const cache = extras?.cache?.get(key);
2196
2448
  const switches = extras?.switches?.get(key);
2197
- const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
2198
- if (columns.hit > 0)
2199
- cells.push(formatPercent(cache?.hit ?? buckets.hit));
2200
- cells.push(formatTokens(buckets.output));
2201
- if (columns.cost > 0)
2202
- cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
2203
- if (columns.spread > 0)
2204
- cells.push(providers.join(", "));
2205
- lines.push({
2206
- text: formatTableRow(cells, widths, aligns),
2207
- tone: "base",
2208
- row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
2209
- });
2210
2449
  const details = [];
2211
2450
  if (cache !== undefined)
2212
2451
  details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
@@ -2216,62 +2455,76 @@ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2216
2455
  if (switches.cacheLost > 0)
2217
2456
  details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
2218
2457
  }
2219
- if (details.length > 0) {
2220
- lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
2458
+ const view = {
2459
+ modelID: model.modelID,
2460
+ variant: model.variant,
2461
+ steps: formatCount(buckets.steps),
2462
+ prompt: formatTokens(buckets.prompt),
2463
+ cached: formatTokens(buckets.cached),
2464
+ hit: formatPercent(cache?.hit ?? buckets.hit),
2465
+ output: formatTokens(buckets.output),
2466
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0),
2467
+ providers: providers.join(", "),
2468
+ detail: details.join(" \xB7 ")
2469
+ };
2470
+ lines.push({
2471
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
2472
+ tone: "base",
2473
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
2474
+ });
2475
+ if (view.detail !== "") {
2476
+ lines.push({ text: truncate(`${" ".repeat(modelWidth + 1)}${view.detail}`, width), tone: "muted" });
2221
2477
  }
2222
2478
  }
2223
2479
  if (rows.length > limit)
2224
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
2480
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, width), tone: "muted" });
2225
2481
  if (rows.length === 0)
2226
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
2482
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
2227
2483
  return lines;
2228
2484
  }
2229
2485
  function unique(values) {
2230
2486
  return [...new Set(values)];
2231
2487
  }
2232
- var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
2233
- function fitColumns(columns, width) {
2234
- const chosen = [...columns];
2235
- while (chosen.length > 1 && tableWidth(chosen) > width) {
2236
- const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
2237
- if (optional === -1)
2238
- break;
2239
- chosen.splice(chosen.length - 1 - optional, 1);
2240
- }
2241
- return chosen;
2242
- }
2243
2488
  function renderTable(rows, columns, width, options) {
2244
- const chosen = fitColumns(columns, width);
2489
+ const chosen = fitTableColumns(columns, width).map(({ index, width: fitted }) => {
2490
+ const column = columns[index];
2491
+ const align = column.align ?? "left";
2492
+ return { ...column, width: fitted, align };
2493
+ });
2494
+ if (chosen.length === 0)
2495
+ return [{ text: truncate(options.empty, width), tone: "muted" }];
2245
2496
  const widths = chosen.map((column) => column.width);
2246
- const aligns = chosen.map((column) => column.align ?? "left");
2247
- const alignsTyped = aligns;
2248
- const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
2497
+ const aligns = chosen.map((column) => column.align);
2498
+ const lines = [
2499
+ { text: formatTableRow(chosen.map((column) => column.header), widths, aligns), tone: HEADER_TONE }
2500
+ ];
2249
2501
  if (rows.length === 0)
2250
- lines.push({ text: options.empty, tone: "muted" });
2502
+ lines.push({ text: truncate(options.empty, width), tone: "muted" });
2251
2503
  for (const row of rows.slice(0, options.limit)) {
2252
2504
  const identity = options.row?.(row);
2253
2505
  lines.push({
2254
- text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
2506
+ text: formatTableRow(chosen.map((column) => column.cell(row, column.width)), widths, aligns),
2255
2507
  tone: options.tone?.(row) ?? "base",
2256
2508
  ...identity === undefined ? {} : { row: identity }
2257
2509
  });
2258
2510
  }
2259
- if (rows.length > options.limit)
2260
- lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
2511
+ if (rows.length > options.limit) {
2512
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - options.limit, "more row")}`, width), tone: "muted" });
2513
+ }
2261
2514
  return lines;
2262
2515
  }
2263
2516
  function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2264
2517
  const lines = renderTable(rows, [
2265
- { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
2266
- { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
2518
+ { header: "provider", width: 14, max: 32, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
2519
+ { header: "models", width: 6, align: "right", priority: 4, cell: (row) => formatCount(row.models.length) },
2267
2520
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2268
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2269
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2270
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2271
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2272
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2273
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2274
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2521
+ { header: "share", width: 6, align: "right", priority: 3, cell: (row) => formatPercent(row.share, 0) },
2522
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2523
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2524
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
2525
+ { header: "tps p50", width: 8, align: "right", priority: 5, cell: (row) => formatTps(row.tps) },
2526
+ { header: "wall", width: 7, align: "right", priority: 6, cell: (row) => formatMs(row.wall) },
2527
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2275
2528
  ], width, {
2276
2529
  limit,
2277
2530
  empty: "no usage recorded for this range",
@@ -2282,16 +2535,16 @@ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2282
2535
  }
2283
2536
  function providerLines(rows, width, limit = 40, estimates = true) {
2284
2537
  return renderTable(rows, [
2285
- { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
2286
- { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
2538
+ { header: "model", width: 24, max: 30, cell: (row, column) => modelCell(row.modelID, row.variant, column) },
2539
+ { header: "provider", width: 12, max: 24, cell: (row, column) => truncate(row.provider ?? "\u2013 (unknown)", column) },
2287
2540
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2288
- { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2289
- { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2290
- { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2291
- { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2292
- { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2293
- { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2294
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2541
+ { header: "share", width: 6, align: "right", priority: 5, cell: (row) => formatPercent(row.share, 0) },
2542
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 2, cell: (row) => formatTokens(row.cache.prompt) },
2543
+ { header: "cached", width: 7, max: 10, align: "right", priority: 3, cell: (row) => formatTokens(row.cache.cached) },
2544
+ { header: "hit", width: 6, max: 7, align: "right", priority: 4, cell: (row) => formatPercent(row.cache.hit) },
2545
+ { header: "tps p50", width: 8, align: "right", priority: 6, cell: (row) => formatTps(row.tps) },
2546
+ { header: "wall", width: 7, align: "right", priority: 7, cell: (row) => formatMs(row.wall) },
2547
+ { header: "cost", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2295
2548
  ], width, {
2296
2549
  limit,
2297
2550
  empty: "no usage recorded for this range",
@@ -2301,80 +2554,126 @@ function providerLines(rows, width, limit = 40, estimates = true) {
2301
2554
  }
2302
2555
  function cacheLines(data, width) {
2303
2556
  const lines = [];
2557
+ const push = (text, tone = "base") => {
2558
+ lines.push({ text: truncate(text, width), tone });
2559
+ };
2304
2560
  const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
2305
- lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
2561
+ push(`reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, total > 0 ? "warning" : "base");
2306
2562
  for (const reason of ["expired", "compaction", "unknown"]) {
2307
2563
  const group = data.drops.filter((drop) => drop.reason === reason);
2308
2564
  if (group.length === 0)
2309
2565
  continue;
2310
2566
  const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
2311
- lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
2567
+ push(` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, reason === "expired" ? "warning" : "muted");
2312
2568
  }
2313
2569
  if (data.drops.length === 0)
2314
- lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
2570
+ push(" none: prompt cache held through every gap", "muted");
2315
2571
  if (data.models !== undefined && data.models.length > 0) {
2316
2572
  lines.push({ text: "", tone: "muted" });
2317
- lines.push({ text: "reuse by model", tone: HEADER_TONE });
2318
- const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
2319
- lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
2320
- for (const row of data.models.slice(0, 10)) {
2321
- const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
2322
- lines.push({
2323
- 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"]),
2324
- tone: "base",
2325
- row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
2326
- });
2573
+ push("reuse by model", HEADER_TONE);
2574
+ let modelWidth = 12;
2575
+ const reuse = fitTable([
2576
+ { header: "model", width: 12, max: 30, cell: (row) => modelCell(row.usage.modelID, row.usage.variant, modelWidth) },
2577
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.cache.steps) },
2578
+ { header: "prompt", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2579
+ { header: "cached", width: 7, max: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2580
+ { header: "write", width: 6, max: 8, align: "right", priority: 1, cell: (row) => formatTokens(row.cache.cacheWrite) },
2581
+ { header: "hit", width: 6, max: 7, align: "right", priority: 2, cell: (row) => formatPercent(row.cache.hit) },
2582
+ { header: "hit p50", width: 7, max: 9, align: "right", priority: 3, cell: (row) => formatPercent(row.cache.hitP50) }
2583
+ ], width);
2584
+ modelWidth = reuse.find((column) => column.index === 0)?.width ?? 0;
2585
+ if (reuse.length > 0) {
2586
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
2587
+ for (const row of data.models.slice(0, 10)) {
2588
+ lines.push({
2589
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
2590
+ tone: "base",
2591
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
2592
+ });
2593
+ }
2327
2594
  }
2328
2595
  }
2329
2596
  if (data.gap !== undefined && data.gap.samples > 0) {
2330
2597
  lines.push({ text: "", tone: "muted" });
2331
- lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
2332
- const widths = [9, 8, 9, 9, 10];
2333
- lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
2334
- for (const bucket of data.gap.buckets) {
2335
- if (bucket.samples === 0)
2336
- continue;
2337
- lines.push({
2338
- text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
2339
- tone: bucket.drops > 0 ? "warning" : "base"
2340
- });
2598
+ push("cache survival against idle time", HEADER_TONE);
2599
+ const buckets = data.gap.buckets;
2600
+ const survival = fitTable([
2601
+ { header: "gap", width: 8, max: 12, cell: (bucket) => bucket.label },
2602
+ { header: "pairs", width: 6, align: "right", cell: (bucket) => formatCount(bucket.samples) },
2603
+ { header: "kept", width: 7, align: "right", cell: (bucket) => formatPercent(bucket.retainedRatio, 0) },
2604
+ { header: "drops", width: 7, align: "right", cell: (bucket) => formatCount(bucket.drops) },
2605
+ { header: "lost", width: 8, align: "right", cell: (bucket) => formatTokens(bucket.lostTokens) }
2606
+ ], width);
2607
+ if (survival.length > 0) {
2608
+ lines.push({ text: formatTableRow(survival.map((column) => column.header), survival.map((column) => column.width), survival.map((column) => column.align)), tone: "muted" });
2609
+ for (const bucket of buckets) {
2610
+ if (bucket.samples === 0)
2611
+ continue;
2612
+ lines.push({
2613
+ text: formatTableRow(survival.map((column) => column.cell(bucket)), survival.map((column) => column.width), survival.map((column) => column.align)),
2614
+ tone: bucket.drops > 0 ? "warning" : "base"
2615
+ });
2616
+ }
2341
2617
  }
2342
2618
  if (data.gap.providers.length > 1) {
2343
2619
  lines.push({ text: "", tone: "muted" });
2344
- lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
2345
- const providerWidths = [26, 8, 9, 9];
2346
- lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
2347
- for (const row of data.gap.providers.slice(0, 8)) {
2348
- lines.push({
2349
- text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
2350
- tone: "base"
2351
- });
2620
+ push("reuse kept, by provider", HEADER_TONE);
2621
+ const providers = data.gap.providers;
2622
+ const reuse = fitTable([
2623
+ { header: "provider", width: 12, max: 30, cell: (row) => row.provider },
2624
+ { header: "pairs", width: 6, align: "right", cell: (row) => formatCount(row.samples) },
2625
+ { header: "kept", width: 7, align: "right", cell: (row) => formatPercent(row.retainedRatio, 0) },
2626
+ { header: "lost", width: 8, align: "right", cell: (row) => formatTokens(row.lostTokens) }
2627
+ ], width);
2628
+ if (reuse.length > 0) {
2629
+ lines.push({ text: formatTableRow(reuse.map((column) => column.header), reuse.map((column) => column.width), reuse.map((column) => column.align)), tone: "muted" });
2630
+ for (const row of providers.slice(0, 8)) {
2631
+ lines.push({
2632
+ text: formatTableRow(reuse.map((column) => column.cell(row)), reuse.map((column) => column.width), reuse.map((column) => column.align)),
2633
+ tone: "base"
2634
+ });
2635
+ }
2352
2636
  }
2353
2637
  }
2354
2638
  }
2355
2639
  lines.push({ text: "", tone: "muted" });
2356
- lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
2640
+ push("observed cache TTL bounds", HEADER_TONE);
2357
2641
  if (data.evidence.length === 0) {
2358
- lines.push({ text: " no comparable step pairs yet", tone: "muted" });
2642
+ push(" no comparable step pairs yet", "muted");
2359
2643
  } else {
2360
- const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
2361
- lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
2362
- for (const row of data.evidence.slice(0, 10)) {
2363
- lines.push({
2364
- text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
2365
- tone: "base"
2366
- });
2644
+ const evidence = fitTable([
2645
+ { header: "model", width: 12, max: 44, cell: (row) => `${row.providerID}/${row.modelID}` },
2646
+ { header: "hits up to", width: 10, align: "right", cell: (row) => formatGap(row.maxHitGapMs) },
2647
+ { header: "drops from", width: 10, align: "right", cell: (row) => formatGap(row.minDropGapMs) },
2648
+ { header: "samples", width: 7, align: "right", priority: 1, cell: (row) => formatCount(row.samples) }
2649
+ ], width);
2650
+ if (evidence.length > 0) {
2651
+ lines.push({ text: formatTableRow(evidence.map((column) => column.header), evidence.map((column) => column.width), evidence.map((column) => column.align)), tone: "muted" });
2652
+ for (const row of data.evidence.slice(0, 10)) {
2653
+ lines.push({
2654
+ text: formatTableRow(evidence.map((column) => column.cell(row)), evidence.map((column) => column.width), evidence.map((column) => column.align)),
2655
+ tone: "base"
2656
+ });
2657
+ }
2367
2658
  }
2368
2659
  }
2369
2660
  if (data.drops.length > 0) {
2370
2661
  lines.push({ text: "", tone: "muted" });
2371
- lines.push({ text: "recent losses", tone: HEADER_TONE });
2372
- for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
2373
- const when = new Date(drop.at).toLocaleTimeString("en-GB");
2374
- lines.push({
2375
- 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"]),
2376
- tone: drop.reason === "expired" ? "warning" : "base"
2377
- });
2662
+ push("recent losses", HEADER_TONE);
2663
+ const losses = fitTable([
2664
+ { header: "when", width: 8, cell: (drop) => new Date(drop.at).toLocaleTimeString("en-GB") },
2665
+ { header: "provider/model", width: 14, max: 40, cell: (drop) => `${drop.providerID ?? ""}/${drop.modelID ?? ""}` },
2666
+ { header: "tokens", width: 7, align: "right", cell: (drop) => `\u2212${formatTokens(drop.tokens)}` },
2667
+ { header: "idle", width: 12, max: 24, priority: 1, cell: (drop) => `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}` }
2668
+ ], width);
2669
+ if (losses.length > 0) {
2670
+ lines.push({ text: formatTableRow(losses.map((column) => column.header), losses.map((column) => column.width), losses.map((column) => column.align)), tone: "muted" });
2671
+ for (const drop of [...data.drops].sort((left, right) => right.at - left.at).slice(0, 8)) {
2672
+ lines.push({
2673
+ text: formatTableRow(losses.map((column) => column.cell(drop)), losses.map((column) => column.width), losses.map((column) => column.align)),
2674
+ tone: drop.reason === "expired" ? "warning" : "base"
2675
+ });
2676
+ }
2378
2677
  }
2379
2678
  }
2380
2679
  return lines;
@@ -2395,110 +2694,162 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true, tot
2395
2694
  }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
2396
2695
  const overall = usageBuckets(totals);
2397
2696
  lines.push({
2398
- text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
2697
+ text: truncate(`${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`, width),
2399
2698
  tone: "muted"
2400
2699
  });
2401
2700
  if (rows.length > 1) {
2402
- lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
2403
- lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
2701
+ const bars = Math.max(4, width - 8);
2702
+ lines.push({ text: truncate(`steps ${sparkline(rows.map((row) => row.usage.steps), bars)}`, width), tone: "muted" });
2703
+ lines.push({ text: truncate(`cached ${sparkline(rows.map((row) => row.usage.cached), bars)}`, width), tone: "muted" });
2404
2704
  lines.push({
2405
- text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
2705
+ text: truncate(`cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)), bars)}`, width),
2406
2706
  tone: "muted"
2407
2707
  });
2408
2708
  }
2409
- const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
2410
- const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
2411
- const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
2412
- const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
2413
- lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
2709
+ const columns = fitTable([
2710
+ { header: "period", width: 10, max: 24, cell: (row) => row.label },
2711
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
2712
+ { header: "sess", width: 6, align: "right", priority: 5, cell: (row) => row.sessions },
2713
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
2714
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
2715
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
2716
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
2717
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
2718
+ ], width);
2719
+ if (columns.length === 0)
2720
+ return [...lines, { text: truncate("no room for a table at this width", width), tone: "muted" }];
2721
+ const header = formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align));
2722
+ lines.push({ text: header, tone: HEADER_TONE });
2414
2723
  const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
2415
2724
  for (const row of newest) {
2416
2725
  const buckets = usageBuckets(row.usage);
2417
- const cells = [
2418
- row.label,
2419
- formatCount(row.steps),
2420
- ...withSessions ? [formatCount(row.sessions)] : [],
2421
- formatTokens(buckets.prompt),
2422
- formatTokens(buckets.cached),
2423
- formatPercent(buckets.hit, 0),
2424
- formatTokens(buckets.output),
2425
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2426
- ];
2427
- lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
2726
+ const view = {
2727
+ label: row.label,
2728
+ steps: formatCount(row.steps),
2729
+ sessions: formatCount(row.sessions),
2730
+ prompt: formatTokens(buckets.prompt),
2731
+ cached: formatTokens(buckets.cached),
2732
+ hit: formatPercent(buckets.hit, 0),
2733
+ output: formatTokens(buckets.output),
2734
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2735
+ };
2736
+ lines.push({
2737
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
2738
+ tone: "base",
2739
+ row: { kind: "period", value: row.key }
2740
+ });
2428
2741
  }
2429
2742
  lines.push({ text: "", tone: "muted" });
2743
+ const total = {
2744
+ label: "total",
2745
+ steps: formatCount(totals.steps),
2746
+ sessions: formatCount(totalSessions ?? totals.sessions),
2747
+ prompt: formatTokens(overall.prompt),
2748
+ cached: formatTokens(overall.cached),
2749
+ hit: formatPercent(overall.hit, 0),
2750
+ output: formatTokens(overall.output),
2751
+ cost: formatSpend(overall.cost, estimates ? overall.listCost : 0)
2752
+ };
2430
2753
  lines.push({
2431
- text: formatTableRow([
2432
- "total",
2433
- formatCount(totals.steps),
2434
- ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
2435
- formatTokens(overall.prompt),
2436
- formatTokens(overall.cached),
2437
- formatPercent(overall.hit, 0),
2438
- formatTokens(overall.output),
2439
- formatSpend(overall.cost, estimates ? overall.listCost : 0)
2440
- ], widths, aligns),
2754
+ text: formatTableRow(columns.map((column) => column.cell(total)), columns.map((column) => column.width), columns.map((column) => column.align)),
2441
2755
  tone: HEADER_TONE
2442
2756
  });
2443
2757
  if (rows.length === 0)
2444
- lines.push({ text: "no usage recorded for this range", tone: "muted" });
2758
+ lines.push({ text: truncate("no usage recorded for this range", width), tone: "muted" });
2445
2759
  return lines;
2446
2760
  }
2761
+ function latencyMetric(label, values, width) {
2762
+ const prefix = padCell(label, 11);
2763
+ let text = `${prefix}${values[0] ?? "\u2013"}`;
2764
+ for (let index = 1;index < values.length; index += 1) {
2765
+ const next = `${text} \xB7 ${values[index]}`;
2766
+ if (next.length > width)
2767
+ break;
2768
+ text = next;
2769
+ }
2770
+ return text;
2771
+ }
2447
2772
  function latencyLines(report, width, groups, limit = 12, estimates = true) {
2448
2773
  const lines = [];
2449
- lines.push({
2450
- 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]),
2451
- tone: "base"
2452
- });
2453
- lines.push({
2454
- 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]),
2455
- tone: "base"
2456
- });
2457
- lines.push({
2458
- 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]),
2459
- tone: "base"
2460
- });
2774
+ if (width >= 68) {
2775
+ lines.push({
2776
+ 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]),
2777
+ tone: "base"
2778
+ });
2779
+ lines.push({
2780
+ 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]),
2781
+ tone: "base"
2782
+ });
2783
+ lines.push({
2784
+ 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]),
2785
+ tone: "base"
2786
+ });
2787
+ } else {
2788
+ lines.push({
2789
+ text: latencyMetric("wall", [`p50 ${formatMs(report.wall.p50)}`, `p90 ${formatMs(report.wall.p90)}`, `p99 ${formatMs(report.wall.p99)}`, `n ${formatCount(report.wall.count)}`], width),
2790
+ tone: "base"
2791
+ });
2792
+ lines.push({
2793
+ text: latencyMetric("stream", [`p50 ${formatMs(report.stream.p50)}`, `p90 ${formatMs(report.stream.p90)}`, `p99 ${formatMs(report.stream.p99)}`], width),
2794
+ tone: "base"
2795
+ });
2796
+ lines.push({
2797
+ text: latencyMetric("throughput", [`p50 ${formatTps(report.tps.p50)}`, `p90 ${formatTps(report.tps.p90)}`, `p99 ${formatTps(report.tps.p99)}`], width),
2798
+ tone: "base"
2799
+ });
2800
+ }
2461
2801
  lines.push({ text: "", tone: "muted" });
2462
2802
  lines.push({
2463
2803
  text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
2464
2804
  tone: "muted"
2465
2805
  });
2466
2806
  if (report.wall.count === 0)
2467
- lines.push({ text: "no completed steps for this range", tone: "muted" });
2807
+ lines.push({ text: truncate("no completed steps for this range", width), tone: "muted" });
2468
2808
  if (groups !== undefined && groups.length > 0) {
2469
2809
  lines.push({ text: "", tone: "muted" });
2470
2810
  lines.push({ text: "by group", tone: HEADER_TONE });
2471
- const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
2472
- const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
2473
- lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
2474
- for (const row of groups.slice(0, limit)) {
2475
- const thin = row.count < 5;
2476
- lines.push({
2477
- text: formatTableRow([
2478
- row.label,
2479
- formatCount(row.count),
2480
- formatMs(row.wall.p50),
2481
- formatMs(row.wall.p90),
2482
- formatMs(row.stream.p50),
2483
- formatTps(row.tps.p50),
2484
- formatTps(row.tps.p90),
2485
- formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
2486
- ], widths, aligns),
2487
- tone: thin ? "muted" : "base",
2488
- row: { kind: "model", value: row.key }
2489
- });
2811
+ const columns = fitTable([
2812
+ { header: "group", width: 8, max: 32, cell: (row) => row.label },
2813
+ { header: "n", width: 4, align: "right", cell: (row) => formatCount(row.count) },
2814
+ { header: "wall p50", width: 8, align: "right", cell: (row) => formatMs(row.wall.p50) },
2815
+ { header: "wall p90", width: 8, max: 9, align: "right", priority: 1, cell: (row) => formatMs(row.wall.p90) },
2816
+ { header: "stream", width: 6, max: 9, align: "right", priority: 2, cell: (row) => formatMs(row.stream.p50) },
2817
+ { header: "tps p50", width: 8, max: 9, align: "right", cell: (row) => formatTps(row.tps.p50) },
2818
+ { header: "tps p90", width: 8, max: 9, align: "right", priority: 3, cell: (row) => formatTps(row.tps.p90) },
2819
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2820
+ ], width);
2821
+ if (columns.length > 0) {
2822
+ lines.push({ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)), tone: "muted" });
2823
+ for (const row of groups.slice(0, limit)) {
2824
+ const thin = row.count < 5;
2825
+ lines.push({
2826
+ text: formatTableRow(columns.map((column) => column.cell(row)), columns.map((column) => column.width), columns.map((column) => column.align)),
2827
+ tone: thin ? "muted" : "base",
2828
+ row: { kind: "model", value: row.key }
2829
+ });
2830
+ }
2490
2831
  }
2491
- lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
2832
+ lines.push({ text: truncate("n < 5 is dimmed: too few samples to compare", width), tone: "muted" });
2492
2833
  }
2493
2834
  return lines;
2494
2835
  }
2495
2836
  function sessionsLines(rows, width, options) {
2496
2837
  const limit = options?.limit ?? 20;
2497
2838
  const estimates = options?.estimates !== false;
2498
- const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
2499
- const aligns = ["left", "right", "right", "right", "right", "right", "right"];
2839
+ const columns = fitTable([
2840
+ { header: "title", width: 10, max: 48, cell: (row) => row.title },
2841
+ { header: "steps", width: 6, align: "right", cell: (row) => row.steps },
2842
+ { header: "prompt", width: 7, max: 10, align: "right", priority: 1, cell: (row) => row.prompt },
2843
+ { header: "cached", width: 7, max: 10, align: "right", priority: 2, cell: (row) => row.cached },
2844
+ { header: "hit", width: 6, max: 7, align: "right", priority: 3, cell: (row) => row.hit },
2845
+ { header: "out", width: 7, max: 9, align: "right", priority: 4, cell: (row) => row.output },
2846
+ { header: "cost", width: 8, max: 9, align: "right", cell: (row) => row.cost }
2847
+ ], width);
2500
2848
  const lines = [
2501
- { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
2849
+ {
2850
+ text: formatTableRow(columns.map((column) => column.header), columns.map((column) => column.width), columns.map((column) => column.align)),
2851
+ tone: HEADER_TONE
2852
+ }
2502
2853
  ];
2503
2854
  const byID = new Map(rows.map((row) => [row.sessionID, row]));
2504
2855
  const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
@@ -2506,18 +2857,18 @@ function sessionsLines(rows, width, options) {
2506
2857
  const orderedAll = [...ordered, ...children];
2507
2858
  for (const row of orderedAll.slice(0, limit)) {
2508
2859
  const child = row.parentID !== undefined && byID.has(row.parentID);
2509
- const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
2510
2860
  const buckets = usageBuckets(row);
2861
+ const view = {
2862
+ title: `${child ? "\u21B3 " : ""}${row.title ?? row.sessionID}`,
2863
+ steps: formatCount(buckets.steps),
2864
+ prompt: formatTokens(buckets.prompt),
2865
+ cached: formatTokens(buckets.cached),
2866
+ hit: formatPercent(buckets.hit, 0),
2867
+ output: formatTokens(buckets.output),
2868
+ cost: formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2869
+ };
2511
2870
  lines.push({
2512
- text: formatTableRow([
2513
- `${child ? "\u21B3 " : ""}${title}`,
2514
- formatCount(buckets.steps),
2515
- formatTokens(buckets.prompt),
2516
- formatTokens(buckets.cached),
2517
- formatPercent(buckets.hit, 0),
2518
- formatTokens(buckets.output),
2519
- formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
2520
- ], widths, aligns),
2871
+ text: formatTableRow(columns.map((column) => column.cell(view)), columns.map((column) => column.width), columns.map((column) => column.align)),
2521
2872
  tone: child ? "muted" : "base",
2522
2873
  row: { kind: "session", value: row.sessionID }
2523
2874
  });
@@ -2532,14 +2883,14 @@ function sessionsLines(rows, width, options) {
2532
2883
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
2533
2884
  lines.push({ text: "", tone: "muted" });
2534
2885
  lines.push({
2535
- 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)}`,
2886
+ 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),
2536
2887
  tone: "muted"
2537
2888
  });
2538
2889
  }
2539
2890
  if (rows.length > limit)
2540
- lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
2891
+ lines.push({ text: truncate(`\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, width), tone: "muted" });
2541
2892
  if (rows.length === 0)
2542
- lines.push({ text: "no sessions recorded for this range", tone: "muted" });
2893
+ lines.push({ text: truncate("no sessions recorded for this range", width), tone: "muted" });
2543
2894
  return lines;
2544
2895
  }
2545
2896
  function dbLines(data, width) {
@@ -2547,16 +2898,16 @@ function dbLines(data, width) {
2547
2898
  const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
2548
2899
  lines.push({ text: truncate(data.info.path, width), tone: "base" });
2549
2900
  lines.push({
2550
- text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
2901
+ text: truncate(`${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`, width),
2551
2902
  tone: "muted"
2552
2903
  });
2553
2904
  lines.push({ text: "", tone: "muted" });
2554
2905
  lines.push({ text: "what it holds", tone: HEADER_TONE });
2555
2906
  for (const table of data.info.tables) {
2556
- lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
2907
+ lines.push({ text: truncate(` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, width), tone: table.rows === 0 ? "muted" : "base" });
2557
2908
  }
2558
2909
  lines.push({
2559
- 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")}`,
2910
+ 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),
2560
2911
  tone: "muted"
2561
2912
  });
2562
2913
  lines.push({ text: "", tone: "muted" });
@@ -2572,7 +2923,7 @@ function dbLines(data, width) {
2572
2923
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
2573
2924
  });
2574
2925
  }
2575
- const widths = [10, 13, 10];
2926
+ const widths = [9, 11, 10];
2576
2927
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
2577
2928
  for (const option of data.info.removable) {
2578
2929
  const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
@@ -2592,7 +2943,7 @@ function dbLines(data, width) {
2592
2943
  });
2593
2944
  if (data.busy === true) {
2594
2945
  lines.push({ text: "", tone: "muted" });
2595
- lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
2946
+ lines.push({ text: truncate("the recorder is writing: try the vacuum again in a moment", width), tone: "warning" });
2596
2947
  }
2597
2948
  return lines;
2598
2949
  }
@@ -2616,28 +2967,74 @@ function turnStats(turn) {
2616
2967
  steps: turn.steps
2617
2968
  };
2618
2969
  }
2970
+ function compactTurnLine(stats, width, options) {
2971
+ const labels = { ...DEFAULT_LABELS, ...options?.labels };
2972
+ const fields = { ...DEFAULT_FIELDS, ...options?.fields };
2973
+ const estimates = options?.estimates !== false;
2974
+ const headParts = [];
2975
+ if (fields.clock && stats.endAt !== undefined)
2976
+ headParts.push(formatClock(stats.endAt));
2977
+ if (stats.providerID !== undefined) {
2978
+ let identity = stats.providerID;
2979
+ if (fields.model && stats.modelID !== undefined)
2980
+ identity += `/${stats.modelID}`;
2981
+ if (fields.variant && stats.variant)
2982
+ identity += ` ${stats.variant}`;
2983
+ headParts.push(identity);
2984
+ }
2985
+ let head = headParts.join(" ");
2986
+ const totals = options?.turnTotals === "sum" ? stats.totals : stats.latest;
2987
+ const display = displayTotals(totals);
2988
+ const money = fields.cost ? formatMoney(stats.totals.cost, estimates ? stats.totals.listCost : 0, labels.estimate) : undefined;
2989
+ const cost = money === undefined ? undefined : `${labels.cost} ${money}`.trim();
2990
+ const warning = fields.cacheExpiry && stats.cacheExpired ? `\u26A0 ${labels.cacheExpired} (\u2212${formatTokens(stats.cacheDropTokens)}${stats.drops.length > 1 ? ` \xD7${stats.drops.length}` : ""})` : undefined;
2991
+ let suffix = [warning, cost].filter((part) => part !== undefined).join(" \xB7 ");
2992
+ if (suffix !== "" && suffix.length + 3 > width)
2993
+ suffix = cost ?? suffix;
2994
+ head = truncate(head, Math.max(0, width - (suffix === "" ? 0 : suffix.length + 3)));
2995
+ if (!fields.turn || stats.totals.steps === 0)
2996
+ return [head, suffix].filter((part) => part !== "").join(" \xB7 ");
2997
+ const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
2998
+ const volumes = [
2999
+ input,
3000
+ `${labels.cached} ${formatTokens(display.cached)}`,
3001
+ `${labels.output} ${formatTokens(display.output)}`,
3002
+ ...fields.reasoning ? [`${labels.reasoning} ${formatTokens(display.reasoning)}`] : []
3003
+ ];
3004
+ let numbers = "";
3005
+ for (const volume of volumes) {
3006
+ const next = numbers === "" ? volume : `${numbers}, ${volume}`;
3007
+ if ([head, next, suffix].filter((part) => part !== "").join(" \xB7 ").length > width)
3008
+ break;
3009
+ numbers = next;
3010
+ }
3011
+ return [head, numbers, suffix].filter((part) => part !== "").join(" \xB7 ");
3012
+ }
2619
3013
  function turnsLines(rows, width, options) {
2620
3014
  const lines = [];
2621
3015
  const warning = rows.filter((turn) => turn.drops.length > 0).length;
2622
3016
  lines.push({
2623
- text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
3017
+ text: truncate(`${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`, width),
2624
3018
  tone: "muted"
2625
3019
  });
2626
3020
  const showSession = options?.sessionTitles !== undefined;
2627
3021
  for (const turn of rows) {
2628
- const line = formatLine(turnStats(turn), {
3022
+ const stats = turnStats(turn);
3023
+ const line = formatLine(stats, {
2629
3024
  ...options,
2630
3025
  fields: { ...options?.fields, session: false }
2631
3026
  });
2632
3027
  const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
3028
+ const available = Math.max(0, width - title.length);
3029
+ const text = `${title}${line.length <= available ? line : compactTurnLine(stats, available, { ...options, fields: { ...options?.fields, session: false } })}`;
2633
3030
  lines.push({
2634
- text: truncate(`${title}${line}`, width),
3031
+ text: truncate(text, width),
2635
3032
  tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
2636
3033
  row: { kind: "turn", value: turn.sessionID }
2637
3034
  });
2638
3035
  }
2639
3036
  if (rows.length === 0)
2640
- lines.push({ text: "no finished turns for this range", tone: "muted" });
3037
+ lines.push({ text: truncate("no finished turns for this range", width), tone: "muted" });
2641
3038
  return lines;
2642
3039
  }
2643
3040
  function sessionSummaryLines(usage, budget = 34, estimates = true) {
@@ -2737,11 +3134,12 @@ function detailLabel(row) {
2737
3134
  }
2738
3135
  }
2739
3136
  function buildPanel(request) {
3137
+ const width = clampPanelWidth(request.width);
2740
3138
  try {
2741
- return build(request);
3139
+ return build({ ...request, width }).map((line) => line.text.length <= width ? line : { ...line, text: truncate(line.text, width) });
2742
3140
  } catch (error) {
2743
3141
  const message = error instanceof Error ? error.message : String(error);
2744
- return [{ text: `stats query failed: ${message}`, tone: "warning" }];
3142
+ return [{ text: truncate(`stats query failed: ${message}`, width), tone: "warning" }];
2745
3143
  }
2746
3144
  }
2747
3145
  function build(request) {
@@ -2813,6 +3211,13 @@ function build(request) {
2813
3211
  }
2814
3212
  case "db":
2815
3213
  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);
3214
+ case "go":
3215
+ return [
3216
+ {
3217
+ text: "OpenCode Go quota is read by the TUI and Desktop from the host; it is not stored in this database.",
3218
+ tone: "muted"
3219
+ }
3220
+ ];
2816
3221
  case "turns": {
2817
3222
  const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
2818
3223
  const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
@@ -2848,10 +3253,15 @@ function buildDetail(request, range, filters, estimates) {
2848
3253
  const steps = stepRows(db, { range, filters: scoped });
2849
3254
  return [
2850
3255
  head,
2851
- {
2852
- 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)}`,
2853
- tone: "muted"
2854
- },
3256
+ ...kvGrid([
3257
+ ["steps", formatCount(stats.steps)],
3258
+ ["in", formatTokens(stats.prompt - stats.cached)],
3259
+ ["prompt", formatTokens(stats.prompt)],
3260
+ ["cached", formatTokens(stats.cached)],
3261
+ ["write", formatTokens(stats.cacheWrite)],
3262
+ ["hit", percent(stats.hit)],
3263
+ ["p50", percent(stats.hitP50)]
3264
+ ], width),
2855
3265
  { text: "", tone: "muted" },
2856
3266
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2857
3267
  { text: "", tone: "muted" },
@@ -2870,10 +3280,14 @@ function buildDetail(request, range, filters, estimates) {
2870
3280
  const stats = cacheStatsOf(db, { range, filters: scoped });
2871
3281
  return [
2872
3282
  head,
2873
- {
2874
- 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)}`,
2875
- tone: "muted"
2876
- },
3283
+ ...kvGrid([
3284
+ ["steps", formatCount(stats.steps)],
3285
+ ["in", formatTokens(stats.prompt - stats.cached)],
3286
+ ["prompt", formatTokens(stats.prompt)],
3287
+ ["cached", formatTokens(stats.cached)],
3288
+ ["hit", percent(stats.hit)],
3289
+ ["p50", percent(stats.hitP50)]
3290
+ ], width),
2877
3291
  { text: "", tone: "muted" },
2878
3292
  ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2879
3293
  { text: "", tone: "muted" },
@@ -3242,7 +3656,7 @@ class ServiceError extends Error {
3242
3656
  this.code = code;
3243
3657
  }
3244
3658
  }
3245
- function clamp(value, minimum, maximum) {
3659
+ function clamp2(value, minimum, maximum) {
3246
3660
  if (!Number.isFinite(value))
3247
3661
  return minimum;
3248
3662
  return Math.min(maximum, Math.max(minimum, Math.round(value)));
@@ -3311,7 +3725,7 @@ function createService(db, options) {
3311
3725
  }
3312
3726
  function turnHistory(input) {
3313
3727
  const handle = db();
3314
- const width = clamp(input.width, 20, 120);
3728
+ const width = clamp2(input.width, 20, MAX_HISTORY_WIDTH);
3315
3729
  const limit = clampTurnsLimit(input.limit);
3316
3730
  const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
3317
3731
  const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
@@ -3340,7 +3754,7 @@ function createService(db, options) {
3340
3754
  function prune(input) {
3341
3755
  requireMaintenance();
3342
3756
  requireConfirm(input.confirm);
3343
- const days = clamp(input.days, 1, MAX_DAYS);
3757
+ const days = clamp2(input.days, 1, MAX_DAYS);
3344
3758
  return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY2));
3345
3759
  }
3346
3760
  function wipe(input) {
@@ -3463,4 +3877,4 @@ scope.onmessage = (event) => {
3463
3877
  }
3464
3878
  };
3465
3879
 
3466
- //# debugId=BFDB9404BB86848D64756E2164756E21
3880
+ //# debugId=0FF21E19CAE9E2DE64756E2164756E21