opencode-usage-insights 0.1.3 → 0.2.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 } 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,
@@ -954,6 +971,28 @@ var PANEL_NAME = "usage-insights";
954
971
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
955
972
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
956
973
  var GRANULARITIES = ["day", "week", "month"];
974
+ var SORT_KEYS = {
975
+ models: ["steps", "cached", "hit", "out", "cost"],
976
+ providers: ["steps", "cached", "hit", "cost", "share", "tps"],
977
+ latency: ["n", "tps", "wall"],
978
+ sessions: ["last", "steps", "cached", "cost"],
979
+ turns: ["time", "cost", "tokens"]
980
+ };
981
+ function sortKeys(view) {
982
+ return SORT_KEYS[view] ?? [];
983
+ }
984
+ function defaultSort(view) {
985
+ return sortKeys(view)[0] ?? "";
986
+ }
987
+ function nextSort(view, current, step) {
988
+ const keys = sortKeys(view);
989
+ if (keys.length === 0)
990
+ return current;
991
+ const index = keys.indexOf(current);
992
+ if (index === -1)
993
+ return keys[0];
994
+ return keys[(index + step + keys.length) % keys.length];
995
+ }
957
996
  function parseArgs(input) {
958
997
  const parsed = {};
959
998
  for (const token of (input ?? "").split(/\s+/)) {
@@ -1170,7 +1209,7 @@ function viewBar(view, width = 200) {
1170
1209
  }
1171
1210
  function keysFor(of) {
1172
1211
  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";
1212
+ return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
1174
1213
  if (of === "periods")
1175
1214
  return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1176
1215
  if (of === "turns")
@@ -1229,8 +1268,8 @@ function helpLines(width) {
1229
1268
  { text: "" },
1230
1269
  { text: "database", tone: HEADER_TONE },
1231
1270
  { 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" },
1271
+ { text: " of it is old: \u2191\u2193 pick a retention or wipe, enter asks before it" },
1272
+ { text: " deletes, e backfills list estimates, v gives the space back" },
1234
1273
  { text: " local time \xB7 SQLite in the OpenCode state directory" }
1235
1274
  ];
1236
1275
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
@@ -1725,10 +1764,14 @@ function dbLines(data, width) {
1725
1764
  });
1726
1765
  lines.push({ text: "", tone: "muted" });
1727
1766
  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" });
1767
+ lines.push({
1768
+ 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),
1769
+ tone: "muted",
1770
+ hint: true
1771
+ });
1729
1772
  if (data.estimates !== false) {
1730
1773
  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),
1774
+ 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
1775
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
1733
1776
  });
1734
1777
  }
@@ -1742,6 +1785,14 @@ function dbLines(data, width) {
1742
1785
  row: { kind: "prune", value: String(option.days) }
1743
1786
  });
1744
1787
  }
1788
+ const steps = data.info.tables.find((table) => table.name === "steps")?.rows ?? 0;
1789
+ const sessions = data.info.tables.find((table) => table.name === "sessions")?.rows ?? 0;
1790
+ lines.push({ text: "", tone: "muted" });
1791
+ lines.push({
1792
+ text: truncate(` wipe everything \xB7 ${formatCount(steps)} steps \xB7 ${formatCount(sessions)} sessions \xB7 cannot be undone`, width),
1793
+ tone: steps === 0 && sessions === 0 ? "muted" : "warning",
1794
+ row: { kind: "wipe", value: "all" }
1795
+ });
1745
1796
  if (data.busy === true) {
1746
1797
  lines.push({ text: "", tone: "muted" });
1747
1798
  lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
@@ -1837,6 +1888,8 @@ function sidebarLines(rows, options) {
1837
1888
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
1838
1889
  const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
1839
1890
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
1891
+ const header = `${clock} ${provider}`;
1892
+ const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
1840
1893
  const volumes = [
1841
1894
  ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
1842
1895
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
@@ -1848,7 +1901,7 @@ function sidebarLines(rows, options) {
1848
1901
  ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
1849
1902
  ` hit ${hit}${suffix}`
1850
1903
  ];
1851
- lines.push({ text: truncate(`${clock} ${provider}`, budget), tone: turn.providerChanged ? "warning" : "base" });
1904
+ lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
1852
1905
  const edge = index === 0 || index === rows.length - 1;
1853
1906
  if (edge || turn.modelChanged || turn.providerChanged) {
1854
1907
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
@@ -1869,1363 +1922,310 @@ function sidebarLines(rows, options) {
1869
1922
  }
1870
1923
 
1871
1924
  // src/panel.tsx
1925
+ import { insert as _$insert } from "@opentui/solid";
1872
1926
  import { effect as _$effect } from "@opentui/solid";
1927
+ import { createTextNode as _$createTextNode } from "@opentui/solid";
1873
1928
  import { insertNode as _$insertNode } from "@opentui/solid";
1874
- import { insert as _$insert } from "@opentui/solid";
1875
1929
  import { createComponent as _$createComponent } from "@opentui/solid";
1876
1930
  import { use as _$use } from "@opentui/solid";
1877
1931
  import { setProp as _$setProp } from "@opentui/solid";
1878
1932
  import { createElement as _$createElement } from "@opentui/solid";
1879
1933
  import { TextAttributes } from "@opentui/core";
1880
- import { For, createMemo, createRenderEffect, createSignal } from "solid-js";
1934
+ import { For, Show, createEffect, createMemo, createRenderEffect, createSignal } from "solid-js";
1881
1935
 
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;
1936
+ // src/rpc.ts
1937
+ import { Rpc } from "@opencode/plugin/rpc";
1938
+ var Tone = { type: "string", enum: ["base", "muted", "warning", "accent"] };
1939
+ var PanelRowSchema = {
1940
+ type: "object",
1941
+ properties: {
1942
+ kind: { type: "string", enum: ["model", "session", "period", "provider", "turn", "prune", "wipe"] },
1943
+ value: { type: "string", maxLength: 500 },
1944
+ variant: { type: "string", maxLength: 200 }
1945
+ },
1946
+ required: ["kind", "value"],
1947
+ additionalProperties: false
1948
+ };
1949
+ var PanelLineSchema = {
1950
+ type: "object",
1951
+ properties: {
1952
+ text: { type: "string" },
1953
+ tone: Tone,
1954
+ hint: { type: "boolean" },
1955
+ row: PanelRowSchema
1956
+ },
1957
+ required: ["text"],
1958
+ additionalProperties: false
1959
+ };
1960
+ var PanelSettingsSchema = {
1961
+ type: "object",
1962
+ properties: {
1963
+ view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"] },
1964
+ range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
1965
+ sort: { type: "string", maxLength: 40 },
1966
+ sortDesc: { type: "boolean" },
1967
+ granularity: { type: "string", enum: ["day", "week", "month"] },
1968
+ turnsScope: { type: "string", enum: ["session", "all"] },
1969
+ modelID: { type: "string", maxLength: 300 },
1970
+ providerID: { type: "string", maxLength: 300 }
1971
+ },
1972
+ required: ["view", "range", "sort", "sortDesc", "granularity", "turnsScope", "modelID", "providerID"],
1973
+ additionalProperties: false
1974
+ };
1975
+ var TableSizeSchema = {
1976
+ type: "object",
1977
+ properties: {
1978
+ name: { type: "string" },
1979
+ rows: { type: "number" }
1980
+ },
1981
+ required: ["name", "rows"],
1982
+ additionalProperties: false
1983
+ };
1984
+ var DbInfoSchema = {
1985
+ type: "object",
1986
+ properties: {
1987
+ path: { type: "string" },
1988
+ bytes: { type: "number" },
1989
+ walBytes: { type: "number" },
1990
+ schemaVersion: { type: "number" },
1991
+ tables: { type: "array", items: TableSizeSchema },
1992
+ firstAt: { type: "number" },
1993
+ lastAt: { type: "number" },
1994
+ removable: {
1995
+ type: "array",
1996
+ items: {
1997
+ type: "object",
1998
+ properties: { days: { type: "number" }, steps: { type: "number" } },
1999
+ required: ["days", "steps"],
2000
+ additionalProperties: false
2125
2001
  }
2126
- }
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
- }
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;
2185
- return {
2186
- buckets,
2187
- providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),
2188
- samples
2189
- };
2190
- }
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]);
2243
- }
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";
2248
- 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
2259
- };
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;
2373
- }
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
2384
- });
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"]
2002
+ },
2003
+ unpriced: { type: "number" }
2004
+ },
2005
+ required: ["path", "bytes", "schemaVersion", "tables", "removable", "unpriced"],
2006
+ additionalProperties: false
2396
2007
  };
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
- }
2500
- });
2501
- }
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 });
2509
- }
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"
2008
+ var FilterOptionSchema = {
2009
+ type: "object",
2010
+ properties: { value: { type: "string" }, steps: { type: "number" } },
2011
+ required: ["value", "steps"],
2012
+ additionalProperties: false
2013
+ };
2014
+ var PruneResultSchema = {
2015
+ type: "object",
2016
+ properties: {
2017
+ steps: { type: "number" },
2018
+ prompts: { type: "number" },
2019
+ events: { type: "number" },
2020
+ usage: { type: "number" }
2021
+ },
2022
+ required: ["steps", "prompts", "events", "usage"],
2023
+ additionalProperties: false
2024
+ };
2025
+ var WipeResultSchema = {
2026
+ type: "object",
2027
+ properties: {
2028
+ steps: { type: "number" },
2029
+ prompts: { type: "number" },
2030
+ events: { type: "number" },
2031
+ usage: { type: "number" },
2032
+ sessions: { type: "number" }
2033
+ },
2034
+ required: ["steps", "prompts", "events", "usage", "sessions"],
2035
+ additionalProperties: false
2036
+ };
2037
+ var BackfillResultSchema = {
2038
+ type: "object",
2039
+ properties: {
2040
+ candidates: { type: "number" },
2041
+ updated: { type: "number" }
2042
+ },
2043
+ required: ["candidates", "updated"],
2044
+ additionalProperties: false
2045
+ };
2046
+ var VacuumResultSchema = {
2047
+ type: "object",
2048
+ properties: {
2049
+ before: { type: "number" },
2050
+ after: { type: "number" },
2051
+ freed: { type: "number" }
2052
+ },
2053
+ required: ["before", "after", "freed"],
2054
+ additionalProperties: false
2055
+ };
2056
+ var NoInput = { type: "object", properties: {}, additionalProperties: false };
2057
+ var ErrorSchema = {
2058
+ type: "object",
2059
+ properties: { message: { type: "string", maxLength: 500 } },
2060
+ additionalProperties: false
2061
+ };
2062
+ var errors = {
2063
+ busy: ErrorSchema,
2064
+ unavailable: ErrorSchema,
2065
+ disabled: ErrorSchema,
2066
+ invalid: ErrorSchema
2067
+ };
2068
+ var UsageInsights = Rpc.define({
2069
+ id: "usage-insights",
2070
+ methods: {
2071
+ panel: {
2072
+ input: {
2073
+ type: "object",
2074
+ properties: {
2075
+ sessionID: { type: "string", maxLength: 200 },
2076
+ settings: PanelSettingsSchema,
2077
+ detail: PanelRowSchema,
2078
+ width: { type: "number", minimum: 20, maximum: MAX_PANEL_WIDTH },
2079
+ busy: { type: "boolean" }
2080
+ },
2081
+ required: ["sessionID", "settings", "width"],
2082
+ additionalProperties: false
2542
2083
  },
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"
2084
+ output: {
2085
+ type: "object",
2086
+ properties: {
2087
+ lines: { type: "array", items: PanelLineSchema },
2088
+ database: DbInfoSchema
2089
+ },
2090
+ required: ["lines"],
2091
+ additionalProperties: false
2564
2092
  },
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;
2093
+ errors
2094
+ },
2095
+ turns: {
2096
+ input: {
2097
+ type: "object",
2098
+ properties: {
2099
+ sessionID: { type: "string", maxLength: 200 },
2100
+ limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
2101
+ width: { type: "number", minimum: 20, maximum: 120 }
2102
+ },
2103
+ required: ["sessionID", "limit", "width"],
2104
+ additionalProperties: false
2105
+ },
2106
+ output: {
2107
+ type: "object",
2108
+ properties: {
2109
+ summary: { type: "array", items: PanelLineSchema },
2110
+ history: { type: "array", items: PanelLineSchema }
2111
+ },
2112
+ required: ["summary", "history"],
2113
+ additionalProperties: false
2114
+ },
2115
+ errors
2116
+ },
2117
+ listCost: {
2118
+ input: {
2119
+ type: "object",
2120
+ properties: { sessionID: { type: "string", maxLength: 200 } },
2121
+ required: ["sessionID"],
2122
+ additionalProperties: false
2123
+ },
2124
+ output: {
2125
+ type: "object",
2126
+ properties: { cost: { type: "number" } },
2127
+ required: ["cost"],
2128
+ additionalProperties: false
2129
+ },
2130
+ errors
2131
+ },
2132
+ filters: {
2133
+ input: NoInput,
2134
+ output: {
2135
+ type: "object",
2136
+ properties: {
2137
+ models: { type: "array", items: FilterOptionSchema },
2138
+ providers: { type: "array", items: FilterOptionSchema }
2139
+ },
2140
+ required: ["models", "providers"],
2141
+ additionalProperties: false
2142
+ },
2143
+ errors
2144
+ },
2145
+ dbInfo: {
2146
+ input: NoInput,
2147
+ output: DbInfoSchema,
2148
+ errors
2149
+ },
2150
+ prune: {
2151
+ input: {
2152
+ type: "object",
2153
+ properties: {
2154
+ days: { type: "number", minimum: 1, maximum: 3650 },
2155
+ confirm: { type: "boolean", enum: [true] }
2156
+ },
2157
+ required: ["days", "confirm"],
2158
+ additionalProperties: false
2159
+ },
2160
+ output: PruneResultSchema,
2161
+ errors
2162
+ },
2163
+ wipe: {
2164
+ input: {
2165
+ type: "object",
2166
+ properties: { confirm: { type: "boolean", enum: [true] } },
2167
+ required: ["confirm"],
2168
+ additionalProperties: false
2169
+ },
2170
+ output: WipeResultSchema,
2171
+ errors
2172
+ },
2173
+ vacuum: {
2174
+ input: {
2175
+ type: "object",
2176
+ properties: { confirm: { type: "boolean", enum: [true] } },
2177
+ required: ["confirm"],
2178
+ additionalProperties: false
2179
+ },
2180
+ output: VacuumResultSchema,
2181
+ errors
2182
+ },
2183
+ backfill: {
2184
+ input: {
2185
+ type: "object",
2186
+ properties: { confirm: { type: "boolean", enum: [true] } },
2187
+ required: ["confirm"],
2188
+ additionalProperties: false
2189
+ },
2190
+ output: BackfillResultSchema,
2191
+ errors
2192
+ }
2193
+ },
2194
+ events: {
2195
+ recorded: {
2196
+ schema: {
2197
+ type: "object",
2198
+ properties: {
2199
+ sessionID: { type: "string", maxLength: 200 },
2200
+ at: { type: "number" }
2201
+ },
2202
+ required: ["at"],
2203
+ additionalProperties: false
2204
+ }
2601
2205
  }
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
2206
  }
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);
2207
+ });
2811
2208
 
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)
2209
+ // src/rpc-client.ts
2210
+ function usageApi(client, location) {
2211
+ const rpc = client.rpc(UsageInsights);
2212
+ const options = (signal) => ({
2213
+ ...location !== undefined && location.directory !== undefined ? { location: { directory: location.directory } } : {},
2214
+ ...signal !== undefined ? { signal } : {}
3062
2215
  });
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
2216
  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
2217
+ panel: (input, signal) => rpc.panel(input, options(signal)),
2218
+ turns: (input, signal) => rpc.turns(input, options(signal)),
2219
+ listCost: (input, signal) => rpc.listCost(input, options(signal)),
2220
+ filters: (signal) => rpc.filters({}, options(signal)),
2221
+ dbInfo: (signal) => rpc.dbInfo({}, options(signal)),
2222
+ prune: (input, signal) => rpc.prune(input, options(signal)),
2223
+ wipe: (input, signal) => rpc.wipe(input, options(signal)),
2224
+ vacuum: (input, signal) => rpc.vacuum(input, options(signal)),
2225
+ backfill: (input, signal) => rpc.backfill(input, options(signal)),
2226
+ onRecorded: (handler, signal) => rpc.events.on("recorded", (event) => handler(event.data), signal === undefined ? undefined : { signal })
3162
2227
  };
3163
2228
  }
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
2229
 
3230
2230
  // src/panel.tsx
3231
2231
  function Panel(props) {
@@ -3234,71 +2234,77 @@ function Panel(props) {
3234
2234
  const [help, setHelp] = createSignal(false);
3235
2235
  const [tick, setTick] = createSignal(0);
3236
2236
  const [busy, setBusy] = createSignal(false);
2237
+ const [lines, setLines] = createSignal([]);
2238
+ const [database, setDatabase] = createSignal(undefined);
2239
+ const [loading, setLoading] = createSignal(false);
2240
+ const [error, setError] = createSignal(undefined);
2241
+ let generation = 0;
3237
2242
  let scroller;
3238
- const width = () => Math.max(60, props.input.width - 4);
2243
+ const width = () => clampPanelWidth(Math.max(60, props.input.width - 4));
3239
2244
  const view = () => sanitizeSettings(props.settings).view;
3240
2245
  const settings = () => sanitizeSettings(props.settings);
3241
- const filters = () => {
2246
+ const api = () => usageApi(props.ctx.client, props.ctx.location);
2247
+ function errorMessage(cause) {
2248
+ if (cause instanceof Error)
2249
+ return cause.message;
2250
+ if (cause !== null && typeof cause === "object" && "message" in cause)
2251
+ return String(cause.message);
2252
+ return "usage service unavailable";
2253
+ }
2254
+ const rowKey = (row) => `${row.kind}:${row.value}${row.variant !== undefined ? `#${row.variant}` : ""}`;
2255
+ const request = createMemo(() => {
2256
+ tick();
2257
+ props.deps.refresh?.();
2258
+ if (help())
2259
+ return;
3242
2260
  const current = settings();
3243
2261
  return {
3244
- ...current.modelID !== "" ? {
3245
- modelID: current.modelID
2262
+ sessionID: props.input.sessionID,
2263
+ settings: current,
2264
+ ...detail() !== undefined ? {
2265
+ detail: detail()
3246
2266
  } : {},
3247
- ...current.providerID !== "" ? {
3248
- provider: current.providerID
3249
- } : {}
2267
+ width: width(),
2268
+ busy: busy()
3250
2269
  };
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 {
2270
+ });
2271
+ createEffect(() => {
2272
+ const input = request();
2273
+ const current = ++generation;
2274
+ if (input === undefined) {
2275
+ setLines(helpLines(width()));
2276
+ setDatabase(undefined);
2277
+ setError(undefined);
2278
+ setLoading(false);
3261
2279
  return;
3262
2280
  }
2281
+ setLoading(true);
2282
+ api().panel(input).then((result) => {
2283
+ if (current !== generation)
2284
+ return;
2285
+ setLines(result.lines);
2286
+ setDatabase(result.database);
2287
+ setError(undefined);
2288
+ }).catch((cause) => {
2289
+ if (current !== generation)
2290
+ return;
2291
+ setError(errorMessage(cause));
2292
+ if (lines().length === 0)
2293
+ setLines([]);
2294
+ }).finally(() => {
2295
+ if (current === generation)
2296
+ setLoading(false);
2297
+ });
3263
2298
  });
3264
2299
  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) {
2300
+ if (error() !== undefined && lines().length === 0) {
3272
2301
  return [{
3273
- text: `stats database is not readable at ${props.deps.dbPath()}; enable the usage-insights server plugin in opencode.json`,
2302
+ text: `usage service unavailable: ${error()}`,
3274
2303
  tone: "warning"
3275
2304
  }];
3276
2305
  }
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);
2306
+ const visible = (line) => props.maintenance !== false || line.row?.kind !== "prune" && line.row?.kind !== "wipe";
2307
+ return lines().filter(visible);
3302
2308
  });
3303
2309
  const header = createMemo(() => {
3304
2310
  const current = settings();
@@ -3365,6 +2371,10 @@ function Panel(props) {
3365
2371
  prune(Number.parseInt(entry.row.value, 10));
3366
2372
  return;
3367
2373
  }
2374
+ if (entry.row.kind === "wipe") {
2375
+ wipe();
2376
+ return;
2377
+ }
3368
2378
  setDetail(entry.row);
3369
2379
  setAnchor(undefined);
3370
2380
  }
@@ -3376,6 +2386,13 @@ function Panel(props) {
3376
2386
  }
3377
2387
  }
3378
2388
  async function prune(days) {
2389
+ if (props.maintenance === false) {
2390
+ props.ctx.ui.toast.show({
2391
+ message: "database maintenance is disabled",
2392
+ variant: "warning"
2393
+ });
2394
+ return;
2395
+ }
3379
2396
  if (!Number.isFinite(days))
3380
2397
  return;
3381
2398
  if (sessionRunning()) {
@@ -3397,27 +2414,75 @@ function Panel(props) {
3397
2414
  });
3398
2415
  if (confirmed !== true)
3399
2416
  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) {
2417
+ try {
2418
+ const result = await api().prune({
2419
+ days,
2420
+ confirm: true
2421
+ });
2422
+ props.ctx.ui.toast.show({
2423
+ message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
2424
+ variant: "success"
2425
+ });
2426
+ } catch (cause) {
3403
2427
  props.ctx.ui.toast.show({
3404
- message: "the recorder is writing: try again in a moment",
2428
+ message: errorMessage(cause),
3405
2429
  variant: "warning"
3406
2430
  });
3407
- } else {
2431
+ }
2432
+ setAnchor(undefined);
2433
+ setTick((value) => value + 1);
2434
+ props.deps.bump?.();
2435
+ }
2436
+ async function wipe() {
2437
+ if (props.maintenance === false) {
3408
2438
  props.ctx.ui.toast.show({
3409
- message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
2439
+ message: "database maintenance is disabled",
2440
+ variant: "warning"
2441
+ });
2442
+ return;
2443
+ }
2444
+ if (sessionRunning()) {
2445
+ props.ctx.ui.toast.show({
2446
+ message: "the session is running: wipe again when it is idle",
2447
+ variant: "warning"
2448
+ });
2449
+ return;
2450
+ }
2451
+ const info = database();
2452
+ const steps = info?.tables.find((table) => table.name === "steps")?.rows ?? 0;
2453
+ const sessions = info?.tables.find((table) => table.name === "sessions")?.rows ?? 0;
2454
+ const confirmed = await props.ctx.ui.dialog.confirm({
2455
+ title: "Wipe all recorded usage",
2456
+ message: `${formatCount(steps)} steps and ${formatCount(sessions)} sessions would be deleted, with their prompts, compactions and other usage. This cannot be undone.`,
2457
+ label: {
2458
+ confirm: "Wipe",
2459
+ cancel: "Keep"
2460
+ }
2461
+ });
2462
+ if (confirmed !== true)
2463
+ return;
2464
+ try {
2465
+ const result = await api().wipe({
2466
+ confirm: true
2467
+ });
2468
+ props.ctx.ui.toast.show({
2469
+ message: `wiped ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage \xB7 ${result.sessions} sessions`,
3410
2470
  variant: "success"
3411
2471
  });
2472
+ } catch (cause) {
2473
+ props.ctx.ui.toast.show({
2474
+ message: errorMessage(cause),
2475
+ variant: "warning"
2476
+ });
3412
2477
  }
3413
2478
  setAnchor(undefined);
3414
2479
  setTick((value) => value + 1);
3415
2480
  props.deps.bump?.();
3416
2481
  }
3417
2482
  async function backfillEstimates() {
3418
- if (props.format?.estimates === false) {
2483
+ if (props.maintenance === false) {
3419
2484
  props.ctx.ui.toast.show({
3420
- message: "list-price estimates are turned off",
2485
+ message: "database maintenance is disabled",
3421
2486
  variant: "warning"
3422
2487
  });
3423
2488
  return;
@@ -3438,7 +2503,7 @@ function Panel(props) {
3438
2503
  return;
3439
2504
  }
3440
2505
  const candidates = info?.unpriced ?? 0;
3441
- if (candidates === 0) {
2506
+ if (info !== undefined && candidates === 0) {
3442
2507
  props.ctx.ui.toast.show({
3443
2508
  message: "every $0 step already has a list estimate"
3444
2509
  });
@@ -3454,22 +2519,31 @@ function Panel(props) {
3454
2519
  });
3455
2520
  if (confirmed !== true)
3456
2521
  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"
2522
+ try {
2523
+ const result = await api().backfill({
2524
+ confirm: true
3462
2525
  });
3463
- } else {
3464
2526
  props.ctx.ui.toast.show({
3465
2527
  message: `backfilled ${formatCount(result.updated)} of ${formatCount(result.candidates)} steps`,
3466
2528
  variant: result.updated === 0 ? "warning" : "success"
3467
2529
  });
2530
+ } catch (cause) {
2531
+ props.ctx.ui.toast.show({
2532
+ message: errorMessage(cause),
2533
+ variant: "warning"
2534
+ });
3468
2535
  }
3469
2536
  setTick((value) => value + 1);
3470
2537
  props.deps.bump?.();
3471
2538
  }
3472
2539
  async function compact() {
2540
+ if (props.maintenance === false) {
2541
+ props.ctx.ui.toast.show({
2542
+ message: "database maintenance is disabled",
2543
+ variant: "warning"
2544
+ });
2545
+ return;
2546
+ }
3473
2547
  if (sessionRunning()) {
3474
2548
  props.ctx.ui.toast.show({
3475
2549
  message: "the session is running: compact again when it is idle",
@@ -3487,25 +2561,21 @@ function Panel(props) {
3487
2561
  });
3488
2562
  if (confirmed !== true)
3489
2563
  return;
3490
- const path = props.deps.dbPath();
3491
- let result;
3492
2564
  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"
2565
+ const result = await api().vacuum({
2566
+ confirm: true
3502
2567
  });
3503
- } else {
3504
2568
  setBusy(false);
3505
2569
  props.ctx.ui.toast.show({
3506
2570
  message: `compacted: ${(result.freed / 1048576).toFixed(1)} MB back`,
3507
2571
  variant: "success"
3508
2572
  });
2573
+ } catch (cause) {
2574
+ setBusy(true);
2575
+ props.ctx.ui.toast.show({
2576
+ message: errorMessage(cause),
2577
+ variant: "warning"
2578
+ });
3509
2579
  }
3510
2580
  setTick((value) => value + 1);
3511
2581
  }
@@ -3516,10 +2586,16 @@ function Panel(props) {
3516
2586
  setAnchor(undefined);
3517
2587
  }
3518
2588
  async function pickFilter(kind) {
3519
- const db = props.deps.db();
3520
- if (db === undefined)
2589
+ let all;
2590
+ try {
2591
+ all = await api().filters();
2592
+ } catch (cause) {
2593
+ props.ctx.ui.toast.show({
2594
+ message: errorMessage(cause),
2595
+ variant: "warning"
2596
+ });
3521
2597
  return;
3522
- const all = filterOptions(db);
2598
+ }
3523
2599
  const list = kind === "model" ? all.models : all.providers;
3524
2600
  const current = settings();
3525
2601
  const selected = kind === "model" ? current.modelID : current.providerID;
@@ -3612,13 +2688,13 @@ function Panel(props) {
3612
2688
  const selectedBackground = () => props.ctx.theme.background.raised.high;
3613
2689
  const cursorIndex = () => cursor();
3614
2690
  return (() => {
3615
- var _el$ = _$createElement("box"), _el$2 = _$createElement("scrollbox"), _el$3 = _$createElement("text"), _el$4 = _$createElement("text");
2691
+ var _el$ = _$createElement("box"), _el$2 = _$createElement("scrollbox"), _el$5 = _$createElement("text"), _el$6 = _$createElement("text");
3616
2692
  _$insertNode(_el$, _el$2);
3617
2693
  _$setProp(_el$, "flexDirection", "column");
3618
2694
  _$setProp(_el$, "paddingLeft", 1);
3619
2695
  _$setProp(_el$, "paddingRight", 1);
3620
- _$insertNode(_el$2, _el$3);
3621
- _$insertNode(_el$2, _el$4);
2696
+ _$insertNode(_el$2, _el$5);
2697
+ _$insertNode(_el$2, _el$6);
3622
2698
  _$use((target) => {
3623
2699
  scroller = target;
3624
2700
  const focusable = target;
@@ -3635,12 +2711,12 @@ function Panel(props) {
3635
2711
  return header();
3636
2712
  },
3637
2713
  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;
2714
+ var _el$7 = _$createElement("text");
2715
+ _$insert(_el$7, () => line.text);
2716
+ _$effect((_$p) => _$setProp(_el$7, "fg", color(line.tone), _$p));
2717
+ return _el$7;
3642
2718
  })()
3643
- }), _el$3);
2719
+ }), _el$5);
3644
2720
  _$insert(_el$2, _$createComponent(For, {
3645
2721
  get each() {
3646
2722
  return content();
@@ -3648,14 +2724,14 @@ function Panel(props) {
3648
2724
  children: (line, index) => {
3649
2725
  const selected = () => index() === selectedLineIndex(content(), cursorIndex());
3650
2726
  return (() => {
3651
- var _el$6 = _$createElement("text");
3652
- _$insert(_el$6, () => line.text);
2727
+ var _el$8 = _$createElement("text");
2728
+ _$insert(_el$8, () => line.text);
3653
2729
  _$effect((_p$) => {
3654
2730
  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));
2731
+ _v$3 !== _p$.e && (_p$.e = _$setProp(_el$8, "id", _v$3, _p$.e));
2732
+ _v$4 !== _p$.t && (_p$.t = _$setProp(_el$8, "fg", _v$4, _p$.t));
2733
+ _v$5 !== _p$.a && (_p$.a = _$setProp(_el$8, "bg", _v$5, _p$.a));
2734
+ _v$6 !== _p$.o && (_p$.o = _$setProp(_el$8, "attributes", _v$6, _p$.o));
3659
2735
  return _p$;
3660
2736
  }, {
3661
2737
  e: undefined,
@@ -3663,15 +2739,26 @@ function Panel(props) {
3663
2739
  a: undefined,
3664
2740
  o: undefined
3665
2741
  });
3666
- return _el$6;
2742
+ return _el$8;
3667
2743
  })();
3668
2744
  }
3669
- }), _el$3);
3670
- _$insert(_el$4, () => keysFor(view()));
2745
+ }), _el$5);
2746
+ _$insert(_el$2, _$createComponent(Show, {
2747
+ get when() {
2748
+ return loading();
2749
+ },
2750
+ get children() {
2751
+ var _el$3 = _$createElement("text");
2752
+ _$insertNode(_el$3, _$createTextNode(`loading\u2026`));
2753
+ _$effect((_$p) => _$setProp(_el$3, "fg", props.ctx.theme.text.muted, _$p));
2754
+ return _el$3;
2755
+ }
2756
+ }), _el$5);
2757
+ _$insert(_el$6, () => keysFor(view()));
3671
2758
  _$effect((_p$) => {
3672
2759
  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));
2760
+ _v$ !== _p$.e && (_p$.e = _$setProp(_el$5, "fg", _v$, _p$.e));
2761
+ _v$2 !== _p$.t && (_p$.t = _$setProp(_el$6, "fg", _v$2, _p$.t));
3675
2762
  return _p$;
3676
2763
  }, {
3677
2764
  e: undefined,
@@ -3767,12 +2854,15 @@ function costOf(table, ref, usage) {
3767
2854
  }
3768
2855
 
3769
2856
  // src/sidebar.tsx
3770
- import { effect as _$effect2 } from "@opentui/solid";
3771
2857
  import { insert as _$insert2 } from "@opentui/solid";
2858
+ import { effect as _$effect2 } from "@opentui/solid";
2859
+ import { createTextNode as _$createTextNode2 } from "@opentui/solid";
2860
+ import { insertNode as _$insertNode2 } from "@opentui/solid";
2861
+ import { memo as _$memo } from "@opentui/solid";
3772
2862
  import { createComponent as _$createComponent2 } from "@opentui/solid";
3773
2863
  import { setProp as _$setProp2 } from "@opentui/solid";
3774
2864
  import { createElement as _$createElement2 } from "@opentui/solid";
3775
- import { For as For2, createMemo as createMemo2 } from "solid-js";
2865
+ import { For as For2, Show as Show2, createEffect as createEffect2, createMemo as createMemo2, createSignal as createSignal2, onCleanup } from "solid-js";
3776
2866
  function TurnsSidebar(props) {
3777
2867
  const color = (tone) => {
3778
2868
  switch (tone) {
@@ -3786,30 +2876,49 @@ function TurnsSidebar(props) {
3786
2876
  return props.ctx.theme.text.base;
3787
2877
  }
3788
2878
  };
3789
- const lines = createMemo2(() => {
2879
+ const [data, setData] = createSignal2(undefined);
2880
+ const [error, setError] = createSignal2(undefined);
2881
+ const [loading, setLoading] = createSignal2(false);
2882
+ let generation = 0;
2883
+ createEffect2(() => {
3790
2884
  props.deps.refresh();
3791
- const db = props.deps.db();
3792
- if (db === undefined)
3793
- return [];
3794
- 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 {
2885
+ const input = {
2886
+ sessionID: props.sessionID,
2887
+ limit: props.deps.limit,
2888
+ width: props.deps.budget ?? 34
2889
+ };
2890
+ const current = ++generation;
2891
+ const controller = new AbortController;
2892
+ onCleanup(() => controller.abort());
2893
+ setLoading(true);
2894
+ usageApi(props.ctx.client, props.ctx.location).turns(input, controller.signal).then((result) => {
2895
+ if (current !== generation)
2896
+ return;
2897
+ setData(result);
2898
+ setError(undefined);
2899
+ }).catch((cause) => {
2900
+ if (current !== generation)
2901
+ return;
2902
+ setError(cause);
2903
+ }).finally(() => {
2904
+ if (current === generation)
2905
+ setLoading(false);
2906
+ });
2907
+ });
2908
+ const lines = createMemo2(() => {
2909
+ const result = data();
2910
+ if (result === undefined) {
2911
+ if (error() !== undefined)
2912
+ return [{
2913
+ text: "usage history unavailable",
2914
+ tone: "muted"
2915
+ }];
3811
2916
  return [];
3812
2917
  }
2918
+ return [...result.summary, {
2919
+ text: "turns",
2920
+ tone: "accent"
2921
+ }, ...result.history];
3813
2922
  });
3814
2923
  return (() => {
3815
2924
  var _el$ = _$createElement2("box");
@@ -3821,12 +2930,23 @@ function TurnsSidebar(props) {
3821
2930
  return lines();
3822
2931
  },
3823
2932
  children: (line) => (() => {
2933
+ var _el$4 = _$createElement2("text");
2934
+ _$insert2(_el$4, () => line.text);
2935
+ _$effect2((_$p) => _$setProp2(_el$4, "fg", color(line.tone), _$p));
2936
+ return _el$4;
2937
+ })()
2938
+ }), null);
2939
+ _$insert2(_el$, _$createComponent2(Show2, {
2940
+ get when() {
2941
+ return _$memo(() => !!loading())() && data() !== undefined;
2942
+ },
2943
+ get children() {
3824
2944
  var _el$2 = _$createElement2("text");
3825
- _$insert2(_el$2, () => line.text);
3826
- _$effect2((_$p) => _$setProp2(_el$2, "fg", color(line.tone), _$p));
2945
+ _$insertNode2(_el$2, _$createTextNode2(`\u2026`));
2946
+ _$effect2((_$p) => _$setProp2(_el$2, "fg", props.ctx.theme.text.muted, _$p));
3827
2947
  return _el$2;
3828
- })()
3829
- }));
2948
+ }
2949
+ }), null);
3830
2950
  return _el$;
3831
2951
  })();
3832
2952
  }
@@ -3877,14 +2997,14 @@ var tui_default = Plugin.define({
3877
2997
  const patchSettings = (mutation) => {
3878
2998
  updateSettings(mutation);
3879
2999
  };
3880
- const [refresh, setRefresh] = createSignal2(0);
3881
- let database;
3882
- let databaseFailed = false;
3000
+ const [refresh, setRefresh] = createSignal3(0);
3001
+ const [listCosts, setListCosts] = createSignal3({});
3002
+ const pendingListCost = new Set;
3003
+ const dirtyListCost = new Set;
3004
+ const api = usageApi(ctx.client, ctx.location);
3883
3005
  let refreshTimer;
3884
3006
  let lastRefresh = 0;
3885
- const sessionCostCache = new Map;
3886
3007
  function bumpRefresh() {
3887
- sessionCostCache.clear();
3888
3008
  const now = Date.now();
3889
3009
  const wait = lastRefresh + REFRESH_THROTTLE_MS - now;
3890
3010
  if (wait <= 0) {
@@ -3901,62 +3021,39 @@ var tui_default = Plugin.define({
3901
3021
  }, wait);
3902
3022
  refreshTimer.unref?.();
3903
3023
  }
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) {
3024
+ function listCostFor(sessionID) {
3918
3025
  if (!pricing)
3919
3026
  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
- }
3027
+ return listCosts()[sessionID] ?? 0;
3938
3028
  }
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() {
3029
+ async function loadListCost(sessionID) {
3951
3030
  if (!pricing)
3952
3031
  return;
3953
- const table = priceTableFor();
3954
- if (table === undefined)
3032
+ if (pendingListCost.has(sessionID)) {
3033
+ dirtyListCost.add(sessionID);
3955
3034
  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;
3035
+ }
3036
+ pendingListCost.add(sessionID);
3037
+ try {
3038
+ const result = await api.listCost({
3039
+ sessionID
3040
+ });
3041
+ setListCosts((current) => {
3042
+ const next = {
3043
+ ...current,
3044
+ [sessionID]: result.cost
3045
+ };
3046
+ const keys = Object.keys(next);
3047
+ if (keys.length > 512)
3048
+ for (const key of keys.slice(0, keys.length - 512))
3049
+ delete next[key];
3050
+ return next;
3051
+ });
3052
+ } catch {} finally {
3053
+ pendingListCost.delete(sessionID);
3054
+ if (dirtyListCost.delete(sessionID))
3055
+ loadListCost(sessionID);
3056
+ }
3960
3057
  }
3961
3058
  function sessionIdle(sessionID) {
3962
3059
  try {
@@ -3972,7 +3069,7 @@ var tui_default = Plugin.define({
3972
3069
  refresh();
3973
3070
  const messages = ctx.data.session.message.list(sessionID);
3974
3071
  const info = ctx.data.session.get(sessionID);
3975
- const session = info === undefined ? undefined : sessionTotals(info, sessionListCostFor(sessionID));
3072
+ const session = info === undefined ? undefined : sessionTotals(info, listCostFor(sessionID));
3976
3073
  return computeTurn(toTranscriptTail(messages, 2, priceFor()), session);
3977
3074
  }
3978
3075
  function toneColor(tone) {
@@ -3989,7 +3086,12 @@ var tui_default = Plugin.define({
3989
3086
  turnTotals: options.turnTotals,
3990
3087
  estimates: pricing
3991
3088
  }));
3992
- return _$createComponent3(Show, {
3089
+ createEffect3(() => {
3090
+ props.sessionID;
3091
+ refresh();
3092
+ loadListCost(props.sessionID);
3093
+ });
3094
+ return _$createComponent3(Show3, {
3993
3095
  get when() {
3994
3096
  return parts().length > 0;
3995
3097
  },
@@ -4027,24 +3129,13 @@ var tui_default = Plugin.define({
4027
3129
  input,
4028
3130
  ctx,
4029
3131
  deps: {
4030
- db,
4031
- dbPath: () => resolveDbPath(options.db),
4032
- withWrite,
4033
- backfill,
4034
- now: () => Date.now(),
4035
- sessionStart,
4036
3132
  refresh,
4037
3133
  bump: bumpRefresh
4038
3134
  },
4039
3135
  settings,
4040
3136
  update: patchSettings,
4041
- get format() {
4042
- return {
4043
- labels: options.labels,
4044
- fields: options.fields,
4045
- turnTotals: options.turnTotals,
4046
- estimates: pricing
4047
- };
3137
+ get maintenance() {
3138
+ return options.maintenance !== false;
4048
3139
  }
4049
3140
  }) : null
4050
3141
  }) : () => {};
@@ -4057,17 +3148,8 @@ var tui_default = Plugin.define({
4057
3148
  ctx,
4058
3149
  get deps() {
4059
3150
  return {
4060
- db,
4061
3151
  refresh,
4062
- limit: Math.max(1, Math.round(options.sidebarTurns ?? 8))
4063
- };
4064
- },
4065
- get options() {
4066
- return {
4067
- labels: options.labels,
4068
- fields: options.fields,
4069
- turnTotals: options.turnTotals,
4070
- estimates: pricing
3152
+ limit: clampTurnsLimit(options.sidebarTurns ?? 8)
4071
3153
  };
4072
3154
  }
4073
3155
  })
@@ -4117,7 +3199,15 @@ var tui_default = Plugin.define({
4117
3199
  };
4118
3200
  });
4119
3201
  }
3202
+ const watchRecorded = () => {
3203
+ try {
3204
+ return api.onRecorded(() => bumpRefresh());
3205
+ } catch {
3206
+ return () => {};
3207
+ }
3208
+ };
4120
3209
  const disposeEvents = [
3210
+ watchRecorded(),
4121
3211
  ctx.data.on("session.step.ended", () => bumpRefresh()),
4122
3212
  ctx.data.on("session.execution.succeeded", () => bumpRefresh()),
4123
3213
  ctx.data.on("session.execution.failed", () => bumpRefresh()),
@@ -4128,11 +3218,15 @@ var tui_default = Plugin.define({
4128
3218
  })
4129
3219
  ];
4130
3220
  __test.line = lineFor;
4131
- __test.lineText = (sessionID) => lineText(lineParts(lineFor(sessionID), {
4132
- labels: options.labels,
4133
- fields: options.fields,
4134
- estimates: pricing
4135
- }));
3221
+ __test.lineText = (sessionID) => {
3222
+ loadListCost(sessionID);
3223
+ return lineText(lineParts(lineFor(sessionID), {
3224
+ labels: options.labels,
3225
+ fields: options.fields,
3226
+ turnTotals: options.turnTotals,
3227
+ estimates: pricing
3228
+ }));
3229
+ };
4136
3230
  __test.open = open;
4137
3231
  __test.state = () => {
4138
3232
  const current = sanitizeSettings(settings);
@@ -4149,7 +3243,6 @@ var tui_default = Plugin.define({
4149
3243
  disposeLine();
4150
3244
  disposePanel();
4151
3245
  disposeSidebar();
4152
- database?.close();
4153
3246
  };
4154
3247
  }
4155
3248
  });
@@ -4158,4 +3251,4 @@ export {
4158
3251
  tui_default as default
4159
3252
  };
4160
3253
 
4161
- //# debugId=A1CD43DA40AD35A864756E2164756E21
3254
+ //# debugId=3E4F6620631DC12564756E2164756E21