opencode-usage-insights 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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, createMemo as createMemo3, createRenderEffect as createRenderEffect2, createSignal as createSignal2 } 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"]);
@@ -351,6 +351,20 @@ function formatLine(stats, options) {
351
351
  return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
352
352
  }
353
353
 
354
+ // src/limits.ts
355
+ var MAX_PANEL_WIDTH = 200;
356
+ var MAX_TURNS = 50;
357
+ function clampPanelWidth(value) {
358
+ if (!Number.isFinite(value))
359
+ return 20;
360
+ return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
361
+ }
362
+ function clampTurnsLimit(value) {
363
+ if (!Number.isFinite(value))
364
+ return 1;
365
+ return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
366
+ }
367
+
354
368
  // src/text.ts
355
369
  var TEXT_LIMIT = 512;
356
370
  function sanitizeText(value, limit = TEXT_LIMIT) {
@@ -883,10 +897,13 @@ function turns(db, options) {
883
897
  window += row.streamed_at - row.created_at;
884
898
  }
885
899
  const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
900
+ const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
901
+ const firstAt = bucket[0]?.created_at ?? promptAt;
886
902
  result.push({
887
903
  sessionID: last.session_id,
888
904
  promptAt,
889
- endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
905
+ endAt,
906
+ durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
890
907
  promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
891
908
  providerID,
892
909
  modelID,
@@ -949,18 +966,159 @@ function filterOptions(db) {
949
966
  return { models: pick("model_id"), providers: pick("provider_id") };
950
967
  }
951
968
 
969
+ // src/quota.ts
970
+ var QUOTA_VIEW = "go";
971
+ var QUOTA_POLL_MS = 60000;
972
+ var DEFAULT_QUOTA_NAME = "OpenCode Go";
973
+ var DAY_MS = 24 * 60 * 60 * 1000;
974
+ var MIN_FORECAST_ELAPSED_MS = 30 * 60 * 1000;
975
+ function quotaNameOf(explicit, providerName) {
976
+ const custom = explicit?.trim();
977
+ if (custom !== undefined && custom !== "")
978
+ return custom;
979
+ const provider = providerName?.trim();
980
+ if (provider !== undefined && provider !== "")
981
+ return provider;
982
+ return DEFAULT_QUOTA_NAME;
983
+ }
984
+ function finite(value) {
985
+ return typeof value === "number" && Number.isFinite(value);
986
+ }
987
+ function clamp(value, minimum, maximum) {
988
+ return Math.min(maximum, Math.max(minimum, value));
989
+ }
990
+ function previousCycleStart(endAt) {
991
+ if (!finite(endAt))
992
+ return endAt;
993
+ const end = new Date(endAt);
994
+ const year = end.getUTCFullYear();
995
+ const month = end.getUTCMonth();
996
+ const day = end.getUTCDate();
997
+ const start = new Date(Date.UTC(year, month - 1, 1, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds()));
998
+ const lastDay = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 0)).getUTCDate();
999
+ start.setUTCDate(Math.min(day, lastDay));
1000
+ return start.getTime();
1001
+ }
1002
+ function forecastMonthly(meter, now) {
1003
+ const endAt = finite(meter.resetsAt) ? meter.resetsAt : now;
1004
+ const startAt = previousCycleStart(endAt);
1005
+ const total = Math.max(1, endAt - startAt);
1006
+ const elapsedMs = clamp(now - startAt, 0, total);
1007
+ const remainingMs = Math.max(0, endAt - now);
1008
+ const percent = clamp(finite(meter.percent) ? meter.percent : 0, 0, 100);
1009
+ const reached = meter.limited === true || percent >= 100;
1010
+ const ratePerDay = !reached && elapsedMs >= MIN_FORECAST_ELAPSED_MS && percent > 0 ? percent / (elapsedMs / DAY_MS) : 0;
1011
+ const projectedPercent = reached ? 100 : ratePerDay > 0 ? percent + ratePerDay * (remainingMs / DAY_MS) : percent;
1012
+ const rawExhaustAt = !reached && ratePerDay > 0 && percent < 100 ? now + (100 - percent) / ratePerDay * DAY_MS : undefined;
1013
+ const exhaustAt = rawExhaustAt !== undefined && rawExhaustAt < endAt ? rawExhaustAt : undefined;
1014
+ const willExhaust = exhaustAt !== undefined;
1015
+ const available = !reached && now < endAt && (elapsedMs >= MIN_FORECAST_ELAPSED_MS || percent === 0);
1016
+ return {
1017
+ startAt,
1018
+ endAt,
1019
+ elapsedMs,
1020
+ remainingMs,
1021
+ ratePerDay,
1022
+ projectedPercent,
1023
+ ...exhaustAt !== undefined ? { exhaustAt } : {},
1024
+ reached,
1025
+ available,
1026
+ willExhaust
1027
+ };
1028
+ }
1029
+ function quotaBar(percent, width = 10) {
1030
+ const value = clamp(finite(percent) ? percent : 0, 0, 100);
1031
+ const cells = Math.max(1, Math.round(width));
1032
+ const filled = value >= 100 ? cells : value <= 0 ? 0 : Math.min(cells, Math.max(1, Math.round(value / 100 * cells)));
1033
+ return `[${"#".repeat(filled)}${"-".repeat(cells - filled)}]`;
1034
+ }
1035
+ function formatRenewal(at, timeZone) {
1036
+ if (!finite(at))
1037
+ return "\u2013";
1038
+ try {
1039
+ return new Intl.DateTimeFormat("en-GB", {
1040
+ day: "2-digit",
1041
+ month: "short",
1042
+ year: "numeric",
1043
+ hour: "2-digit",
1044
+ minute: "2-digit",
1045
+ hour12: false,
1046
+ ...timeZone !== undefined ? { timeZone } : {}
1047
+ }).format(new Date(at)).replace(/,/g, "");
1048
+ } catch {
1049
+ return "\u2013";
1050
+ }
1051
+ }
1052
+ function formatRenewalCompact(at, timeZone) {
1053
+ if (!finite(at))
1054
+ return "\u2013";
1055
+ try {
1056
+ return new Intl.DateTimeFormat("en-GB", {
1057
+ day: "2-digit",
1058
+ month: "short",
1059
+ hour: "2-digit",
1060
+ minute: "2-digit",
1061
+ hour12: false,
1062
+ ...timeZone !== undefined ? { timeZone } : {}
1063
+ }).format(new Date(at)).replace(/,/g, "");
1064
+ } catch {
1065
+ return "\u2013";
1066
+ }
1067
+ }
1068
+ function formatCountdown(at, now) {
1069
+ const remaining = at - now;
1070
+ if (!finite(remaining))
1071
+ return "\u2013";
1072
+ if (remaining <= 0)
1073
+ return "due";
1074
+ return formatDuration(remaining);
1075
+ }
1076
+ function quotaStatus(quota) {
1077
+ const limited = [];
1078
+ if (quota.rolling.limited || quota.rolling.percent >= 100)
1079
+ limited.push("5-hour");
1080
+ if (quota.weekly.limited || quota.weekly.percent >= 100)
1081
+ limited.push("weekly");
1082
+ if (quota.monthly.limited || quota.monthly.percent >= 100)
1083
+ limited.push("monthly");
1084
+ return limited.length === 0 ? "active" : `${limited.join(" / ")} limit reached`;
1085
+ }
1086
+
952
1087
  // src/panel-data.ts
953
1088
  var PANEL_NAME = "usage-insights";
954
1089
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
1090
+ var CLIENT_VIEWS = [...PANEL_VIEWS, QUOTA_VIEW];
955
1091
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
956
1092
  var GRANULARITIES = ["day", "week", "month"];
957
- function parseArgs(input) {
1093
+ var SORT_KEYS = {
1094
+ models: ["steps", "cached", "hit", "out", "cost"],
1095
+ providers: ["steps", "cached", "hit", "cost", "share", "tps"],
1096
+ latency: ["n", "tps", "wall"],
1097
+ sessions: ["last", "steps", "cached", "cost"],
1098
+ turns: ["time", "cost", "tokens"]
1099
+ };
1100
+ function sortKeys(view) {
1101
+ return SORT_KEYS[view] ?? [];
1102
+ }
1103
+ function defaultSort(view) {
1104
+ return sortKeys(view)[0] ?? "";
1105
+ }
1106
+ function nextSort(view, current, step) {
1107
+ const keys = sortKeys(view);
1108
+ if (keys.length === 0)
1109
+ return current;
1110
+ const index = keys.indexOf(current);
1111
+ if (index === -1)
1112
+ return keys[0];
1113
+ return keys[(index + step + keys.length) % keys.length];
1114
+ }
1115
+ function parseArgs(input, views = CLIENT_VIEWS) {
958
1116
  const parsed = {};
959
1117
  for (const token of (input ?? "").split(/\s+/)) {
960
1118
  const value = token.trim().toLowerCase();
961
1119
  if (value === "")
962
1120
  continue;
963
- if (PANEL_VIEWS.includes(value))
1121
+ if (views.includes(value))
964
1122
  parsed.view = value;
965
1123
  else if (RANGE_KEYS.includes(value))
966
1124
  parsed.range = value;
@@ -997,10 +1155,10 @@ var DEFAULT_SETTINGS = {
997
1155
  modelID: "",
998
1156
  providerID: ""
999
1157
  };
1000
- function sanitizeSettings(raw) {
1158
+ function sanitizeSettings(raw, views = CLIENT_VIEWS) {
1001
1159
  const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
1002
1160
  return {
1003
- view: PANEL_VIEWS.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1161
+ view: views.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
1004
1162
  range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
1005
1163
  sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
1006
1164
  sortDesc: settings.sortDesc === true,
@@ -1157,25 +1315,28 @@ function usageBuckets(usage) {
1157
1315
  hit: prompt > 0 ? usage.cached / prompt : undefined
1158
1316
  };
1159
1317
  }
1160
- function viewBar(view, width = 200) {
1318
+ function viewBar(view, width = 200, views = CLIENT_VIEWS) {
1161
1319
  const key = (index) => String((index + 1) % 10);
1162
- const full = PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
1163
- const candidates = [full, PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
1320
+ const full = views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
1321
+ const candidates = [full, views.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
1164
1322
  for (const parts of candidates) {
1165
1323
  const text = parts.join(" ");
1166
1324
  if (text.length <= width)
1167
1325
  return { text, tone: "muted" };
1168
1326
  }
1169
- return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
1327
+ const index = views.indexOf(view);
1328
+ return { text: `[${index === -1 ? "?" : key(index)} ${view}] \xB7 1-9 0 or [ ] to switch`, tone: "muted" };
1170
1329
  }
1171
1330
  function keysFor(of) {
1331
+ if (of === QUOTA_VIEW)
1332
+ return "r refresh \xB7 t range \xB7 0 view \xB7 ? help \xB7 the quotas come from OpenCode Go";
1172
1333
  if (of === "db")
1173
- return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 e backfill estimates \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
1334
+ 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";
1174
1335
  if (of === "periods")
1175
- 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";
1336
+ 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";
1176
1337
  if (of === "turns")
1177
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1178
- 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";
1338
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 0 view \xB7 ? help";
1339
+ 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";
1179
1340
  }
1180
1341
  function filterSummary(filters) {
1181
1342
  const parts = [];
@@ -1192,7 +1353,7 @@ function helpLines(width) {
1192
1353
  const lines = [
1193
1354
  { text: "keys", tone: HEADER_TONE },
1194
1355
  { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
1195
- { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
1356
+ { text: " 1-9 0 [ ] choose a view \xB7 cycle views (9 is db, 0 is go)" },
1196
1357
  { text: " t shift+t previous / next range" },
1197
1358
  { text: " s shift+s cycle sort column \xB7 reverse" },
1198
1359
  { text: " b periods bucket: day \u2192 week \u2192 month" },
@@ -1201,6 +1362,13 @@ function helpLines(width) {
1201
1362
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
1202
1363
  { text: " e db: backfill list-price estimates for the $0 steps" },
1203
1364
  { text: "" },
1365
+ { text: "go quota \xB7 the host's OpenCode Go allowance", tone: HEADER_TONE },
1366
+ { text: " rolling the 5-hour window \xB7 weekly \xB7 monthly" },
1367
+ { text: " forecast the monthly percentage at its reset, from the" },
1368
+ { text: " cycle's average pace (not a sample history)" },
1369
+ { text: " renews the monthly reset reported by the host" },
1370
+ { text: " the plugin reads the host's local usage-limits endpoint;" },
1371
+ { text: " it never reads your API key and never talks to the Console." },
1204
1372
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
1205
1373
  { text: " prompt everything the provider saw: cached + fresh + writes" },
1206
1374
  { text: " in the uncached part: fresh input + cache writes" },
@@ -1229,12 +1397,107 @@ function helpLines(width) {
1229
1397
  { text: "" },
1230
1398
  { text: "database", tone: HEADER_TONE },
1231
1399
  { text: " the db view shows where the file lives, what it holds and how much" },
1232
- { text: " of it is old: \u2191\u2193 pick a retention, enter prunes from its cutoff date," },
1233
- { text: " e backfills list estimates, v gives the space back" },
1400
+ { text: " of it is old: \u2191\u2193 pick a retention or wipe, enter asks before it" },
1401
+ { text: " deletes, e backfills list estimates, v gives the space back" },
1234
1402
  { text: " local time \xB7 SQLite in the OpenCode state directory" }
1235
1403
  ];
1236
1404
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1237
1405
  }
1406
+ function quotaMeterLine(label, meter, now) {
1407
+ const state = meter.limited || meter.percent >= 100 ? "rate-limited" : `${Math.round(meter.percent)}% used`;
1408
+ const countdown = formatCountdown(meter.resetsAt, now);
1409
+ return {
1410
+ text: ` ${padCell(label, 9)}${quotaBar(meter.percent)} ${state} \xB7 ${countdown === "due" ? "resets due" : `resets in ${countdown}`}`,
1411
+ tone: meter.limited || meter.percent >= 100 ? "warning" : "base"
1412
+ };
1413
+ }
1414
+ function goQuotaLines(state, options) {
1415
+ const { now, width, loading, error } = options;
1416
+ const name = options.name?.trim() || DEFAULT_QUOTA_NAME;
1417
+ const lines = [];
1418
+ const push = (text, tone = "base") => {
1419
+ lines.push({ text, tone });
1420
+ };
1421
+ if (state === undefined) {
1422
+ if (error !== undefined && error !== "")
1423
+ push(`Go quota unavailable: ${error}`, "warning");
1424
+ else if (loading === true)
1425
+ push("reading OpenCode Go quota\u2026", "muted");
1426
+ else
1427
+ push("OpenCode Go quota is unavailable", "muted");
1428
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1429
+ }
1430
+ if (state.kind === "none") {
1431
+ push(name, "accent");
1432
+ push(state.reason === "console" ? "Connect OpenCode Console with /connect to see your Go allowance." : "This workspace has no active OpenCode Go subscription.", "muted");
1433
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1434
+ }
1435
+ const quota = state.quota;
1436
+ const workspace = quota.workspace?.name ?? quota.workspace?.id ?? "workspace";
1437
+ const status = quotaStatus(quota);
1438
+ const forecast = forecastMonthly(quota.monthly, now);
1439
+ push(`${name} \xB7 ${workspace}`, "accent");
1440
+ push(`status ${status}`, status === "active" ? "base" : "warning");
1441
+ lines.push(quotaMeterLine("rolling", quota.rolling, now));
1442
+ lines.push(quotaMeterLine("weekly", quota.weekly, now));
1443
+ lines.push(quotaMeterLine("monthly", quota.monthly, now));
1444
+ push("");
1445
+ if (forecast.reached || quota.monthly.limited) {
1446
+ push(`forecast monthly limit reached \xB7 renews ${formatRenewal(quota.monthly.resetsAt)}`, "warning");
1447
+ } else if (now >= forecast.endAt) {
1448
+ push("forecast monthly reset due \xB7 refresh", "warning");
1449
+ } else if (!forecast.available) {
1450
+ push("forecast too early in the cycle to project a monthly pace", "muted");
1451
+ } else if (quota.monthly.percent === 0) {
1452
+ push("forecast no monthly usage yet this cycle", "muted");
1453
+ } else if (forecast.willExhaust && forecast.exhaustAt !== undefined) {
1454
+ push(`forecast limit before renewal ~${formatRenewal(forecast.exhaustAt)} \xB7 ${formatDuration(forecast.exhaustAt - now)} from now \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`, "warning");
1455
+ } else {
1456
+ const projected = Math.min(999, Math.round(forecast.projectedPercent));
1457
+ const headroom = Math.max(0, Math.round(100 - forecast.projectedPercent));
1458
+ push(`forecast ~${projected}% at reset \xB7 ${headroom}% headroom \xB7 ${forecast.ratePerDay.toFixed(1)}%/day`);
1459
+ }
1460
+ const renewal = formatRenewal(quota.monthly.resetsAt);
1461
+ const countdown = formatCountdown(quota.monthly.resetsAt, now);
1462
+ push(`renews ${renewal} \xB7 ${countdown === "due" ? "renewal due" : `in ${countdown}`}`, "muted");
1463
+ if (quota.workspace?.usageURL !== undefined)
1464
+ push(`console ${quota.workspace.usageURL}`, "muted");
1465
+ const age = Math.max(0, now - quota.observedAt);
1466
+ push(`updated ${age < 1000 ? "just now" : `${formatDuration(age)} ago`}`, "muted");
1467
+ if (loading === true)
1468
+ push("refreshing\u2026", "muted");
1469
+ if (error !== undefined && error !== "")
1470
+ push(`quota refresh failed: ${error}`, "warning");
1471
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1472
+ }
1473
+ function goSidebarLines(state, now, width, name = DEFAULT_QUOTA_NAME) {
1474
+ if (state?.kind !== "ok" || width <= 0)
1475
+ return [];
1476
+ const quota = state.quota;
1477
+ const status = quotaStatus(quota);
1478
+ const forecast = forecastMonthly(quota.monthly, now);
1479
+ const base = `5h ${Math.round(quota.rolling.percent)}% \xB7 week ${Math.round(quota.weekly.percent)}% \xB7 month ${Math.round(quota.monthly.percent)}%`;
1480
+ const baseTone = status !== "active" || quota.monthly.percent >= 80 ? "warning" : "base";
1481
+ let forecastText = "forecast too early";
1482
+ let forecastTone = "muted";
1483
+ if (forecast.reached || quota.monthly.limited) {
1484
+ forecastText = "monthly limit reached";
1485
+ forecastTone = "warning";
1486
+ } else if (forecast.willExhaust) {
1487
+ forecastText = "limit before renewal";
1488
+ forecastTone = "warning";
1489
+ } else if (forecast.available && quota.monthly.percent > 0) {
1490
+ forecastText = `forecast ~${Math.min(999, Math.round(forecast.projectedPercent))}% at reset`;
1491
+ } else if (forecast.available && quota.monthly.percent === 0) {
1492
+ forecastText = "forecast no usage yet";
1493
+ }
1494
+ return [
1495
+ { text: truncate(name, width), tone: "accent" },
1496
+ { text: truncate(base, width), tone: baseTone },
1497
+ { text: truncate(forecastText, width), tone: forecastTone },
1498
+ { text: truncate(`renews ${formatRenewalCompact(quota.monthly.resetsAt)}`, width), tone: "muted" }
1499
+ ];
1500
+ }
1238
1501
  function usagePairs(usage, estimates = true) {
1239
1502
  if (usage === undefined)
1240
1503
  return [];
@@ -1725,10 +1988,14 @@ function dbLines(data, width) {
1725
1988
  });
1726
1989
  lines.push({ text: "", tone: "muted" });
1727
1990
  lines.push({ text: "clean up", tone: HEADER_TONE });
1728
- lines.push({ text: truncate(" \u2191\u2193 pick a retention \xB7 enter prunes the steps and their other usage (asks first) \xB7 v gives the space back", width), tone: "muted" });
1991
+ lines.push({
1992
+ text: truncate(` \u2191\u2193 pick a retention \xB7 enter prunes from its cutoff \xB7 the wipe row deletes everything (asks first)${data.estimates === false ? "" : " \xB7 e backfills list estimates"} \xB7 v gives the space back`, width),
1993
+ tone: "muted",
1994
+ hint: true
1995
+ });
1729
1996
  if (data.estimates !== false) {
1730
1997
  lines.push({
1731
- text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price \xB7 e retries`, width),
1998
+ text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price`, width),
1732
1999
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
1733
2000
  });
1734
2001
  }
@@ -1742,6 +2009,14 @@ function dbLines(data, width) {
1742
2009
  row: { kind: "prune", value: String(option.days) }
1743
2010
  });
1744
2011
  }
2012
+ const steps = data.info.tables.find((table) => table.name === "steps")?.rows ?? 0;
2013
+ const sessions = data.info.tables.find((table) => table.name === "sessions")?.rows ?? 0;
2014
+ lines.push({ text: "", tone: "muted" });
2015
+ lines.push({
2016
+ text: truncate(` wipe everything \xB7 ${formatCount(steps)} steps \xB7 ${formatCount(sessions)} sessions \xB7 cannot be undone`, width),
2017
+ tone: steps === 0 && sessions === 0 ? "muted" : "warning",
2018
+ row: { kind: "wipe", value: "all" }
2019
+ });
1745
2020
  if (data.busy === true) {
1746
2021
  lines.push({ text: "", tone: "muted" });
1747
2022
  lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
@@ -1837,6 +2112,8 @@ function sidebarLines(rows, options) {
1837
2112
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
1838
2113
  const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
1839
2114
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
2115
+ const header = `${clock} ${provider}`;
2116
+ const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
1840
2117
  const volumes = [
1841
2118
  ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
1842
2119
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
@@ -1848,7 +2125,7 @@ function sidebarLines(rows, options) {
1848
2125
  ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
1849
2126
  ` hit ${hit}${suffix}`
1850
2127
  ];
1851
- lines.push({ text: truncate(`${clock} ${provider}`, budget), tone: turn.providerChanged ? "warning" : "base" });
2128
+ lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
1852
2129
  const edge = index === 0 || index === rows.length - 1;
1853
2130
  if (edge || turn.modelChanged || turn.providerChanged) {
1854
2131
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
@@ -1869,1445 +2146,409 @@ function sidebarLines(rows, options) {
1869
2146
  }
1870
2147
 
1871
2148
  // src/panel.tsx
2149
+ import { insert as _$insert } from "@opentui/solid";
1872
2150
  import { effect as _$effect } from "@opentui/solid";
2151
+ import { createTextNode as _$createTextNode } from "@opentui/solid";
1873
2152
  import { insertNode as _$insertNode } from "@opentui/solid";
1874
- import { insert as _$insert } from "@opentui/solid";
1875
2153
  import { createComponent as _$createComponent } from "@opentui/solid";
1876
2154
  import { use as _$use } from "@opentui/solid";
1877
2155
  import { setProp as _$setProp } from "@opentui/solid";
1878
2156
  import { createElement as _$createElement } from "@opentui/solid";
1879
2157
  import { TextAttributes } from "@opentui/core";
1880
- import { For, createMemo, createRenderEffect, createSignal } from "solid-js";
2158
+ import { For, Show, createEffect, createMemo, createRenderEffect, createSignal } from "solid-js";
1881
2159
 
1882
- // src/stats/aggregates.ts
1883
- var STEP_AT = "COALESCE(created_at, recorded_at)";
1884
- function normalize(rows, optional) {
1885
- for (const row of rows) {
1886
- for (const key of optional)
1887
- if (row[key] === null)
1888
- row[key] = undefined;
1889
- }
1890
- return rows;
1891
- }
1892
- function groupBy(items, key) {
1893
- const groups = new Map;
1894
- for (const item of items) {
1895
- const group = key(item);
1896
- const list = groups.get(group);
1897
- if (list !== undefined)
1898
- list.push(item);
1899
- else
1900
- groups.set(group, [item]);
1901
- }
1902
- return groups;
1903
- }
1904
- var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,
1905
- model_id AS modelID, variant,
1906
- COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1907
- COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1908
- COALESCE(list_cost, 0) AS listCost,
1909
- created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1910
- var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
1911
- var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1912
- function stepRows(db, options) {
1913
- const filter = buildWhere(options?.range, options?.filters);
1914
- const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
1915
- return normalize(rows, STEP_OPTIONAL);
1916
- }
1917
- function cachePairs(db, options) {
1918
- const filter = buildWhere(options?.range, options?.filters);
1919
- const rows = normalize(db.query(`SELECT ${PAIR_COLUMNS} FROM steps ${filter.where} ORDER BY session_id, ${STEP_AT}, message_id`).all(...filter.params), STEP_OPTIONAL);
1920
- const from = options?.range?.from;
1921
- if (from === undefined || rows.length === 0)
1922
- return rows;
1923
- const seek = db.query(`SELECT ${PAIR_COLUMNS} FROM steps
1924
- WHERE session_id = ? AND COALESCE(created_at, recorded_at) < ?
1925
- ORDER BY COALESCE(created_at, recorded_at) DESC, message_id DESC LIMIT 1`);
1926
- for (const sessionID of new Set(rows.map((row) => row.sessionID))) {
1927
- const boundary = seek.get(sessionID, from);
1928
- if (boundary === null)
1929
- continue;
1930
- const step = normalize([boundary], STEP_OPTIONAL)[0];
1931
- step.boundary = true;
1932
- rows.push(step);
1933
- }
1934
- rows.sort((left, right) => {
1935
- if (left.sessionID !== right.sessionID)
1936
- return left.sessionID < right.sessionID ? -1 : 1;
1937
- if (left.at !== right.at)
1938
- return left.at - right.at;
1939
- return left.messageID < right.messageID ? -1 : left.messageID > right.messageID ? 1 : 0;
1940
- });
1941
- return rows;
1942
- }
1943
- function message(step) {
1944
- return {
1945
- type: "assistant",
1946
- id: step.messageID,
1947
- ...step.modelID === undefined ? {} : { model: { providerID: step.providerID ?? "", id: step.modelID, ...step.variant === undefined ? {} : { variant: step.variant } } },
1948
- tokens: { cache: { read: step.cached } },
1949
- time: {
1950
- ...step.createdAt === undefined ? {} : { created: step.createdAt },
1951
- ...step.streamedAt === undefined ? {} : { streamed: step.streamedAt },
1952
- ...step.completedAt === undefined ? {} : { completed: step.completedAt }
1953
- }
1954
- };
1955
- }
1956
- function pairsOf(rows) {
1957
- const pairs = [];
1958
- for (let index = 1;index < rows.length; index += 1) {
1959
- const previous = rows[index - 1];
1960
- const current = rows[index];
1961
- if (previous.sessionID !== current.sessionID)
1962
- continue;
1963
- pairs.push({ previous, current });
1964
- }
1965
- return pairs;
1966
- }
1967
- function usageOf(steps) {
1968
- const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
1969
- for (const step of steps) {
1970
- usage.steps += 1;
1971
- usage.input += step.input;
1972
- usage.cached += step.cached;
1973
- usage.cacheWrite += step.cacheWrite;
1974
- usage.output += step.output;
1975
- usage.reasoning += step.reasoning;
1976
- usage.cost += step.cost;
1977
- usage.listCost += step.listCost;
1978
- }
1979
- return usage;
1980
- }
1981
- function coverageOf(db, options) {
1982
- const filter = buildWhere(options?.range, options?.filters);
1983
- const row = db.query(`SELECT COUNT(*) AS steps,
1984
- COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,
1985
- COUNT(DISTINCT provider_id) AS providers,
1986
- COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1987
- COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1988
- COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at THEN 0 ELSE 1 END), 0) AS missingTps,
1989
- MIN(${STEP_AT}) AS firstAt,
1990
- MAX(${STEP_AT}) AS lastAt
1991
- FROM steps ${filter.where}`).get(...filter.params);
1992
- return {
1993
- steps: row.steps,
1994
- models: row.models,
1995
- providers: row.providers,
1996
- missingModel: row.missingModel,
1997
- unsettled: row.unsettled,
1998
- missingTps: row.missingTps,
1999
- firstAt: row.firstAt ?? undefined,
2000
- lastAt: row.lastAt ?? undefined
2001
- };
2002
- }
2003
- function groupedRows(db, options) {
2004
- const filter = buildWhere(options?.range, options?.filters);
2005
- const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
2006
- return normalize(rows, STEP_OPTIONAL);
2007
- }
2008
- function timingOf(step) {
2009
- const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
2010
- const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
2011
- return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
2012
- }
2013
- function timingRows(db, options) {
2014
- return groupedRows(db, options);
2015
- }
2016
- function latencyOf(rows) {
2017
- const wall = [];
2018
- const stream = [];
2019
- const tps = [];
2020
- for (const step of rows) {
2021
- const timing = timingOf(step);
2022
- if (timing.wall !== undefined)
2023
- wall.push(timing.wall);
2024
- if (timing.stream !== undefined)
2025
- stream.push(timing.stream);
2026
- if (timing.tps !== undefined)
2027
- tps.push(timing.tps);
2028
- }
2029
- return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
2030
- }
2031
- function latencyGroupsOf(rows, by) {
2032
- const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
2033
- const groups = [];
2034
- for (const [group, steps] of groupBy(rows, key)) {
2035
- const wall = [];
2036
- const stream = [];
2037
- const tps = [];
2038
- for (const step of steps) {
2039
- const timing = timingOf(step);
2040
- if (timing.wall !== undefined)
2041
- wall.push(timing.wall);
2042
- if (timing.stream !== undefined)
2043
- stream.push(timing.stream);
2044
- if (timing.tps !== undefined)
2045
- tps.push(timing.tps);
2046
- }
2047
- const [modelID, variant] = group.split("#");
2048
- groups.push({
2049
- key: group,
2050
- label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
2051
- count: steps.length,
2052
- usage: usageOf(steps),
2053
- wall: latencyStats(wall),
2054
- stream: latencyStats(stream),
2055
- tps: latencyStats(tps)
2056
- });
2057
- }
2058
- return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
2059
- }
2060
- var EMPTY_CACHE = { steps: 0, input: 0, cached: 0, cacheWrite: 0, prompt: 0, hit: undefined, hitP50: undefined };
2061
- function cacheStatsOfSteps(steps) {
2062
- let input = 0;
2063
- let cached = 0;
2064
- let cacheWrite = 0;
2065
- const ratios = [];
2066
- for (const step of steps) {
2067
- input += step.input;
2068
- cached += step.cached;
2069
- cacheWrite += step.cacheWrite;
2070
- const prompt = step.input + step.cached + step.cacheWrite;
2071
- if (prompt > 0)
2072
- ratios.push(step.cached / prompt);
2073
- }
2074
- const prompt = input + cached + cacheWrite;
2075
- return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) };
2076
- }
2077
- function cacheStatsOf(db, options) {
2078
- const rows = stepRows(db, options);
2079
- return rows.length === 0 ? EMPTY_CACHE : cacheStatsOfSteps(rows);
2080
- }
2081
- function cacheStatsByModel(rows) {
2082
- const out = [];
2083
- const inRange = rows.filter((row) => row.boundary !== true);
2084
- for (const [, group] of groupBy(inRange, (row) => modelKey(row.modelID ?? "(unknown)", row.variant))) {
2085
- out.push({ modelID: group[0].modelID ?? "(unknown)", variant: group[0].variant, cache: cacheStatsOfSteps(group) });
2086
- }
2087
- return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID));
2088
- }
2089
- function switchesOf(rows) {
2090
- const perModel = new Map;
2091
- const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 };
2092
- for (const { previous, current } of pairsOf(rows)) {
2093
- if (previous.modelID === undefined || current.modelID === undefined)
2094
- continue;
2095
- const key = modelKey(current.modelID, current.variant);
2096
- const row = perModel.get(key) ?? {
2097
- modelID: current.modelID,
2098
- variant: current.variant,
2099
- steps: 0,
2100
- pairs: 0,
2101
- changes: 0,
2102
- modelChanges: 0,
2103
- providerChanges: 0,
2104
- cacheLost: 0,
2105
- cacheLostEvents: 0
2106
- };
2107
- row.steps += 1;
2108
- row.pairs += 1;
2109
- totals.pairs += 1;
2110
- const modelChanged = key !== modelKey(previous.modelID, previous.variant);
2111
- const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID;
2112
- if (modelChanged)
2113
- row.modelChanges += 1;
2114
- if (providerChanged)
2115
- row.providerChanges += 1;
2116
- if (modelChanged || providerChanged) {
2117
- row.changes += 1;
2118
- totals.changes += 1;
2119
- const lost = cacheDrop(message(previous), message(current), "model");
2120
- if (lost !== undefined) {
2121
- row.cacheLost += lost;
2122
- row.cacheLostEvents += 1;
2123
- totals.cacheLost += lost;
2124
- totals.cacheLostEvents += 1;
2160
+ // src/rpc.ts
2161
+ import { Rpc } from "@opencode/plugin/rpc";
2162
+ var Tone = { type: "string", enum: ["base", "muted", "warning", "accent"] };
2163
+ var PanelRowSchema = {
2164
+ type: "object",
2165
+ properties: {
2166
+ kind: { type: "string", enum: ["model", "session", "period", "provider", "turn", "prune", "wipe"] },
2167
+ value: { type: "string", maxLength: 500 },
2168
+ variant: { type: "string", maxLength: 200 }
2169
+ },
2170
+ required: ["kind", "value"],
2171
+ additionalProperties: false
2172
+ };
2173
+ var PanelLineSchema = {
2174
+ type: "object",
2175
+ properties: {
2176
+ text: { type: "string" },
2177
+ tone: Tone,
2178
+ hint: { type: "boolean" },
2179
+ row: PanelRowSchema
2180
+ },
2181
+ required: ["text"],
2182
+ additionalProperties: false
2183
+ };
2184
+ var PanelSettingsSchema = {
2185
+ type: "object",
2186
+ properties: {
2187
+ view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db", "go"] },
2188
+ range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
2189
+ sort: { type: "string", maxLength: 40 },
2190
+ sortDesc: { type: "boolean" },
2191
+ granularity: { type: "string", enum: ["day", "week", "month"] },
2192
+ turnsScope: { type: "string", enum: ["session", "all"] },
2193
+ modelID: { type: "string", maxLength: 300 },
2194
+ providerID: { type: "string", maxLength: 300 }
2195
+ },
2196
+ required: ["view", "range", "sort", "sortDesc", "granularity", "turnsScope", "modelID", "providerID"],
2197
+ additionalProperties: false
2198
+ };
2199
+ var TableSizeSchema = {
2200
+ type: "object",
2201
+ properties: {
2202
+ name: { type: "string" },
2203
+ rows: { type: "number" }
2204
+ },
2205
+ required: ["name", "rows"],
2206
+ additionalProperties: false
2207
+ };
2208
+ var DbInfoSchema = {
2209
+ type: "object",
2210
+ properties: {
2211
+ path: { type: "string" },
2212
+ bytes: { type: "number" },
2213
+ walBytes: { type: "number" },
2214
+ schemaVersion: { type: "number" },
2215
+ tables: { type: "array", items: TableSizeSchema },
2216
+ firstAt: { type: "number" },
2217
+ lastAt: { type: "number" },
2218
+ removable: {
2219
+ type: "array",
2220
+ items: {
2221
+ type: "object",
2222
+ properties: { days: { type: "number" }, steps: { type: "number" } },
2223
+ required: ["days", "steps"],
2224
+ additionalProperties: false
2225
+ }
2226
+ },
2227
+ unpriced: { type: "number" }
2228
+ },
2229
+ required: ["path", "bytes", "schemaVersion", "tables", "removable", "unpriced"],
2230
+ additionalProperties: false
2231
+ };
2232
+ var FilterOptionSchema = {
2233
+ type: "object",
2234
+ properties: { value: { type: "string" }, steps: { type: "number" } },
2235
+ required: ["value", "steps"],
2236
+ additionalProperties: false
2237
+ };
2238
+ var PruneResultSchema = {
2239
+ type: "object",
2240
+ properties: {
2241
+ steps: { type: "number" },
2242
+ prompts: { type: "number" },
2243
+ events: { type: "number" },
2244
+ usage: { type: "number" }
2245
+ },
2246
+ required: ["steps", "prompts", "events", "usage"],
2247
+ additionalProperties: false
2248
+ };
2249
+ var WipeResultSchema = {
2250
+ type: "object",
2251
+ properties: {
2252
+ steps: { type: "number" },
2253
+ prompts: { type: "number" },
2254
+ events: { type: "number" },
2255
+ usage: { type: "number" },
2256
+ sessions: { type: "number" }
2257
+ },
2258
+ required: ["steps", "prompts", "events", "usage", "sessions"],
2259
+ additionalProperties: false
2260
+ };
2261
+ var BackfillResultSchema = {
2262
+ type: "object",
2263
+ properties: {
2264
+ candidates: { type: "number" },
2265
+ updated: { type: "number" }
2266
+ },
2267
+ required: ["candidates", "updated"],
2268
+ additionalProperties: false
2269
+ };
2270
+ var VacuumResultSchema = {
2271
+ type: "object",
2272
+ properties: {
2273
+ before: { type: "number" },
2274
+ after: { type: "number" },
2275
+ freed: { type: "number" }
2276
+ },
2277
+ required: ["before", "after", "freed"],
2278
+ additionalProperties: false
2279
+ };
2280
+ var NoInput = { type: "object", properties: {}, additionalProperties: false };
2281
+ var ErrorSchema = {
2282
+ type: "object",
2283
+ properties: { message: { type: "string", maxLength: 500 } },
2284
+ additionalProperties: false
2285
+ };
2286
+ var errors = {
2287
+ busy: ErrorSchema,
2288
+ unavailable: ErrorSchema,
2289
+ disabled: ErrorSchema,
2290
+ invalid: ErrorSchema
2291
+ };
2292
+ var UsageInsights = Rpc.define({
2293
+ id: "usage-insights",
2294
+ methods: {
2295
+ panel: {
2296
+ input: {
2297
+ type: "object",
2298
+ properties: {
2299
+ sessionID: { type: "string", maxLength: 200 },
2300
+ settings: PanelSettingsSchema,
2301
+ detail: PanelRowSchema,
2302
+ width: { type: "number", minimum: 20, maximum: MAX_PANEL_WIDTH },
2303
+ busy: { type: "boolean" }
2304
+ },
2305
+ required: ["sessionID", "settings", "width"],
2306
+ additionalProperties: false
2307
+ },
2308
+ output: {
2309
+ type: "object",
2310
+ properties: {
2311
+ lines: { type: "array", items: PanelLineSchema },
2312
+ database: DbInfoSchema
2313
+ },
2314
+ required: ["lines"],
2315
+ additionalProperties: false
2316
+ },
2317
+ errors
2318
+ },
2319
+ turns: {
2320
+ input: {
2321
+ type: "object",
2322
+ properties: {
2323
+ sessionID: { type: "string", maxLength: 200 },
2324
+ limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
2325
+ width: { type: "number", minimum: 20, maximum: 120 }
2326
+ },
2327
+ required: ["sessionID", "limit", "width"],
2328
+ additionalProperties: false
2329
+ },
2330
+ output: {
2331
+ type: "object",
2332
+ properties: {
2333
+ summary: { type: "array", items: PanelLineSchema },
2334
+ history: { type: "array", items: PanelLineSchema }
2335
+ },
2336
+ required: ["summary", "history"],
2337
+ additionalProperties: false
2338
+ },
2339
+ errors
2340
+ },
2341
+ listCost: {
2342
+ input: {
2343
+ type: "object",
2344
+ properties: { sessionID: { type: "string", maxLength: 200 } },
2345
+ required: ["sessionID"],
2346
+ additionalProperties: false
2347
+ },
2348
+ output: {
2349
+ type: "object",
2350
+ properties: { cost: { type: "number" } },
2351
+ required: ["cost"],
2352
+ additionalProperties: false
2353
+ },
2354
+ errors
2355
+ },
2356
+ filters: {
2357
+ input: NoInput,
2358
+ output: {
2359
+ type: "object",
2360
+ properties: {
2361
+ models: { type: "array", items: FilterOptionSchema },
2362
+ providers: { type: "array", items: FilterOptionSchema }
2363
+ },
2364
+ required: ["models", "providers"],
2365
+ additionalProperties: false
2366
+ },
2367
+ errors
2368
+ },
2369
+ dbInfo: {
2370
+ input: NoInput,
2371
+ output: DbInfoSchema,
2372
+ errors
2373
+ },
2374
+ prune: {
2375
+ input: {
2376
+ type: "object",
2377
+ properties: {
2378
+ days: { type: "number", minimum: 1, maximum: 3650 },
2379
+ confirm: { type: "boolean", enum: [true] }
2380
+ },
2381
+ required: ["days", "confirm"],
2382
+ additionalProperties: false
2383
+ },
2384
+ output: PruneResultSchema,
2385
+ errors
2386
+ },
2387
+ wipe: {
2388
+ input: {
2389
+ type: "object",
2390
+ properties: { confirm: { type: "boolean", enum: [true] } },
2391
+ required: ["confirm"],
2392
+ additionalProperties: false
2393
+ },
2394
+ output: WipeResultSchema,
2395
+ errors
2396
+ },
2397
+ vacuum: {
2398
+ input: {
2399
+ type: "object",
2400
+ properties: { confirm: { type: "boolean", enum: [true] } },
2401
+ required: ["confirm"],
2402
+ additionalProperties: false
2403
+ },
2404
+ output: VacuumResultSchema,
2405
+ errors
2406
+ },
2407
+ backfill: {
2408
+ input: {
2409
+ type: "object",
2410
+ properties: { confirm: { type: "boolean", enum: [true] } },
2411
+ required: ["confirm"],
2412
+ additionalProperties: false
2413
+ },
2414
+ output: BackfillResultSchema,
2415
+ errors
2416
+ }
2417
+ },
2418
+ events: {
2419
+ recorded: {
2420
+ schema: {
2421
+ type: "object",
2422
+ properties: {
2423
+ sessionID: { type: "string", maxLength: 200 },
2424
+ at: { type: "number" }
2425
+ },
2426
+ required: ["at"],
2427
+ additionalProperties: false
2125
2428
  }
2126
2429
  }
2127
- perModel.set(key, row);
2128
- }
2129
- return {
2130
- rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),
2131
- totals
2132
- };
2133
- }
2134
- var GAP_BUCKETS = [
2135
- ["<1m", 0, 60000],
2136
- ["1\u20135m", 60000, 5 * 60000],
2137
- ["5\u201315m", 5 * 60000, 15 * 60000],
2138
- ["15\u201360m", 15 * 60000, 60 * 60000],
2139
- ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
2140
- [">6h", 6 * 60 * 60000, undefined]
2141
- ];
2142
- function bucketFor(gapMs) {
2143
- const index = GAP_BUCKETS.findIndex(([, from, to]) => gapMs >= from && (to === undefined || gapMs < to));
2144
- return index === -1 ? GAP_BUCKETS.length - 1 : index;
2145
- }
2146
- function gapReportOf(rows) {
2147
- const buckets = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }));
2148
- const providers = new Map;
2149
- let samples = 0;
2150
- for (const { previous, current } of pairsOf(rows)) {
2151
- if (previous.modelID === undefined || current.modelID === undefined)
2152
- continue;
2153
- if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant))
2154
- continue;
2155
- if ((previous.providerID ?? "") !== (current.providerID ?? ""))
2156
- continue;
2157
- const gap = stepGap(message(previous), message(current));
2158
- if (gap === undefined)
2159
- continue;
2160
- const lost = cacheDrop(message(previous), message(current));
2161
- const bucket = buckets[bucketFor(gap)];
2162
- bucket.samples += 1;
2163
- samples += 1;
2164
- if (lost === undefined)
2165
- bucket.retained += 1;
2166
- else {
2167
- bucket.drops += 1;
2168
- bucket.lostTokens += lost;
2169
- }
2170
- const provider = current.providerID ?? previous.providerID ?? "(unknown)";
2171
- const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined };
2172
- row.samples += 1;
2173
- if (lost === undefined)
2174
- row.retained += 1;
2175
- else {
2176
- row.drops += 1;
2177
- row.lostTokens += lost;
2178
- }
2179
- providers.set(provider, row);
2180
2430
  }
2181
- for (const bucket of buckets)
2182
- bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined;
2183
- for (const row of providers.values())
2184
- row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined;
2431
+ });
2432
+
2433
+ // src/rpc-client.ts
2434
+ function usageApi(client, location) {
2435
+ const rpc = client.rpc(UsageInsights);
2436
+ const options = (signal) => ({
2437
+ ...location !== undefined && location.directory !== undefined ? { location: { directory: location.directory } } : {},
2438
+ ...signal !== undefined ? { signal } : {}
2439
+ });
2185
2440
  return {
2186
- buckets,
2187
- providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),
2188
- samples
2441
+ panel: (input, signal) => rpc.panel(input, options(signal)),
2442
+ turns: (input, signal) => rpc.turns(input, options(signal)),
2443
+ listCost: (input, signal) => rpc.listCost(input, options(signal)),
2444
+ filters: (signal) => rpc.filters({}, options(signal)),
2445
+ dbInfo: (signal) => rpc.dbInfo({}, options(signal)),
2446
+ prune: (input, signal) => rpc.prune(input, options(signal)),
2447
+ wipe: (input, signal) => rpc.wipe(input, options(signal)),
2448
+ vacuum: (input, signal) => rpc.vacuum(input, options(signal)),
2449
+ backfill: (input, signal) => rpc.backfill(input, options(signal)),
2450
+ onRecorded: (handler, signal) => rpc.events.on("recorded", (event) => handler(event.data), signal === undefined ? undefined : { signal })
2189
2451
  };
2190
2452
  }
2191
- function ttlEvidenceOf(rows) {
2192
- const evidence = new Map;
2193
- for (const { previous, current } of pairsOf(rows)) {
2194
- if (previous.modelID === undefined || current.modelID === undefined)
2195
- continue;
2196
- const key = `${current.providerID ?? ""}/${current.modelID}`;
2197
- const before = `${previous.providerID ?? ""}/${previous.modelID}#${previous.variant ?? ""}`;
2198
- const after = `${current.providerID ?? ""}/${current.modelID}#${current.variant ?? ""}`;
2199
- if (before !== after)
2200
- continue;
2201
- const row = evidence.get(key) ?? {
2202
- providerID: current.providerID ?? "(unknown)",
2203
- modelID: current.modelID,
2204
- samples: 0,
2205
- maxHitGapMs: undefined,
2206
- minDropGapMs: undefined
2207
- };
2208
- row.samples += 1;
2209
- const gapMs = stepGap(message(previous), message(current));
2210
- if (gapMs !== undefined) {
2211
- const lost = cacheDrop(message(previous), message(current));
2212
- if (lost === undefined)
2213
- row.maxHitGapMs = row.maxHitGapMs === undefined ? gapMs : Math.max(row.maxHitGapMs, gapMs);
2214
- else
2215
- row.minDropGapMs = row.minDropGapMs === undefined ? gapMs : Math.min(row.minDropGapMs, gapMs);
2216
- }
2217
- evidence.set(key, row);
2218
- }
2219
- return [...evidence.values()].sort((left, right) => right.samples - left.samples || `${left.providerID}/${left.modelID}`.localeCompare(`${right.providerID}/${right.modelID}`));
2220
- }
2221
- function cacheDropsOf(db, rows, options) {
2222
- const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS;
2223
- const losses = [];
2224
- for (const { previous, current } of pairsOf(rows)) {
2225
- const tokens = cacheDrop(message(previous), message(current), "model");
2226
- if (tokens === undefined)
2227
- continue;
2228
- losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) });
2229
- }
2230
- if (losses.length === 0)
2231
- return [];
2232
- const compactions = new Map;
2233
- const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
2234
- const events = db.query(`SELECT session_id, at FROM events
2235
- WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
2236
- ORDER BY at`).all(...sessionIDs);
2237
- for (const event of events) {
2238
- const list = compactions.get(event.session_id);
2239
- if (list !== undefined)
2240
- list.push(event.at);
2241
- else
2242
- compactions.set(event.session_id, [event.at]);
2453
+
2454
+ // src/panel.tsx
2455
+ function Panel(props) {
2456
+ const [anchor, setAnchor] = createSignal(undefined);
2457
+ const [detail, setDetail] = createSignal(undefined);
2458
+ const [help, setHelp] = createSignal(false);
2459
+ const [tick, setTick] = createSignal(0);
2460
+ const [busy, setBusy] = createSignal(false);
2461
+ const [lines, setLines] = createSignal([]);
2462
+ const [database, setDatabase] = createSignal(undefined);
2463
+ const [loading, setLoading] = createSignal(false);
2464
+ const [error, setError] = createSignal(undefined);
2465
+ let generation = 0;
2466
+ let scroller;
2467
+ const width = () => clampPanelWidth(Math.max(60, props.input.width - 4));
2468
+ const view = () => sanitizeSettings(props.settings, props.views).view;
2469
+ const settings = () => sanitizeSettings(props.settings, props.views);
2470
+ const api = () => usageApi(props.ctx.client, props.ctx.location);
2471
+ function errorMessage(cause) {
2472
+ if (cause instanceof Error)
2473
+ return cause.message;
2474
+ if (cause !== null && typeof cause === "object" && "message" in cause)
2475
+ return String(cause.message);
2476
+ return "usage service unavailable";
2243
2477
  }
2244
- return losses.map((loss) => {
2245
- const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
2246
- const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
2247
- const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
2478
+ const rowKey = (row) => `${row.kind}:${row.value}${row.variant !== undefined ? `#${row.variant}` : ""}`;
2479
+ const request = createMemo(() => {
2480
+ tick();
2481
+ props.deps.refresh?.();
2482
+ if (help() || view() === QUOTA_VIEW)
2483
+ return;
2484
+ const current = settings();
2248
2485
  return {
2249
- sessionID: loss.current.sessionID,
2250
- messageID: loss.current.messageID,
2251
- providerID: loss.current.providerID,
2252
- modelID: loss.current.modelID,
2253
- variant: loss.current.variant,
2254
- at: loss.current.at,
2255
- tokens: loss.tokens,
2256
- gapMs: loss.gapMs,
2257
- prevCached: loss.previous.cached,
2258
- reason
2486
+ sessionID: props.input.sessionID,
2487
+ settings: current,
2488
+ ...detail() !== undefined ? {
2489
+ detail: detail()
2490
+ } : {},
2491
+ width: width(),
2492
+ busy: busy()
2259
2493
  };
2260
- }).sort((left, right) => left.at - right.at);
2261
- }
2262
- function groupValues(steps) {
2263
- const wall = [];
2264
- const tps = [];
2265
- for (const step of steps) {
2266
- const timing = timingOf(step);
2267
- if (timing.wall !== undefined)
2268
- wall.push(timing.wall);
2269
- if (timing.tps !== undefined)
2270
- tps.push(timing.tps);
2271
- }
2272
- return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
2273
- }
2274
- function providerOf(steps, models) {
2275
- const values = groupValues(steps);
2276
- let firstAt;
2277
- let lastAt;
2278
- for (const step of steps) {
2279
- if (firstAt === undefined || step.at < firstAt)
2280
- firstAt = step.at;
2281
- if (lastAt === undefined || step.at > lastAt)
2282
- lastAt = step.at;
2283
- }
2284
- return {
2285
- provider: steps[0].providerID,
2286
- models: models.split("\x00"),
2287
- share: 0,
2288
- usage: usageOf(steps),
2289
- cache: values.cache,
2290
- tps: values.tps,
2291
- wall: values.wall,
2292
- firstAt,
2293
- lastAt
2294
- };
2295
- }
2296
- var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => modelLabel(key.slice(0, key.indexOf("#")), key.slice(key.indexOf("#") + 1) || undefined)).join("\x00");
2297
- function providerSummaryOf(rows) {
2298
- const out = [];
2299
- for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
2300
- const summary = providerOf(steps, modelNames(steps));
2301
- out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length });
2302
- }
2303
- return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? "").localeCompare(right.provider ?? ""));
2304
- }
2305
- function providerBreakdownOf(rows) {
2306
- const out = [];
2307
- for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
2308
- for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
2309
- const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
2310
- out.push({
2311
- ...providerOf(steps, modelNames(steps)),
2312
- modelID,
2313
- variant: variant === "" ? undefined : variant,
2314
- share: steps.length / modelRows.length
2315
- });
2316
- }
2317
- }
2318
- return out.sort((left, right) => right.usage.steps - left.usage.steps || right.cache.cached - left.cache.cached);
2319
- }
2320
- function isoWeek(date) {
2321
- const monday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
2322
- monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);
2323
- const thursday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 3);
2324
- const firstThursday = new Date(thursday.getFullYear(), 0, 4);
2325
- firstThursday.setDate(firstThursday.getDate() - (firstThursday.getDay() + 6) % 7 + 3);
2326
- const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000));
2327
- return { year: thursday.getFullYear(), week, monday };
2328
- }
2329
- function periodEnd(at, granularity) {
2330
- const date = new Date(at);
2331
- if (granularity === "month")
2332
- return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime();
2333
- if (granularity === "week")
2334
- return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime();
2335
- return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
2336
- }
2337
- function periodStart(at, granularity) {
2338
- const date = new Date(at);
2339
- const pad = (value) => String(value).padStart(2, "0");
2340
- if (granularity === "month") {
2341
- const start = new Date(date.getFullYear(), date.getMonth(), 1);
2342
- return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() };
2343
- }
2344
- if (granularity === "week") {
2345
- const { year, week, monday } = isoWeek(date);
2346
- return { key: `${year}-W${pad(week)}`, label: `${year}-W${pad(week)}`, start: monday.getTime() };
2347
- }
2348
- const start = new Date(date.getFullYear(), date.getMonth(), date.getDate());
2349
- const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
2350
- return { key, label: key, start: start.getTime() };
2351
- }
2352
- function periodsOf(rows, granularity, otherRows = []) {
2353
- const byKey = new Map;
2354
- for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {
2355
- const period = periodStart(steps[0].at, granularity);
2356
- byKey.set(key, {
2357
- key,
2358
- label: period.label,
2359
- at: period.start,
2360
- steps: steps.length,
2361
- sessions: new Set(steps.map((step) => step.sessionID)).size,
2362
- usage: usageOf(steps),
2363
- cache: cacheStatsOfSteps(steps)
2364
- });
2365
- }
2366
- for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {
2367
- const cost = group.reduce((sum, row) => sum + row.cost, 0);
2368
- const existing = byKey.get(key);
2369
- if (existing !== undefined) {
2370
- existing.usage.cost += cost;
2371
- existing.otherCost = (existing.otherCost ?? 0) + cost;
2372
- continue;
2494
+ });
2495
+ createEffect(() => {
2496
+ const input = request();
2497
+ const current = ++generation;
2498
+ if (input === undefined) {
2499
+ setLines(view() === QUOTA_VIEW ? [] : helpLines(width()));
2500
+ setDatabase(undefined);
2501
+ setError(undefined);
2502
+ setLoading(false);
2503
+ return;
2373
2504
  }
2374
- const period = periodStart(group[0].at, granularity);
2375
- byKey.set(key, {
2376
- key,
2377
- label: period.label,
2378
- at: period.start,
2379
- steps: 0,
2380
- sessions: new Set(group.map((row) => row.sessionID)).size,
2381
- usage: { ...usageOf([]), cost },
2382
- cache: cacheStatsOfSteps([]),
2383
- otherCost: cost
2505
+ setLoading(true);
2506
+ api().panel(input).then((result) => {
2507
+ if (current !== generation)
2508
+ return;
2509
+ setLines(result.lines);
2510
+ setDatabase(result.database);
2511
+ setError(undefined);
2512
+ }).catch((cause) => {
2513
+ if (current !== generation)
2514
+ return;
2515
+ setError(errorMessage(cause));
2516
+ if (lines().length === 0)
2517
+ setLines([]);
2518
+ }).finally(() => {
2519
+ if (current === generation)
2520
+ setLoading(false);
2384
2521
  });
2385
- }
2386
- return [...byKey.values()].sort((left, right) => left.at - right.at);
2387
- }
2388
-
2389
- // src/panel-build.ts
2390
- var SORT_KEYS = {
2391
- models: ["steps", "cached", "hit", "out", "cost"],
2392
- providers: ["steps", "cached", "hit", "cost", "share", "tps"],
2393
- latency: ["n", "tps", "wall"],
2394
- sessions: ["last", "steps", "cached", "cost"],
2395
- turns: ["time", "cost", "tokens"]
2396
- };
2397
- function sortKeys(view) {
2398
- return SORT_KEYS[view] ?? [];
2399
- }
2400
- function defaultSort(view) {
2401
- return sortKeys(view)[0] ?? "";
2402
- }
2403
- function nextSort(view, current, step) {
2404
- const keys = sortKeys(view);
2405
- if (keys.length === 0)
2406
- return current;
2407
- const index = keys.indexOf(current);
2408
- if (index === -1)
2409
- return keys[0];
2410
- return keys[(index + step + keys.length) % keys.length];
2411
- }
2412
- function detailLabel(row) {
2413
- switch (row.kind) {
2414
- case "model":
2415
- return `model ${row.variant !== undefined ? `${row.value} ${row.variant}` : row.value}`;
2416
- case "session":
2417
- case "turn":
2418
- return `session ${row.value}`;
2419
- case "period":
2420
- return `period ${row.value}`;
2421
- case "provider":
2422
- return `provider ${row.value}`;
2423
- case "prune":
2424
- return `prune older than ${row.value} days`;
2425
- }
2426
- }
2427
- function buildPanel(request) {
2428
- try {
2429
- return build(request);
2430
- } catch (error) {
2431
- const message = error instanceof Error ? error.message : String(error);
2432
- return [{ text: `stats query failed: ${message}`, tone: "warning" }];
2433
- }
2434
- }
2435
- function build(request) {
2436
- const { db, view, now, sessionStart, width } = request;
2437
- const estimates = request.estimates !== false;
2438
- const scoped = request.range === "session" && request.sessionID !== "";
2439
- const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
2440
- const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
2441
- if (request.detail !== undefined)
2442
- return buildDetail(request, range, filters, estimates);
2443
- switch (view) {
2444
- case "overview": {
2445
- const usage = overview(db, range, filters);
2446
- const sessionUsage = request.sessionID === "" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID });
2447
- const childIDs = request.sessionID === "" ? [] : childSessionIDs(db, request.sessionID);
2448
- const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs);
2449
- return overviewLines({
2450
- usage,
2451
- session: sessionUsage,
2452
- ...children.length > 0 ? { subagents: children } : {},
2453
- range: request.range,
2454
- activity: activityOf(db, range, filters, now),
2455
- coverage: coverageOf(db, { range, filters }),
2456
- estimates
2457
- }, width);
2458
- }
2459
- case "models": {
2460
- const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
2461
- const pairs = cachePairs(db, { range, filters });
2462
- const switches = switchesOf(pairs);
2463
- return modelsLines(rows, width, {
2464
- cache: cacheByModel(pairs),
2465
- switches: switchesByModel(switches.rows)
2466
- }, 40, estimates);
2467
- }
2468
- case "providers":
2469
- return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
2470
- case "cache": {
2471
- const pairs = cachePairs(db, { range, filters });
2472
- return cacheLines({
2473
- drops: cacheDropsOf(db, pairs),
2474
- evidence: ttlEvidenceOf(pairs),
2475
- gap: gapReportOf(pairs),
2476
- models: topCacheModels(pairs)
2477
- }, width);
2478
- }
2479
- case "periods": {
2480
- const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters));
2481
- const sessions = overview(db, range, filters).sessions;
2482
- return periodLines(rows, width, request.granularity, 40, estimates, sessions);
2483
- }
2484
- case "latency": {
2485
- const timings = timingRows(db, { range, filters });
2486
- const by = filters.modelID !== undefined ? "provider" : "model";
2487
- return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
2488
- }
2489
- case "sessions": {
2490
- const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates);
2491
- const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
2492
- return sessionsLines(rows, width, {
2493
- limit: 20,
2494
- estimates,
2495
- rollup: {
2496
- subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),
2497
- subagentCost: child.reduce((sum, row) => sum + row.cost, 0),
2498
- subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0)
2499
- }
2522
+ });
2523
+ const content = createMemo(() => {
2524
+ if (help())
2525
+ return helpLines(width());
2526
+ if (view() === QUOTA_VIEW) {
2527
+ return goQuotaLines(props.quota.state(), {
2528
+ now: Date.now(),
2529
+ width: width(),
2530
+ loading: props.quota.loading(),
2531
+ error: props.quota.error(),
2532
+ name: props.quotaName
2500
2533
  });
2501
2534
  }
2502
- case "db":
2503
- 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);
2504
- case "turns": {
2505
- const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
2506
- const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
2507
- const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
2508
- return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
2535
+ if (error() !== undefined && lines().length === 0) {
2536
+ return [{
2537
+ text: `usage service unavailable: ${error()}`,
2538
+ tone: "warning"
2539
+ }];
2509
2540
  }
2510
- }
2511
- }
2512
- function rangeForRequest(key, now) {
2513
- switch (key) {
2514
- case "today": {
2515
- const start = new Date(now);
2516
- start.setHours(0, 0, 0, 0);
2517
- return { from: start.getTime() };
2518
- }
2519
- case "7d":
2520
- return { from: now - 7 * 24 * 60 * 60 * 1000 };
2521
- case "30d":
2522
- return { from: now - 30 * 24 * 60 * 60 * 1000 };
2523
- default:
2524
- return;
2525
- }
2526
- }
2527
- function buildDetail(request, range, filters, estimates) {
2528
- const row = request.detail;
2529
- const db = request.db;
2530
- const width = request.width;
2531
- const head = { text: detailLabel(row), tone: "accent" };
2532
- const back = { text: "backspace returns \xB7 the header shows where you came from", tone: "muted" };
2533
- if (row.kind === "model") {
2534
- const scoped = { ...filters, modelKey: modelKey(row.value, row.variant) };
2535
- const stats = cacheStatsOf(db, { range, filters: scoped });
2536
- const steps = stepRows(db, { range, filters: scoped });
2537
- return [
2538
- head,
2539
- {
2540
- 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)}`,
2541
- tone: "muted"
2542
- },
2543
- { text: "", tone: "muted" },
2544
- ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2545
- { text: "", tone: "muted" },
2546
- ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
2547
- { text: "", tone: "muted" },
2548
- back
2549
- ];
2550
- }
2551
- if (row.kind === "session" || row.kind === "turn") {
2552
- const rows = turns(db, { sessionID: row.value, limit: 80 });
2553
- return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: "", tone: "muted" }, back];
2554
- }
2555
- if (row.kind === "provider") {
2556
- const scoped = { ...filters, provider: row.value };
2557
- const steps = stepRows(db, { range, filters: scoped });
2558
- const stats = cacheStatsOf(db, { range, filters: scoped });
2559
- return [
2560
- head,
2561
- {
2562
- 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)}`,
2563
- tone: "muted"
2564
- },
2565
- { text: "", tone: "muted" },
2566
- ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2567
- { text: "", tone: "muted" },
2568
- ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
2569
- { text: "", tone: "muted" },
2570
- back
2571
- ];
2572
- }
2573
- if (row.kind === "period") {
2574
- const periods = periodsOf(stepRows(db, { range, filters }), request.granularity);
2575
- const period = periods.find((entry) => entry.key === row.value);
2576
- const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at);
2577
- const to = period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY);
2578
- const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters });
2579
- return [
2580
- head,
2581
- { text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
2582
- { text: "", tone: "muted" },
2583
- ...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),
2584
- { text: "", tone: "muted" },
2585
- back
2586
- ];
2587
- }
2588
- return [head, back];
2589
- }
2590
- function percent(value) {
2591
- return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
2592
- }
2593
- function sortModels(rows, sort, desc, estimates = true) {
2594
- const sign = desc ? 1 : -1;
2595
- const pick = (model) => {
2596
- if (sort === "cached")
2597
- return model.totals.cached;
2598
- if (sort === "hit") {
2599
- const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite;
2600
- return prompt > 0 ? model.totals.cached / prompt : -1;
2601
- }
2602
- if (sort === "out")
2603
- return model.totals.output + model.totals.reasoning;
2604
- if (sort === "cost")
2605
- return estimates ? spend(model.totals) : model.totals.cost;
2606
- return model.totals.steps;
2607
- };
2608
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2609
- }
2610
- function sortProviders(rows, sort, desc, estimates = true) {
2611
- const sign = desc ? 1 : -1;
2612
- const pick = (row) => {
2613
- if (sort === "cached")
2614
- return row.cache.cached;
2615
- if (sort === "hit")
2616
- return row.cache.hit ?? -1;
2617
- if (sort === "cost")
2618
- return estimates ? spend(row.usage) : row.usage.cost;
2619
- if (sort === "share")
2620
- return row.share;
2621
- if (sort === "tps")
2622
- return row.tps ?? -1;
2623
- return row.usage.steps;
2624
- };
2625
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2626
- }
2627
- function sortLatency(rows, sort, desc) {
2628
- const sign = desc ? 1 : -1;
2629
- const pick = (row) => {
2630
- if (sort === "tps")
2631
- return row.tps.p50 ?? -1;
2632
- if (sort === "wall")
2633
- return row.wall.p50 ?? -1;
2634
- return row.count;
2635
- };
2636
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2637
- }
2638
- function sortSessions(rows, sort, desc, estimates = true) {
2639
- const sign = desc ? 1 : -1;
2640
- const pick = (row) => {
2641
- if (sort === "steps")
2642
- return row.steps;
2643
- if (sort === "cached")
2644
- return row.cached;
2645
- if (sort === "cost")
2646
- return estimates ? spend(row) : row.cost;
2647
- return row.lastAt ?? 0;
2648
- };
2649
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2650
- }
2651
- function sortTurns(rows, sort, desc, estimates = true) {
2652
- const sign = desc ? 1 : -1;
2653
- const pick = (row) => {
2654
- if (sort === "cost")
2655
- return estimates ? spend(row.totals) : row.totals.cost;
2656
- if (sort === "tokens")
2657
- return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning;
2658
- return row.endAt ?? 0;
2659
- };
2660
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2661
- }
2662
- function cacheByModel(pairs) {
2663
- const map = new Map;
2664
- for (const row of cacheStatsByModel(pairs)) {
2665
- map.set(modelKey(row.modelID, row.variant), row.cache);
2666
- }
2667
- return map;
2668
- }
2669
- function switchesByModel(rows) {
2670
- return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]));
2671
- }
2672
- function topCacheModels(pairs) {
2673
- return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
2674
- }
2675
- function activityOf(db, range, filters, now) {
2676
- const filter = buildWhere(range, filters, STEP_TIME);
2677
- const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params);
2678
- const from = range?.from ?? earliest?.at ?? 0;
2679
- const to = range?.to ?? now;
2680
- const span = Math.max(1, to - from);
2681
- const ladder = [3600000, 3 * 3600000, 6 * 3600000, 12 * 3600000, 86400000, 3 * 86400000, 7 * 86400000, 30 * 86400000];
2682
- const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1];
2683
- const rows = db.query(`SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps
2684
- FROM steps ${filter.where}
2685
- GROUP BY bucket ORDER BY bucket`).all(bucket, ...filter.params);
2686
- if (rows.length === 0)
2687
- return [];
2688
- const first = Math.floor(from / bucket);
2689
- const last = rows[rows.length - 1].bucket;
2690
- const series = [];
2691
- for (let index = first;index <= last; index += 1) {
2692
- series.push(rows.find((row) => row.bucket === index)?.steps ?? 0);
2693
- }
2694
- return series;
2695
- }
2696
-
2697
- // src/stats/maintenance.ts
2698
- import { statSync as statSync2 } from "fs";
2699
-
2700
- // src/stats/db.ts
2701
- import { Database } from "bun:sqlite";
2702
- import { chmodSync, mkdirSync } from "fs";
2703
- import { dirname } from "path";
2704
-
2705
- // src/stats/paths.ts
2706
- import { homedir } from "os";
2707
- import { join } from "path";
2708
- import { statSync } from "fs";
2709
- function defaultDbPath(env = process.env, platform = process.platform) {
2710
- const name = join("opencode", "opencode-usage-insights", "usage.db");
2711
- if (platform === "win32") {
2712
- return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
2713
- }
2714
- if (platform === "darwin") {
2715
- return join(homedir(), "Library", "Application Support", name);
2716
- }
2717
- return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
2718
- }
2719
- function expandHome(path, home = homedir()) {
2720
- if (path === "~")
2721
- return home;
2722
- if (path.startsWith("~/") || path.startsWith("~\\"))
2723
- return join(home, path.slice(2));
2724
- return path;
2725
- }
2726
- function resolveDbPath(configured, env = process.env, platform = process.platform) {
2727
- const home = env.HOME ?? env.USERPROFILE ?? homedir();
2728
- if (configured)
2729
- return expandHome(configured, home);
2730
- if (env.OPENCODE_USAGE_INSIGHTS_DB)
2731
- return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
2732
- return defaultDbPath(env, platform);
2733
- }
2734
- function ensureRegularFile(path) {
2735
- let stats;
2736
- try {
2737
- stats = statSync(path);
2738
- } catch {
2739
- return;
2740
- }
2741
- if (!stats.isFile())
2742
- throw new Error(`not a regular file: ${path}`);
2743
- }
2744
-
2745
- // src/stats/db.ts
2746
- var SCHEMA_VERSION = 11;
2747
- var LABEL_LIMIT = 4 * TEXT_LIMIT;
2748
- var SCHEMA = `
2749
- CREATE TABLE IF NOT EXISTS meta (
2750
- key TEXT PRIMARY KEY,
2751
- value TEXT NOT NULL
2752
- );
2753
-
2754
- CREATE TABLE IF NOT EXISTS sessions (
2755
- session_id TEXT PRIMARY KEY,
2756
- parent_id TEXT,
2757
- directory TEXT,
2758
- title TEXT,
2759
- started_at INTEGER,
2760
- updated_at INTEGER
2761
- );
2762
-
2763
- CREATE TABLE IF NOT EXISTS prompts (
2764
- session_id TEXT NOT NULL,
2765
- message_id TEXT NOT NULL,
2766
- created_at INTEGER,
2767
- PRIMARY KEY (session_id, message_id)
2768
- );
2769
- CREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);
2770
-
2771
- CREATE TABLE IF NOT EXISTS steps (
2772
- message_id TEXT PRIMARY KEY,
2773
- session_id TEXT NOT NULL,
2774
- parent_id TEXT,
2775
- provider_id TEXT,
2776
- model_id TEXT,
2777
- variant TEXT,
2778
- input_tokens INTEGER NOT NULL DEFAULT 0,
2779
- output_tokens INTEGER NOT NULL DEFAULT 0,
2780
- reasoning_tokens INTEGER NOT NULL DEFAULT 0,
2781
- cache_read INTEGER NOT NULL DEFAULT 0,
2782
- cache_write INTEGER NOT NULL DEFAULT 0,
2783
- cost REAL NOT NULL DEFAULT 0,
2784
- list_cost REAL,
2785
- created_at INTEGER,
2786
- streamed_at INTEGER,
2787
- completed_at INTEGER,
2788
- finish TEXT,
2789
- recorded_at INTEGER NOT NULL
2790
- );
2791
- CREATE INDEX IF NOT EXISTS steps_session ON steps(session_id, created_at);
2792
- CREATE INDEX IF NOT EXISTS steps_model ON steps(provider_id, model_id, variant);
2793
- CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
2794
- -- Every range filter and every ordering compares the step's own clock, which
2795
- -- falls back to the recording time for a step that was already in flight when
2796
- -- the plugin loaded. The index has to cover that expression, or every ranged
2797
- -- view is a full table scan.
2798
- CREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));
2799
- CREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));
2800
-
2801
- CREATE TABLE IF NOT EXISTS events (
2802
- id INTEGER PRIMARY KEY AUTOINCREMENT,
2803
- session_id TEXT NOT NULL,
2804
- kind TEXT NOT NULL,
2805
- message_id TEXT,
2806
- at INTEGER,
2807
- data TEXT
2808
- );
2809
- CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
2810
- CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
2811
-
2812
- -- Usage the host reports with no assistant step of its own: the compaction
2813
- -- summarisation and the session-title generation. The host publishes it as
2814
- -- session.usage.recorded with a source other than generate, and includes it in
2815
- -- the session's own cost/token totals. Primary key is the host event ID, so a
2816
- -- replayed event never counts twice.
2817
- CREATE TABLE IF NOT EXISTS usage (
2818
- id TEXT PRIMARY KEY,
2819
- session_id TEXT NOT NULL,
2820
- source TEXT NOT NULL,
2821
- at INTEGER,
2822
- cost REAL NOT NULL DEFAULT 0,
2823
- input_tokens INTEGER NOT NULL DEFAULT 0,
2824
- output_tokens INTEGER NOT NULL DEFAULT 0,
2825
- reasoning_tokens INTEGER NOT NULL DEFAULT 0,
2826
- cache_read INTEGER NOT NULL DEFAULT 0,
2827
- cache_write INTEGER NOT NULL DEFAULT 0
2828
- );
2829
- CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
2830
- CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
2831
- `;
2832
- var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
2833
- function jsonText(value) {
2834
- if (value === undefined || value === null)
2835
- return null;
2836
- if (typeof value === "string")
2837
- return value;
2838
- try {
2839
- return JSON.stringify(value);
2840
- } catch {
2841
- return null;
2842
- }
2843
- }
2844
- function finite(value) {
2845
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
2846
- }
2847
- function tokenCount(value) {
2848
- return Math.max(0, Math.floor(finite(value)));
2849
- }
2850
- function timestamp(value) {
2851
- return typeof value === "number" && Number.isFinite(value) ? value : null;
2852
- }
2853
- var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
2854
- var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
2855
- function dropUnused(db) {
2856
- const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
2857
- const tables = new Set(objects.filter((row) => row.type === "table").map((row) => row.name));
2858
- const indexes = new Set(objects.filter((row) => row.type === "index").map((row) => row.name));
2859
- if (tables.has("http_responses"))
2860
- db.exec("DROP TABLE http_responses");
2861
- if (indexes.has("steps_upstream"))
2862
- db.exec("DROP INDEX steps_upstream");
2863
- if (indexes.has("steps_router"))
2864
- db.exec("DROP INDEX steps_router");
2865
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
2866
- for (const name of REMOVED_COLUMNS) {
2867
- if (columns.has(name))
2868
- db.exec(`ALTER TABLE steps DROP COLUMN ${name}`);
2869
- }
2870
- if (tables.has("events")) {
2871
- const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(", ");
2872
- db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
2873
- }
2874
- }
2875
- function addMissing(db) {
2876
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
2877
- if (columns.size > 0 && !columns.has("list_cost")) {
2878
- db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
2879
- }
2880
- }
2881
- function dedupeEvents(db) {
2882
- const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
2883
- if (table === null)
2884
- return;
2885
- db.exec(`DELETE FROM events
2886
- WHERE kind = 'compaction' AND message_id IS NULL
2887
- AND rowid NOT IN (
2888
- SELECT MIN(rowid) FROM events
2889
- WHERE kind = 'compaction' AND message_id IS NULL
2890
- GROUP BY session_id, at, data
2891
- )`);
2892
- db.exec(`DELETE FROM events
2893
- WHERE message_id IS NOT NULL
2894
- AND rowid NOT IN (
2895
- SELECT MIN(rowid) FROM events
2896
- WHERE message_id IS NOT NULL
2897
- GROUP BY kind, message_id
2898
- )`);
2899
- }
2900
- function addEventKey(db) {
2901
- const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
2902
- if (table === null)
2903
- return;
2904
- db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
2905
- }
2906
- function backfillCompactionUsage(db) {
2907
- const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
2908
- if (!tables.has("events") || !tables.has("usage"))
2909
- return;
2910
- db.exec(`INSERT OR IGNORE INTO usage (
2911
- id, session_id, source, at, cost,
2912
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
2913
- )
2914
- SELECT 'compaction:' || rowid, session_id, 'compaction', at,
2915
- MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
2916
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
2917
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
2918
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
2919
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
2920
- MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
2921
- FROM events
2922
- WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
2923
- AND json_valid(data)`);
2924
- }
2925
- function migrate(db) {
2926
- dropUnused(db);
2927
- addMissing(db);
2928
- dedupeEvents(db);
2929
- backfillCompactionUsage(db);
2930
- addEventKey(db);
2931
- }
2932
- var POSIX = process.platform !== "win32";
2933
- function hardenDirectory(path) {
2934
- if (!POSIX)
2935
- return;
2936
- try {
2937
- chmodSync(path, 448);
2938
- } catch {}
2939
- }
2940
- function hardenFiles(path) {
2941
- if (!POSIX || path === ":memory:")
2942
- return;
2943
- for (const file of [path, `${path}-wal`, `${path}-shm`]) {
2944
- try {
2945
- chmodSync(file, 384);
2946
- } catch {}
2947
- }
2948
- }
2949
- function prepareDirectory(path) {
2950
- if (path === ":memory:")
2951
- return;
2952
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
2953
- hardenDirectory(dirname(path));
2954
- }
2955
- function openStatsDb(path) {
2956
- if (path !== ":memory:")
2957
- ensureRegularFile(path);
2958
- prepareDirectory(path);
2959
- const db = new Database(path, { create: true });
2960
- db.exec("PRAGMA journal_mode = WAL");
2961
- db.exec("PRAGMA busy_timeout = 5000");
2962
- db.exec("PRAGMA synchronous = NORMAL");
2963
- db.exec(SCHEMA);
2964
- migrate(db);
2965
- db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
2966
- hardenFiles(path);
2967
- return db;
2968
- }
2969
- function openStatsDbReadOnly(path) {
2970
- ensureRegularFile(path);
2971
- const db = new Database(path, { readonly: true });
2972
- try {
2973
- db.query("SELECT 1 FROM steps LIMIT 1").get();
2974
- } catch (error) {
2975
- db.close();
2976
- throw error;
2977
- }
2978
- return db;
2979
- }
2980
- function openStatsDbWrite(path) {
2981
- if (path !== ":memory:")
2982
- ensureRegularFile(path);
2983
- prepareDirectory(path);
2984
- const db = new Database(path, { create: true });
2985
- db.exec("PRAGMA busy_timeout = 250");
2986
- db.exec("PRAGMA synchronous = NORMAL");
2987
- hardenFiles(path);
2988
- return db;
2989
- }
2990
- function recordStep(db, record) {
2991
- const cost = Math.max(0, finite(record.cost));
2992
- const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
2993
- db.query(`INSERT INTO steps (
2994
- message_id, session_id, parent_id, provider_id, model_id, variant,
2995
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
2996
- created_at, streamed_at, completed_at, finish, recorded_at
2997
- ) VALUES (
2998
- $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
2999
- $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
3000
- $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
3001
- )
3002
- ON CONFLICT(message_id) DO UPDATE SET
3003
- session_id = excluded.session_id,
3004
- parent_id = COALESCE(excluded.parent_id, steps.parent_id),
3005
- provider_id = COALESCE(excluded.provider_id, steps.provider_id),
3006
- model_id = COALESCE(excluded.model_id, steps.model_id),
3007
- variant = COALESCE(excluded.variant, steps.variant),
3008
- input_tokens = excluded.input_tokens,
3009
- output_tokens = excluded.output_tokens,
3010
- reasoning_tokens = excluded.reasoning_tokens,
3011
- cache_read = excluded.cache_read,
3012
- cache_write = excluded.cache_write,
3013
- cost = excluded.cost,
3014
- -- A step that starts being charged loses its estimate; an estimate is
3015
- -- kept when a replayed event arrives without a price table.
3016
- list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
3017
- created_at = COALESCE(excluded.created_at, steps.created_at),
3018
- streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
3019
- completed_at = COALESCE(excluded.completed_at, steps.completed_at),
3020
- finish = COALESCE(excluded.finish, steps.finish),
3021
- recorded_at = excluded.recorded_at`).run({
3022
- $messageID: record.messageID,
3023
- $sessionID: record.sessionID,
3024
- $parentID: record.parentID ?? null,
3025
- $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
3026
- $modelID: record.modelID ?? null,
3027
- $variant: record.variant ?? null,
3028
- $input: tokenCount(record.input),
3029
- $output: tokenCount(record.output),
3030
- $reasoning: tokenCount(record.reasoning),
3031
- $cacheRead: tokenCount(record.cacheRead),
3032
- $cacheWrite: tokenCount(record.cacheWrite),
3033
- $cost: cost,
3034
- $listCost: listCost,
3035
- $createdAt: timestamp(record.createdAt),
3036
- $streamedAt: timestamp(record.streamedAt),
3037
- $completedAt: timestamp(record.completedAt),
3038
- $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
3039
- $recordedAt: timestamp(record.recordedAt) ?? Date.now()
3040
- });
3041
- }
3042
- function recordUsage(db, record) {
3043
- if (typeof record.id !== "string" || record.id === "")
3044
- return;
3045
- if (typeof record.sessionID !== "string" || record.sessionID === "")
3046
- return;
3047
- db.query(`INSERT INTO usage (
3048
- id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3049
- ) VALUES (
3050
- $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
3051
- ) ON CONFLICT(id) DO NOTHING`).run({
3052
- $id: record.id,
3053
- $sessionID: record.sessionID,
3054
- $source: sanitizeLabel(record.source, 64),
3055
- $at: timestamp(record.at) ?? Date.now(),
3056
- $cost: Math.max(0, finite(record.cost)),
3057
- $input: tokenCount(record.input),
3058
- $output: tokenCount(record.output),
3059
- $reasoning: tokenCount(record.reasoning),
3060
- $cacheRead: tokenCount(record.cacheRead),
3061
- $cacheWrite: tokenCount(record.cacheWrite)
3062
- });
3063
- }
3064
- function recordPrompt(db, record) {
3065
- db.query(`INSERT INTO prompts (session_id, message_id, created_at)
3066
- VALUES ($sessionID, $messageID, $createdAt)
3067
- ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
3068
- $sessionID: record.sessionID,
3069
- $messageID: record.messageID,
3070
- $createdAt: timestamp(record.createdAt)
3071
- });
3072
- }
3073
- function recordEvent(db, record) {
3074
- db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
3075
- VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
3076
- $sessionID: record.sessionID,
3077
- $kind: sanitizeLabel(record.kind, 64),
3078
- $messageID: record.messageID ?? null,
3079
- $at: timestamp(record.at) ?? Date.now(),
3080
- $data: jsonText(record.data)
3081
- });
3082
- }
3083
- function upsertSession(db, record) {
3084
- db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at, updated_at)
3085
- VALUES ($sessionID, $parentID, $directory, $title, $startedAt, $updatedAt)
3086
- ON CONFLICT(session_id) DO UPDATE SET
3087
- parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
3088
- directory = COALESCE(excluded.directory, sessions.directory),
3089
- title = COALESCE(excluded.title, sessions.title),
3090
- started_at = COALESCE(sessions.started_at, excluded.started_at),
3091
- updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`).run({
3092
- $sessionID: record.sessionID,
3093
- $parentID: record.parentID ?? null,
3094
- $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
3095
- $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
3096
- $startedAt: timestamp(record.startedAt),
3097
- $updatedAt: timestamp(record.updatedAt)
3098
- });
3099
- }
3100
-
3101
- // src/stats/maintenance.ts
3102
- var STEP_TIME2 = "COALESCE(created_at, recorded_at)";
3103
- var DAY = 24 * 60 * 60 * 1000;
3104
- function size(path) {
3105
- try {
3106
- return statSync2(path).size;
3107
- } catch {
3108
- return 0;
3109
- }
3110
- }
3111
- function hasTable(db, name) {
3112
- try {
3113
- return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
3114
- } catch {
3115
- return false;
3116
- }
3117
- }
3118
- function dbInfo(db, path, now = Date.now()) {
3119
- const tables = TABLES.map((table) => ({
3120
- name: table,
3121
- rows: hasTable(db, table) ? db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n : 0
3122
- }));
3123
- const window = db.query(`SELECT MIN(${STEP_TIME2}) AS first, MAX(${STEP_TIME2}) AS last FROM steps`).get();
3124
- const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
3125
- return {
3126
- path,
3127
- unpriced: hasListCost(db) ? db.query(`SELECT COUNT(*) AS n FROM steps
3128
- WHERE cost = 0 AND list_cost IS NULL
3129
- AND provider_id IS NOT NULL AND provider_id <> ''
3130
- AND model_id IS NOT NULL AND model_id <> ''
3131
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n : 0,
3132
- bytes: size(path),
3133
- walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
3134
- schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
3135
- tables,
3136
- firstAt: window.first ?? undefined,
3137
- lastAt: window.last ?? undefined,
3138
- removable: [30, 90, 365].map((days) => ({
3139
- days,
3140
- steps: db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${STEP_TIME2} < ?`).get(now - days * DAY).n
3141
- }))
3142
- };
3143
- }
3144
- var PRUNE_BATCH = 5000;
3145
- function deleteBatched(db, table, where, cutoff) {
3146
- const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`);
3147
- let removed = 0;
3148
- for (;; ) {
3149
- const changes = statement.run(cutoff).changes;
3150
- removed += changes;
3151
- if (changes < PRUNE_BATCH)
3152
- break;
3153
- }
3154
- return removed;
3155
- }
3156
- function pruneOlderThan(db, cutoff) {
3157
- return {
3158
- steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
3159
- prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
3160
- events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
3161
- usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
3162
- };
3163
- }
3164
- function footprint(path) {
3165
- return size(path) + size(`${path}-wal`);
3166
- }
3167
- function vacuum(db, path) {
3168
- const before = footprint(path);
3169
- db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
3170
- db.exec("VACUUM");
3171
- const after = footprint(path);
3172
- return { before, after, freed: Math.max(0, before - after) };
3173
- }
3174
- function hasListCost(db) {
3175
- try {
3176
- return db.query("PRAGMA table_info(steps)").all().some((column) => column.name === "list_cost");
3177
- } catch {
3178
- return false;
3179
- }
3180
- }
3181
- var BACKFILL_BATCH = 1000;
3182
- function backfillListCost(db, price) {
3183
- if (!hasListCost(db))
3184
- return { candidates: 0, updated: 0 };
3185
- const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
3186
- WHERE cost = 0 AND list_cost IS NULL
3187
- AND provider_id IS NOT NULL AND provider_id <> ''
3188
- AND model_id IS NOT NULL AND model_id <> ''
3189
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
3190
- if (candidates === 0)
3191
- return { candidates: 0, updated: 0 };
3192
- const select = db.query(`SELECT rowid, provider_id, model_id,
3193
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3194
- FROM steps
3195
- WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
3196
- AND provider_id IS NOT NULL AND provider_id <> ''
3197
- AND model_id IS NOT NULL AND model_id <> ''
3198
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
3199
- ORDER BY rowid
3200
- LIMIT ?`);
3201
- const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
3202
- let cursor = 0;
3203
- let updated = 0;
3204
- for (;; ) {
3205
- const rows = select.all(cursor, BACKFILL_BATCH);
3206
- if (rows.length === 0)
3207
- break;
3208
- db.transaction(() => {
3209
- for (const row of rows) {
3210
- const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
3211
- input: row.input_tokens ?? 0,
3212
- output: row.output_tokens ?? 0,
3213
- reasoning: row.reasoning_tokens ?? 0,
3214
- cacheRead: row.cache_read ?? 0,
3215
- cacheWrite: row.cache_write ?? 0
3216
- });
3217
- if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
3218
- continue;
3219
- if (update.run(estimate, row.rowid).changes > 0)
3220
- updated += 1;
3221
- }
3222
- })();
3223
- cursor = rows[rows.length - 1].rowid;
3224
- if (rows.length < BACKFILL_BATCH)
3225
- break;
3226
- }
3227
- return { candidates, updated };
3228
- }
3229
-
3230
- // src/panel.tsx
3231
- function Panel(props) {
3232
- const [anchor, setAnchor] = createSignal(undefined);
3233
- const [detail, setDetail] = createSignal(undefined);
3234
- const [help, setHelp] = createSignal(false);
3235
- const [tick, setTick] = createSignal(0);
3236
- const [busy, setBusy] = createSignal(false);
3237
- let scroller;
3238
- const width = () => Math.max(60, props.input.width - 4);
3239
- const view = () => sanitizeSettings(props.settings).view;
3240
- const settings = () => sanitizeSettings(props.settings);
3241
- const filters = () => {
3242
- const current = settings();
3243
- return {
3244
- ...current.modelID !== "" ? {
3245
- modelID: current.modelID
3246
- } : {},
3247
- ...current.providerID !== "" ? {
3248
- provider: current.providerID
3249
- } : {}
3250
- };
3251
- };
3252
- const rowKey = (row) => `${row.kind}:${row.value}${row.variant !== undefined ? `#${row.variant}` : ""}`;
3253
- const database = createMemo(() => {
3254
- tick();
3255
- const handle = props.deps.db();
3256
- if (handle === undefined)
3257
- return;
3258
- try {
3259
- return dbInfo(handle, props.deps.dbPath(), props.deps.now());
3260
- } catch {
3261
- return;
3262
- }
3263
- });
3264
- const content = createMemo(() => {
3265
- tick();
3266
- props.deps.refresh?.();
3267
- const current = settings();
3268
- if (help())
3269
- return helpLines(width());
3270
- const db = props.deps.db();
3271
- if (db === undefined) {
3272
- return [{
3273
- text: `stats database is not readable at ${props.deps.dbPath()}; enable the usage-insights server plugin in opencode.json`,
3274
- tone: "warning"
3275
- }];
3276
- }
3277
- const info = current.view === "db" ? database() : undefined;
3278
- const request = {
3279
- db,
3280
- view: current.view,
3281
- range: current.range,
3282
- filters: filters(),
3283
- granularity: current.granularity,
3284
- turnsScope: current.turnsScope,
3285
- sort: current.sort,
3286
- sortDesc: current.sortDesc,
3287
- sessionID: props.input.sessionID,
3288
- sessionStart: props.deps.sessionStart(props.input.sessionID),
3289
- now: props.deps.now(),
3290
- format: props.format,
3291
- estimates: props.format?.estimates !== false,
3292
- ...detail() !== undefined ? {
3293
- detail: detail()
3294
- } : {},
3295
- ...info !== undefined ? {
3296
- database: info
3297
- } : {},
3298
- busy: busy(),
3299
- width: width()
3300
- };
3301
- return buildPanel(request);
2541
+ const visible = (line) => props.maintenance !== false || line.row?.kind !== "prune" && line.row?.kind !== "wipe";
2542
+ return lines().filter(visible);
3302
2543
  });
3303
2544
  const header = createMemo(() => {
3304
2545
  const current = settings();
3305
2546
  const filters = filterSummary(current);
3306
- const where = detail() !== undefined ? " \xB7 backspace returns" : filters === undefined ? "" : ` \xB7 ${filters}`;
2547
+ const where = detail() !== undefined ? " \xB7 backspace returns" : current.view === QUOTA_VIEW ? "" : filters === undefined ? "" : ` \xB7 ${filters}`;
3307
2548
  return [{
3308
- text: `usage insights \xB7 ${rangeLabel(current.range)}${where}`,
2549
+ text: `usage insights \xB7 ${current.view === QUOTA_VIEW ? `${props.quotaName} \xB7 live` : rangeLabel(current.range)}${where}`,
3309
2550
  tone: "accent"
3310
- }, viewBar(current.view, width()), {
2551
+ }, viewBar(current.view, width(), props.views), {
3311
2552
  text: "",
3312
2553
  tone: "muted"
3313
2554
  }];
@@ -3365,6 +2606,10 @@ function Panel(props) {
3365
2606
  prune(Number.parseInt(entry.row.value, 10));
3366
2607
  return;
3367
2608
  }
2609
+ if (entry.row.kind === "wipe") {
2610
+ wipe();
2611
+ return;
2612
+ }
3368
2613
  setDetail(entry.row);
3369
2614
  setAnchor(undefined);
3370
2615
  }
@@ -3376,6 +2621,13 @@ function Panel(props) {
3376
2621
  }
3377
2622
  }
3378
2623
  async function prune(days) {
2624
+ if (props.maintenance === false) {
2625
+ props.ctx.ui.toast.show({
2626
+ message: "database maintenance is disabled",
2627
+ variant: "warning"
2628
+ });
2629
+ return;
2630
+ }
3379
2631
  if (!Number.isFinite(days))
3380
2632
  return;
3381
2633
  if (sessionRunning()) {
@@ -3397,27 +2649,75 @@ function Panel(props) {
3397
2649
  });
3398
2650
  if (confirmed !== true)
3399
2651
  return;
3400
- const cutoff = props.deps.now() - days * 24 * 60 * 60 * 1000;
3401
- const result = props.deps.withWrite?.((handle) => pruneOlderThan(handle, cutoff));
3402
- if (result === undefined) {
2652
+ try {
2653
+ const result = await api().prune({
2654
+ days,
2655
+ confirm: true
2656
+ });
3403
2657
  props.ctx.ui.toast.show({
3404
- message: "the recorder is writing: try again in a moment",
2658
+ message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
2659
+ variant: "success"
2660
+ });
2661
+ } catch (cause) {
2662
+ props.ctx.ui.toast.show({
2663
+ message: errorMessage(cause),
3405
2664
  variant: "warning"
3406
2665
  });
3407
- } else {
2666
+ }
2667
+ setAnchor(undefined);
2668
+ setTick((value) => value + 1);
2669
+ props.deps.bump?.();
2670
+ }
2671
+ async function wipe() {
2672
+ if (props.maintenance === false) {
3408
2673
  props.ctx.ui.toast.show({
3409
- message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
2674
+ message: "database maintenance is disabled",
2675
+ variant: "warning"
2676
+ });
2677
+ return;
2678
+ }
2679
+ if (sessionRunning()) {
2680
+ props.ctx.ui.toast.show({
2681
+ message: "the session is running: wipe again when it is idle",
2682
+ variant: "warning"
2683
+ });
2684
+ return;
2685
+ }
2686
+ const info = database();
2687
+ const steps = info?.tables.find((table) => table.name === "steps")?.rows ?? 0;
2688
+ const sessions = info?.tables.find((table) => table.name === "sessions")?.rows ?? 0;
2689
+ const confirmed = await props.ctx.ui.dialog.confirm({
2690
+ title: "Wipe all recorded usage",
2691
+ message: `${formatCount(steps)} steps and ${formatCount(sessions)} sessions would be deleted, with their prompts, compactions and other usage. This cannot be undone.`,
2692
+ label: {
2693
+ confirm: "Wipe",
2694
+ cancel: "Keep"
2695
+ }
2696
+ });
2697
+ if (confirmed !== true)
2698
+ return;
2699
+ try {
2700
+ const result = await api().wipe({
2701
+ confirm: true
2702
+ });
2703
+ props.ctx.ui.toast.show({
2704
+ message: `wiped ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage \xB7 ${result.sessions} sessions`,
3410
2705
  variant: "success"
3411
2706
  });
2707
+ } catch (cause) {
2708
+ props.ctx.ui.toast.show({
2709
+ message: errorMessage(cause),
2710
+ variant: "warning"
2711
+ });
3412
2712
  }
3413
2713
  setAnchor(undefined);
3414
2714
  setTick((value) => value + 1);
3415
2715
  props.deps.bump?.();
3416
2716
  }
3417
2717
  async function backfillEstimates() {
3418
- if (props.format?.estimates === false) {
2718
+ if (props.maintenance === false) {
3419
2719
  props.ctx.ui.toast.show({
3420
- message: "list-price estimates are turned off",
2720
+ message: "database maintenance is disabled",
3421
2721
  variant: "warning"
3422
2722
  });
3423
2723
  return;
@@ -3438,7 +2738,7 @@ function Panel(props) {
3438
2738
  return;
3439
2739
  }
3440
2740
  const candidates = info?.unpriced ?? 0;
3441
- if (candidates === 0) {
2741
+ if (info !== undefined && candidates === 0) {
3442
2742
  props.ctx.ui.toast.show({
3443
2743
  message: "every $0 step already has a list estimate"
3444
2744
  });
@@ -3454,22 +2754,31 @@ function Panel(props) {
3454
2754
  });
3455
2755
  if (confirmed !== true)
3456
2756
  return;
3457
- const result = props.deps.backfill?.();
3458
- if (result === undefined) {
3459
- props.ctx.ui.toast.show({
3460
- message: "the price catalog is unavailable: try again in a moment",
3461
- variant: "warning"
2757
+ try {
2758
+ const result = await api().backfill({
2759
+ confirm: true
3462
2760
  });
3463
- } else {
3464
2761
  props.ctx.ui.toast.show({
3465
2762
  message: `backfilled ${formatCount(result.updated)} of ${formatCount(result.candidates)} steps`,
3466
2763
  variant: result.updated === 0 ? "warning" : "success"
3467
2764
  });
2765
+ } catch (cause) {
2766
+ props.ctx.ui.toast.show({
2767
+ message: errorMessage(cause),
2768
+ variant: "warning"
2769
+ });
3468
2770
  }
3469
2771
  setTick((value) => value + 1);
3470
2772
  props.deps.bump?.();
3471
2773
  }
3472
2774
  async function compact() {
2775
+ if (props.maintenance === false) {
2776
+ props.ctx.ui.toast.show({
2777
+ message: "database maintenance is disabled",
2778
+ variant: "warning"
2779
+ });
2780
+ return;
2781
+ }
3473
2782
  if (sessionRunning()) {
3474
2783
  props.ctx.ui.toast.show({
3475
2784
  message: "the session is running: compact again when it is idle",
@@ -3487,25 +2796,21 @@ function Panel(props) {
3487
2796
  });
3488
2797
  if (confirmed !== true)
3489
2798
  return;
3490
- const path = props.deps.dbPath();
3491
- let result;
3492
2799
  try {
3493
- result = props.deps.withWrite?.((handle) => vacuum(handle, path));
3494
- } catch {
3495
- result = undefined;
3496
- }
3497
- if (result === undefined) {
3498
- setBusy(true);
3499
- props.ctx.ui.toast.show({
3500
- message: "the recorder is writing: try again in a moment",
3501
- variant: "warning"
2800
+ const result = await api().vacuum({
2801
+ confirm: true
3502
2802
  });
3503
- } else {
3504
2803
  setBusy(false);
3505
2804
  props.ctx.ui.toast.show({
3506
2805
  message: `compacted: ${(result.freed / 1048576).toFixed(1)} MB back`,
3507
2806
  variant: "success"
3508
2807
  });
2808
+ } catch (cause) {
2809
+ setBusy(true);
2810
+ props.ctx.ui.toast.show({
2811
+ message: errorMessage(cause),
2812
+ variant: "warning"
2813
+ });
3509
2814
  }
3510
2815
  setTick((value) => value + 1);
3511
2816
  }
@@ -3516,10 +2821,16 @@ function Panel(props) {
3516
2821
  setAnchor(undefined);
3517
2822
  }
3518
2823
  async function pickFilter(kind) {
3519
- const db = props.deps.db();
3520
- if (db === undefined)
2824
+ let all;
2825
+ try {
2826
+ all = await api().filters();
2827
+ } catch (cause) {
2828
+ props.ctx.ui.toast.show({
2829
+ message: errorMessage(cause),
2830
+ variant: "warning"
2831
+ });
3521
2832
  return;
3522
- const all = filterOptions(db);
2833
+ }
3523
2834
  const list = kind === "model" ? all.models : all.providers;
3524
2835
  const current = settings();
3525
2836
  const selected = kind === "model" ? current.modelID : current.providerID;
@@ -3558,12 +2869,12 @@ function Panel(props) {
3558
2869
  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", "]", () => {
3559
2870
  setHelp(false);
3560
2871
  props.update((draft) => {
3561
- draft.view = nextIn(PANEL_VIEWS, sanitizeSettings(draft).view, 1);
2872
+ draft.view = nextIn(props.views, sanitizeSettings(draft, props.views).view, 1);
3562
2873
  });
3563
2874
  }), command("usage-insights.view.previous", "Previous view", "[", () => {
3564
2875
  setHelp(false);
3565
2876
  props.update((draft) => {
3566
- draft.view = nextIn(PANEL_VIEWS, sanitizeSettings(draft).view, -1);
2877
+ draft.view = nextIn(props.views, sanitizeSettings(draft, props.views).view, -1);
3567
2878
  });
3568
2879
  }), command("usage-insights.range.next", "Next range", "t", () => props.update((draft) => {
3569
2880
  draft.range = nextIn(RANGE_KEYS, sanitizeSettings(draft).range, 1);
@@ -3586,10 +2897,14 @@ function Panel(props) {
3586
2897
  draft.providerID = "";
3587
2898
  });
3588
2899
  setAnchor(undefined);
3589
- }), command("usage-insights.refresh", "Refresh", "r", () => setTick((value) => value + 1)), command("usage-insights.backfill", "Backfill list-price estimates", "e", () => {
2900
+ }), command("usage-insights.refresh", "Refresh", "r", () => {
2901
+ setTick((value) => value + 1);
2902
+ if (view() === QUOTA_VIEW)
2903
+ props.quota.refresh();
2904
+ }), command("usage-insights.backfill", "Backfill list-price estimates", "e", () => {
3590
2905
  if (view() === "db")
3591
2906
  backfillEstimates();
3592
- }), 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), () => {
2907
+ }), 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), () => {
3593
2908
  setHelp(false);
3594
2909
  props.update((draft) => {
3595
2910
  draft.view = name;
@@ -3612,13 +2927,13 @@ function Panel(props) {
3612
2927
  const selectedBackground = () => props.ctx.theme.background.raised.high;
3613
2928
  const cursorIndex = () => cursor();
3614
2929
  return (() => {
3615
- var _el$ = _$createElement("box"), _el$2 = _$createElement("scrollbox"), _el$3 = _$createElement("text"), _el$4 = _$createElement("text");
2930
+ var _el$ = _$createElement("box"), _el$2 = _$createElement("scrollbox"), _el$5 = _$createElement("text"), _el$6 = _$createElement("text");
3616
2931
  _$insertNode(_el$, _el$2);
3617
2932
  _$setProp(_el$, "flexDirection", "column");
3618
2933
  _$setProp(_el$, "paddingLeft", 1);
3619
2934
  _$setProp(_el$, "paddingRight", 1);
3620
- _$insertNode(_el$2, _el$3);
3621
- _$insertNode(_el$2, _el$4);
2935
+ _$insertNode(_el$2, _el$5);
2936
+ _$insertNode(_el$2, _el$6);
3622
2937
  _$use((target) => {
3623
2938
  scroller = target;
3624
2939
  const focusable = target;
@@ -3635,12 +2950,12 @@ function Panel(props) {
3635
2950
  return header();
3636
2951
  },
3637
2952
  children: (line) => (() => {
3638
- var _el$5 = _$createElement("text");
3639
- _$insert(_el$5, () => line.text);
3640
- _$effect((_$p) => _$setProp(_el$5, "fg", color(line.tone), _$p));
3641
- return _el$5;
2953
+ var _el$7 = _$createElement("text");
2954
+ _$insert(_el$7, () => line.text);
2955
+ _$effect((_$p) => _$setProp(_el$7, "fg", color(line.tone), _$p));
2956
+ return _el$7;
3642
2957
  })()
3643
- }), _el$3);
2958
+ }), _el$5);
3644
2959
  _$insert(_el$2, _$createComponent(For, {
3645
2960
  get each() {
3646
2961
  return content();
@@ -3648,14 +2963,14 @@ function Panel(props) {
3648
2963
  children: (line, index) => {
3649
2964
  const selected = () => index() === selectedLineIndex(content(), cursorIndex());
3650
2965
  return (() => {
3651
- var _el$6 = _$createElement("text");
3652
- _$insert(_el$6, () => line.text);
2966
+ var _el$8 = _$createElement("text");
2967
+ _$insert(_el$8, () => line.text);
3653
2968
  _$effect((_p$) => {
3654
2969
  var _v$3 = `line-${index()}`, _v$4 = color(line.tone), _v$5 = selected() ? selectedBackground() : undefined, _v$6 = selected() ? TextAttributes.BOLD : undefined;
3655
- _v$3 !== _p$.e && (_p$.e = _$setProp(_el$6, "id", _v$3, _p$.e));
3656
- _v$4 !== _p$.t && (_p$.t = _$setProp(_el$6, "fg", _v$4, _p$.t));
3657
- _v$5 !== _p$.a && (_p$.a = _$setProp(_el$6, "bg", _v$5, _p$.a));
3658
- _v$6 !== _p$.o && (_p$.o = _$setProp(_el$6, "attributes", _v$6, _p$.o));
2970
+ _v$3 !== _p$.e && (_p$.e = _$setProp(_el$8, "id", _v$3, _p$.e));
2971
+ _v$4 !== _p$.t && (_p$.t = _$setProp(_el$8, "fg", _v$4, _p$.t));
2972
+ _v$5 !== _p$.a && (_p$.a = _$setProp(_el$8, "bg", _v$5, _p$.a));
2973
+ _v$6 !== _p$.o && (_p$.o = _$setProp(_el$8, "attributes", _v$6, _p$.o));
3659
2974
  return _p$;
3660
2975
  }, {
3661
2976
  e: undefined,
@@ -3663,15 +2978,26 @@ function Panel(props) {
3663
2978
  a: undefined,
3664
2979
  o: undefined
3665
2980
  });
3666
- return _el$6;
2981
+ return _el$8;
3667
2982
  })();
3668
2983
  }
3669
- }), _el$3);
3670
- _$insert(_el$4, () => keysFor(view()));
2984
+ }), _el$5);
2985
+ _$insert(_el$2, _$createComponent(Show, {
2986
+ get when() {
2987
+ return loading();
2988
+ },
2989
+ get children() {
2990
+ var _el$3 = _$createElement("text");
2991
+ _$insertNode(_el$3, _$createTextNode(`loading\u2026`));
2992
+ _$effect((_$p) => _$setProp(_el$3, "fg", props.ctx.theme.text.muted, _$p));
2993
+ return _el$3;
2994
+ }
2995
+ }), _el$5);
2996
+ _$insert(_el$6, () => keysFor(view()));
3671
2997
  _$effect((_p$) => {
3672
2998
  var _v$ = props.ctx.theme.text.muted, _v$2 = props.ctx.theme.text.muted;
3673
- _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, "fg", _v$, _p$.e));
3674
- _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, "fg", _v$2, _p$.t));
2999
+ _v$ !== _p$.e && (_p$.e = _$setProp(_el$5, "fg", _v$, _p$.e));
3000
+ _v$2 !== _p$.t && (_p$.t = _$setProp(_el$6, "fg", _v$2, _p$.t));
3675
3001
  return _p$;
3676
3002
  }, {
3677
3003
  e: undefined,
@@ -3766,13 +3092,74 @@ function costOf(table, ref, usage) {
3766
3092
  return billed / 1e6;
3767
3093
  }
3768
3094
 
3095
+ // src/quota-client.ts
3096
+ function finite2(value) {
3097
+ return typeof value === "number" && Number.isFinite(value);
3098
+ }
3099
+ function meterOf(value) {
3100
+ if (value === undefined || !finite2(value.percent) || !finite2(value.resetsAt))
3101
+ return;
3102
+ return {
3103
+ percent: Math.min(100, Math.max(0, Math.round(value.percent))),
3104
+ limited: value.limited === true,
3105
+ resetsAt: value.resetsAt
3106
+ };
3107
+ }
3108
+ function workspaceOf(value) {
3109
+ const workspace = value?.workspace;
3110
+ if (workspace === undefined || workspace === null || typeof workspace.id !== "string" || workspace.id === "")
3111
+ return;
3112
+ return {
3113
+ id: workspace.id,
3114
+ ...typeof workspace.name === "string" && workspace.name !== "" ? { name: workspace.name } : {},
3115
+ ...typeof workspace.usageURL === "string" && workspace.usageURL !== "" ? { usageURL: workspace.usageURL } : {}
3116
+ };
3117
+ }
3118
+ function normalizeQuota(data, now = Date.now()) {
3119
+ if (data === null || data === undefined)
3120
+ return { kind: "none", reason: "console" };
3121
+ const value = data;
3122
+ const go = value?.go;
3123
+ if (go === undefined || go === null)
3124
+ return { kind: "none", reason: "subscription" };
3125
+ const rolling = meterOf(go.rolling);
3126
+ const weekly = meterOf(go.weekly);
3127
+ const monthly = meterOf(go.monthly);
3128
+ if (rolling === undefined || weekly === undefined || monthly === undefined) {
3129
+ return { kind: "none", reason: "subscription" };
3130
+ }
3131
+ const workspace = workspaceOf(value);
3132
+ return {
3133
+ kind: "ok",
3134
+ quota: {
3135
+ ...workspace !== undefined ? { workspace } : {},
3136
+ rolling,
3137
+ weekly,
3138
+ monthly,
3139
+ observedAt: now
3140
+ }
3141
+ };
3142
+ }
3143
+ async function fetchGoQuota(client, location, signal) {
3144
+ const usage = client.experimental?.usage;
3145
+ if (typeof usage?.limits !== "function") {
3146
+ throw new Error("this OpenCode build does not expose Go usage limits");
3147
+ }
3148
+ const payload = await usage.limits(location?.directory !== undefined ? { location: { directory: location.directory } } : undefined, signal !== undefined ? { signal } : undefined);
3149
+ const data = payload?.data;
3150
+ return normalizeQuota(data, Date.now());
3151
+ }
3152
+
3769
3153
  // src/sidebar.tsx
3770
- import { effect as _$effect2 } from "@opentui/solid";
3771
3154
  import { insert as _$insert2 } from "@opentui/solid";
3155
+ import { effect as _$effect2 } from "@opentui/solid";
3156
+ import { createTextNode as _$createTextNode2 } from "@opentui/solid";
3157
+ import { insertNode as _$insertNode2 } from "@opentui/solid";
3158
+ import { memo as _$memo } from "@opentui/solid";
3772
3159
  import { createComponent as _$createComponent2 } from "@opentui/solid";
3773
3160
  import { setProp as _$setProp2 } from "@opentui/solid";
3774
3161
  import { createElement as _$createElement2 } from "@opentui/solid";
3775
- import { For as For2, createMemo as createMemo2 } from "solid-js";
3162
+ import { For as For2, Show as Show2, createEffect as createEffect2, createMemo as createMemo2, createSignal as createSignal2, onCleanup } from "solid-js";
3776
3163
  function TurnsSidebar(props) {
3777
3164
  const color = (tone) => {
3778
3165
  switch (tone) {
@@ -3786,30 +3173,54 @@ function TurnsSidebar(props) {
3786
3173
  return props.ctx.theme.text.base;
3787
3174
  }
3788
3175
  };
3789
- const lines = createMemo2(() => {
3176
+ const [data, setData] = createSignal2(undefined);
3177
+ const [error, setError] = createSignal2(undefined);
3178
+ const [loading, setLoading] = createSignal2(false);
3179
+ let generation = 0;
3180
+ createEffect2(() => {
3790
3181
  props.deps.refresh();
3791
- const db = props.deps.db();
3792
- if (db === undefined)
3793
- return [];
3182
+ const input = {
3183
+ sessionID: props.sessionID,
3184
+ limit: props.deps.limit,
3185
+ width: props.deps.budget ?? 34
3186
+ };
3187
+ const current = ++generation;
3188
+ const controller = new AbortController;
3189
+ onCleanup(() => controller.abort());
3190
+ setLoading(true);
3191
+ usageApi(props.ctx.client, props.ctx.location).turns(input, controller.signal).then((result) => {
3192
+ if (current !== generation)
3193
+ return;
3194
+ setData(result);
3195
+ setError(undefined);
3196
+ }).catch((cause) => {
3197
+ if (current !== generation)
3198
+ return;
3199
+ setError(cause);
3200
+ }).finally(() => {
3201
+ if (current === generation)
3202
+ setLoading(false);
3203
+ });
3204
+ });
3205
+ const lines = createMemo2(() => {
3794
3206
  const budget = props.deps.budget ?? 34;
3795
- try {
3796
- const summary = sessionSummaryLines(overview(db, undefined, {
3797
- sessionID: props.sessionID
3798
- }), budget, props.options?.estimates !== false);
3799
- const history = sidebarLines(turns(db, {
3800
- sessionID: props.sessionID,
3801
- limit: props.deps.limit
3802
- }), {
3803
- ...props.options,
3804
- budget
3805
- });
3806
- return [...summary, {
3807
- text: "turns",
3808
- tone: "accent"
3809
- }, ...history];
3810
- } catch {
3811
- return [];
3812
- }
3207
+ const quotaLines = props.quota === undefined ? [] : goSidebarLines(props.quota(), Date.now(), budget, props.quotaName);
3208
+ const result = data();
3209
+ if (result === undefined) {
3210
+ if (error() !== undefined)
3211
+ return [...quotaLines, {
3212
+ text: "usage history unavailable",
3213
+ tone: "muted"
3214
+ }];
3215
+ return quotaLines;
3216
+ }
3217
+ return [...quotaLines.length > 0 ? [...quotaLines, {
3218
+ text: "",
3219
+ tone: "muted"
3220
+ }] : [], ...result.summary, {
3221
+ text: "turns",
3222
+ tone: "accent"
3223
+ }, ...result.history];
3813
3224
  });
3814
3225
  return (() => {
3815
3226
  var _el$ = _$createElement2("box");
@@ -3821,12 +3232,23 @@ function TurnsSidebar(props) {
3821
3232
  return lines();
3822
3233
  },
3823
3234
  children: (line) => (() => {
3235
+ var _el$4 = _$createElement2("text");
3236
+ _$insert2(_el$4, () => line.text);
3237
+ _$effect2((_$p) => _$setProp2(_el$4, "fg", color(line.tone), _$p));
3238
+ return _el$4;
3239
+ })()
3240
+ }), null);
3241
+ _$insert2(_el$, _$createComponent2(Show2, {
3242
+ get when() {
3243
+ return _$memo(() => !!loading())() && data() !== undefined;
3244
+ },
3245
+ get children() {
3824
3246
  var _el$2 = _$createElement2("text");
3825
- _$insert2(_el$2, () => line.text);
3826
- _$effect2((_$p) => _$setProp2(_el$2, "fg", color(line.tone), _$p));
3247
+ _$insertNode2(_el$2, _$createTextNode2(`\u2026`));
3248
+ _$effect2((_$p) => _$setProp2(_el$2, "fg", props.ctx.theme.text.muted, _$p));
3827
3249
  return _el$2;
3828
- })()
3829
- }));
3250
+ }
3251
+ }), null);
3830
3252
  return _el$;
3831
3253
  })();
3832
3254
  }
@@ -3847,8 +3269,71 @@ var tui_default = Plugin.define({
3847
3269
  return;
3848
3270
  const panelEnabled = options.panel !== false;
3849
3271
  const pricing = options.pricing !== "off";
3272
+ const quotaEnabled = options.quota !== "off";
3273
+ const quotaActive = quotaEnabled && (options.sidebar !== false || panelEnabled);
3274
+ const views = quotaEnabled ? CLIENT_VIEWS : PANEL_VIEWS;
3275
+ function providerName() {
3276
+ try {
3277
+ const providers = ctx.data.location?.provider?.list(ctx.location);
3278
+ return providers?.find((provider) => provider.id === "opencode-go")?.name;
3279
+ } catch {
3280
+ return;
3281
+ }
3282
+ }
3283
+ const quotaName = quotaNameOf(options.quotaName, providerName());
3850
3284
  const PRICE_TTL_MS = 5 * 60 * 1000;
3851
3285
  let priceCache;
3286
+ function errorMessage(cause) {
3287
+ if (cause instanceof Error)
3288
+ return cause.message;
3289
+ if (cause !== null && typeof cause === "object" && "message" in cause) {
3290
+ return String(cause.message);
3291
+ }
3292
+ return "the usage limits request failed";
3293
+ }
3294
+ const [quotaState, setQuotaState] = createSignal3(undefined);
3295
+ const [quotaLoading, setQuotaLoading] = createSignal3(quotaActive);
3296
+ const [quotaError, setQuotaError] = createSignal3(undefined);
3297
+ const [quotaTick, setQuotaTick] = createSignal3(0);
3298
+ let quotaGeneration = 0;
3299
+ const refreshQuota = () => {
3300
+ if (quotaActive)
3301
+ setQuotaTick((value) => value + 1);
3302
+ };
3303
+ createEffect3(() => {
3304
+ if (!quotaActive)
3305
+ return;
3306
+ quotaTick();
3307
+ const generation = ++quotaGeneration;
3308
+ const controller = new AbortController;
3309
+ onCleanup2(() => controller.abort());
3310
+ setQuotaLoading(true);
3311
+ fetchGoQuota(ctx.client, ctx.location, controller.signal).then((result) => {
3312
+ if (generation !== quotaGeneration)
3313
+ return;
3314
+ setQuotaState(result);
3315
+ setQuotaError(undefined);
3316
+ }).catch((cause) => {
3317
+ if (generation !== quotaGeneration)
3318
+ return;
3319
+ setQuotaError(errorMessage(cause));
3320
+ }).finally(() => {
3321
+ if (generation === quotaGeneration)
3322
+ setQuotaLoading(false);
3323
+ });
3324
+ });
3325
+ createEffect3(() => {
3326
+ if (!quotaActive)
3327
+ return;
3328
+ const timer = setInterval(() => setQuotaTick((value) => value + 1), QUOTA_POLL_MS);
3329
+ onCleanup2(() => clearInterval(timer));
3330
+ });
3331
+ const quotaResource = {
3332
+ state: quotaState,
3333
+ loading: quotaLoading,
3334
+ error: quotaError,
3335
+ refresh: refreshQuota
3336
+ };
3852
3337
  function priceTableFor() {
3853
3338
  if (!pricing)
3854
3339
  return;
@@ -3877,14 +3362,14 @@ var tui_default = Plugin.define({
3877
3362
  const patchSettings = (mutation) => {
3878
3363
  updateSettings(mutation);
3879
3364
  };
3880
- const [refresh, setRefresh] = createSignal2(0);
3881
- let database;
3882
- let databaseFailed = false;
3365
+ const [refresh, setRefresh] = createSignal3(0);
3366
+ const [listCosts, setListCosts] = createSignal3({});
3367
+ const pendingListCost = new Set;
3368
+ const dirtyListCost = new Set;
3369
+ const api = usageApi(ctx.client, ctx.location);
3883
3370
  let refreshTimer;
3884
3371
  let lastRefresh = 0;
3885
- const sessionCostCache = new Map;
3886
3372
  function bumpRefresh() {
3887
- sessionCostCache.clear();
3888
3373
  const now = Date.now();
3889
3374
  const wait = lastRefresh + REFRESH_THROTTLE_MS - now;
3890
3375
  if (wait <= 0) {
@@ -3901,62 +3386,39 @@ var tui_default = Plugin.define({
3901
3386
  }, wait);
3902
3387
  refreshTimer.unref?.();
3903
3388
  }
3904
- function db() {
3905
- if (database !== undefined)
3906
- return database;
3907
- if (databaseFailed)
3908
- return;
3909
- try {
3910
- database = openStatsDbReadOnly(resolveDbPath(options.db));
3911
- return database;
3912
- } catch {
3913
- databaseFailed = true;
3914
- return;
3915
- }
3916
- }
3917
- function sessionListCostFor(sessionID) {
3389
+ function listCostFor(sessionID) {
3918
3390
  if (!pricing)
3919
3391
  return 0;
3920
- const cached = sessionCostCache.get(sessionID);
3921
- if (cached !== undefined)
3922
- return cached;
3923
- const handle = db();
3924
- if (handle === undefined)
3925
- return 0;
3926
- try {
3927
- const value = sessionListCost(handle, sessionID);
3928
- if (sessionCostCache.size >= 512) {
3929
- const oldest = sessionCostCache.keys().next();
3930
- if (oldest.done !== true)
3931
- sessionCostCache.delete(oldest.value);
3932
- }
3933
- sessionCostCache.set(sessionID, value);
3934
- return value;
3935
- } catch {
3936
- return 0;
3937
- }
3392
+ return listCosts()[sessionID] ?? 0;
3938
3393
  }
3939
- function withWrite(run) {
3940
- let handle;
3941
- try {
3942
- handle = openStatsDbWrite(resolveDbPath(options.db));
3943
- return run(handle);
3944
- } catch {
3945
- return;
3946
- } finally {
3947
- handle?.close();
3948
- }
3949
- }
3950
- function backfill() {
3394
+ async function loadListCost(sessionID) {
3951
3395
  if (!pricing)
3952
3396
  return;
3953
- const table = priceTableFor();
3954
- if (table === undefined)
3397
+ if (pendingListCost.has(sessionID)) {
3398
+ dirtyListCost.add(sessionID);
3955
3399
  return;
3956
- return withWrite((handle) => backfillListCost(handle, (ref, tokens) => costOf(table, ref, tokens)));
3957
- }
3958
- function sessionStart(sessionID) {
3959
- return ctx.data.session.get(sessionID)?.time.created;
3400
+ }
3401
+ pendingListCost.add(sessionID);
3402
+ try {
3403
+ const result = await api.listCost({
3404
+ sessionID
3405
+ });
3406
+ setListCosts((current) => {
3407
+ const next = {
3408
+ ...current,
3409
+ [sessionID]: result.cost
3410
+ };
3411
+ const keys = Object.keys(next);
3412
+ if (keys.length > 512)
3413
+ for (const key of keys.slice(0, keys.length - 512))
3414
+ delete next[key];
3415
+ return next;
3416
+ });
3417
+ } catch {} finally {
3418
+ pendingListCost.delete(sessionID);
3419
+ if (dirtyListCost.delete(sessionID))
3420
+ loadListCost(sessionID);
3421
+ }
3960
3422
  }
3961
3423
  function sessionIdle(sessionID) {
3962
3424
  try {
@@ -3972,7 +3434,7 @@ var tui_default = Plugin.define({
3972
3434
  refresh();
3973
3435
  const messages = ctx.data.session.message.list(sessionID);
3974
3436
  const info = ctx.data.session.get(sessionID);
3975
- const session = info === undefined ? undefined : sessionTotals(info, sessionListCostFor(sessionID));
3437
+ const session = info === undefined ? undefined : sessionTotals(info, listCostFor(sessionID));
3976
3438
  return computeTurn(toTranscriptTail(messages, 2, priceFor()), session);
3977
3439
  }
3978
3440
  function toneColor(tone) {
@@ -3989,7 +3451,12 @@ var tui_default = Plugin.define({
3989
3451
  turnTotals: options.turnTotals,
3990
3452
  estimates: pricing
3991
3453
  }));
3992
- return _$createComponent3(Show, {
3454
+ createEffect3(() => {
3455
+ props.sessionID;
3456
+ refresh();
3457
+ loadListCost(props.sessionID);
3458
+ });
3459
+ return _$createComponent3(Show3, {
3993
3460
  get when() {
3994
3461
  return parts().length > 0;
3995
3462
  },
@@ -4027,25 +3494,17 @@ var tui_default = Plugin.define({
4027
3494
  input,
4028
3495
  ctx,
4029
3496
  deps: {
4030
- db,
4031
- dbPath: () => resolveDbPath(options.db),
4032
- withWrite,
4033
- backfill,
4034
- now: () => Date.now(),
4035
- sessionStart,
4036
3497
  refresh,
4037
3498
  bump: bumpRefresh
4038
3499
  },
4039
3500
  settings,
4040
3501
  update: patchSettings,
4041
- get format() {
4042
- return {
4043
- labels: options.labels,
4044
- fields: options.fields,
4045
- turnTotals: options.turnTotals,
4046
- estimates: pricing
4047
- };
4048
- }
3502
+ get maintenance() {
3503
+ return options.maintenance !== false;
3504
+ },
3505
+ views,
3506
+ quota: quotaResource,
3507
+ quotaName
4049
3508
  }) : null
4050
3509
  }) : () => {};
4051
3510
  const disposeSidebar = ctx.ui.slot({
@@ -4057,23 +3516,16 @@ var tui_default = Plugin.define({
4057
3516
  ctx,
4058
3517
  get deps() {
4059
3518
  return {
4060
- db,
4061
3519
  refresh,
4062
- limit: Math.max(1, Math.round(options.sidebarTurns ?? 8))
3520
+ limit: clampTurnsLimit(options.sidebarTurns ?? 8)
4063
3521
  };
4064
3522
  },
4065
- get options() {
4066
- return {
4067
- labels: options.labels,
4068
- fields: options.fields,
4069
- turnTotals: options.turnTotals,
4070
- estimates: pricing
4071
- };
4072
- }
3523
+ quota: quotaEnabled ? quotaState : undefined,
3524
+ quotaName
4073
3525
  })
4074
3526
  });
4075
3527
  function open(input) {
4076
- const parsed = parseArgs(input);
3528
+ const parsed = parseArgs(input, views);
4077
3529
  if (parsed.view !== undefined || parsed.range !== undefined) {
4078
3530
  patchSettings((draft) => {
4079
3531
  if (parsed.view !== undefined)
@@ -4101,14 +3553,14 @@ var tui_default = Plugin.define({
4101
3553
  bind: false,
4102
3554
  palette: true,
4103
3555
  slash: {
4104
- name: "usage",
3556
+ name: "usage-insights",
4105
3557
  aliases: ["insights"],
4106
3558
  arguments: true
4107
3559
  },
4108
3560
  run: (input) => {
4109
3561
  if (!open(input)) {
4110
3562
  ctx.ui.toast.show({
4111
- message: "Open a session first, then run /usage",
3563
+ message: "Open a session first, then run /usage-insights",
4112
3564
  variant: "warning"
4113
3565
  });
4114
3566
  }
@@ -4117,7 +3569,15 @@ var tui_default = Plugin.define({
4117
3569
  };
4118
3570
  });
4119
3571
  }
3572
+ const watchRecorded = () => {
3573
+ try {
3574
+ return api.onRecorded(() => bumpRefresh());
3575
+ } catch {
3576
+ return () => {};
3577
+ }
3578
+ };
4120
3579
  const disposeEvents = [
3580
+ watchRecorded(),
4121
3581
  ctx.data.on("session.step.ended", () => bumpRefresh()),
4122
3582
  ctx.data.on("session.execution.succeeded", () => bumpRefresh()),
4123
3583
  ctx.data.on("session.execution.failed", () => bumpRefresh()),
@@ -4128,14 +3588,18 @@ var tui_default = Plugin.define({
4128
3588
  })
4129
3589
  ];
4130
3590
  __test.line = lineFor;
4131
- __test.lineText = (sessionID) => lineText(lineParts(lineFor(sessionID), {
4132
- labels: options.labels,
4133
- fields: options.fields,
4134
- estimates: pricing
4135
- }));
3591
+ __test.lineText = (sessionID) => {
3592
+ loadListCost(sessionID);
3593
+ return lineText(lineParts(lineFor(sessionID), {
3594
+ labels: options.labels,
3595
+ fields: options.fields,
3596
+ turnTotals: options.turnTotals,
3597
+ estimates: pricing
3598
+ }));
3599
+ };
4136
3600
  __test.open = open;
4137
3601
  __test.state = () => {
4138
- const current = sanitizeSettings(settings);
3602
+ const current = sanitizeSettings(settings, views);
4139
3603
  return {
4140
3604
  view: current.view,
4141
3605
  range: current.range
@@ -4149,7 +3613,6 @@ var tui_default = Plugin.define({
4149
3613
  disposeLine();
4150
3614
  disposePanel();
4151
3615
  disposeSidebar();
4152
- database?.close();
4153
3616
  };
4154
3617
  }
4155
3618
  });
@@ -4158,4 +3621,4 @@ export {
4158
3621
  tui_default as default
4159
3622
  };
4160
3623
 
4161
- //# debugId=A1CD43DA40AD35A864756E2164756E21
3624
+ //# debugId=7F05368FEEAF73BE64756E2164756E21