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/index.js CHANGED
@@ -2,6 +2,295 @@
2
2
  // src/index.ts
3
3
  import { Plugin } from "@opencode/plugin";
4
4
 
5
+ // src/rpc.ts
6
+ import { Rpc } from "@opencode/plugin/rpc";
7
+
8
+ // src/limits.ts
9
+ var MAX_PANEL_WIDTH = 200;
10
+ var MAX_TURNS = 50;
11
+ function clampPanelWidth(value) {
12
+ if (!Number.isFinite(value))
13
+ return 20;
14
+ return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
15
+ }
16
+ function clampTurnsLimit(value) {
17
+ if (!Number.isFinite(value))
18
+ return 1;
19
+ return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
20
+ }
21
+
22
+ // src/rpc.ts
23
+ var Tone = { type: "string", enum: ["base", "muted", "warning", "accent"] };
24
+ var PanelRowSchema = {
25
+ type: "object",
26
+ properties: {
27
+ kind: { type: "string", enum: ["model", "session", "period", "provider", "turn", "prune", "wipe"] },
28
+ value: { type: "string", maxLength: 500 },
29
+ variant: { type: "string", maxLength: 200 }
30
+ },
31
+ required: ["kind", "value"],
32
+ additionalProperties: false
33
+ };
34
+ var PanelLineSchema = {
35
+ type: "object",
36
+ properties: {
37
+ text: { type: "string" },
38
+ tone: Tone,
39
+ hint: { type: "boolean" },
40
+ row: PanelRowSchema
41
+ },
42
+ required: ["text"],
43
+ additionalProperties: false
44
+ };
45
+ var PanelSettingsSchema = {
46
+ type: "object",
47
+ properties: {
48
+ view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"] },
49
+ range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
50
+ sort: { type: "string", maxLength: 40 },
51
+ sortDesc: { type: "boolean" },
52
+ granularity: { type: "string", enum: ["day", "week", "month"] },
53
+ turnsScope: { type: "string", enum: ["session", "all"] },
54
+ modelID: { type: "string", maxLength: 300 },
55
+ providerID: { type: "string", maxLength: 300 }
56
+ },
57
+ required: ["view", "range", "sort", "sortDesc", "granularity", "turnsScope", "modelID", "providerID"],
58
+ additionalProperties: false
59
+ };
60
+ var TableSizeSchema = {
61
+ type: "object",
62
+ properties: {
63
+ name: { type: "string" },
64
+ rows: { type: "number" }
65
+ },
66
+ required: ["name", "rows"],
67
+ additionalProperties: false
68
+ };
69
+ var DbInfoSchema = {
70
+ type: "object",
71
+ properties: {
72
+ path: { type: "string" },
73
+ bytes: { type: "number" },
74
+ walBytes: { type: "number" },
75
+ schemaVersion: { type: "number" },
76
+ tables: { type: "array", items: TableSizeSchema },
77
+ firstAt: { type: "number" },
78
+ lastAt: { type: "number" },
79
+ removable: {
80
+ type: "array",
81
+ items: {
82
+ type: "object",
83
+ properties: { days: { type: "number" }, steps: { type: "number" } },
84
+ required: ["days", "steps"],
85
+ additionalProperties: false
86
+ }
87
+ },
88
+ unpriced: { type: "number" }
89
+ },
90
+ required: ["path", "bytes", "schemaVersion", "tables", "removable", "unpriced"],
91
+ additionalProperties: false
92
+ };
93
+ var FilterOptionSchema = {
94
+ type: "object",
95
+ properties: { value: { type: "string" }, steps: { type: "number" } },
96
+ required: ["value", "steps"],
97
+ additionalProperties: false
98
+ };
99
+ var PruneResultSchema = {
100
+ type: "object",
101
+ properties: {
102
+ steps: { type: "number" },
103
+ prompts: { type: "number" },
104
+ events: { type: "number" },
105
+ usage: { type: "number" }
106
+ },
107
+ required: ["steps", "prompts", "events", "usage"],
108
+ additionalProperties: false
109
+ };
110
+ var WipeResultSchema = {
111
+ type: "object",
112
+ properties: {
113
+ steps: { type: "number" },
114
+ prompts: { type: "number" },
115
+ events: { type: "number" },
116
+ usage: { type: "number" },
117
+ sessions: { type: "number" }
118
+ },
119
+ required: ["steps", "prompts", "events", "usage", "sessions"],
120
+ additionalProperties: false
121
+ };
122
+ var BackfillResultSchema = {
123
+ type: "object",
124
+ properties: {
125
+ candidates: { type: "number" },
126
+ updated: { type: "number" }
127
+ },
128
+ required: ["candidates", "updated"],
129
+ additionalProperties: false
130
+ };
131
+ var VacuumResultSchema = {
132
+ type: "object",
133
+ properties: {
134
+ before: { type: "number" },
135
+ after: { type: "number" },
136
+ freed: { type: "number" }
137
+ },
138
+ required: ["before", "after", "freed"],
139
+ additionalProperties: false
140
+ };
141
+ var NoInput = { type: "object", properties: {}, additionalProperties: false };
142
+ var ErrorSchema = {
143
+ type: "object",
144
+ properties: { message: { type: "string", maxLength: 500 } },
145
+ additionalProperties: false
146
+ };
147
+ var errors = {
148
+ busy: ErrorSchema,
149
+ unavailable: ErrorSchema,
150
+ disabled: ErrorSchema,
151
+ invalid: ErrorSchema
152
+ };
153
+ var UsageInsights = Rpc.define({
154
+ id: "usage-insights",
155
+ methods: {
156
+ panel: {
157
+ input: {
158
+ type: "object",
159
+ properties: {
160
+ sessionID: { type: "string", maxLength: 200 },
161
+ settings: PanelSettingsSchema,
162
+ detail: PanelRowSchema,
163
+ width: { type: "number", minimum: 20, maximum: MAX_PANEL_WIDTH },
164
+ busy: { type: "boolean" }
165
+ },
166
+ required: ["sessionID", "settings", "width"],
167
+ additionalProperties: false
168
+ },
169
+ output: {
170
+ type: "object",
171
+ properties: {
172
+ lines: { type: "array", items: PanelLineSchema },
173
+ database: DbInfoSchema
174
+ },
175
+ required: ["lines"],
176
+ additionalProperties: false
177
+ },
178
+ errors
179
+ },
180
+ turns: {
181
+ input: {
182
+ type: "object",
183
+ properties: {
184
+ sessionID: { type: "string", maxLength: 200 },
185
+ limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
186
+ width: { type: "number", minimum: 20, maximum: 120 }
187
+ },
188
+ required: ["sessionID", "limit", "width"],
189
+ additionalProperties: false
190
+ },
191
+ output: {
192
+ type: "object",
193
+ properties: {
194
+ summary: { type: "array", items: PanelLineSchema },
195
+ history: { type: "array", items: PanelLineSchema }
196
+ },
197
+ required: ["summary", "history"],
198
+ additionalProperties: false
199
+ },
200
+ errors
201
+ },
202
+ listCost: {
203
+ input: {
204
+ type: "object",
205
+ properties: { sessionID: { type: "string", maxLength: 200 } },
206
+ required: ["sessionID"],
207
+ additionalProperties: false
208
+ },
209
+ output: {
210
+ type: "object",
211
+ properties: { cost: { type: "number" } },
212
+ required: ["cost"],
213
+ additionalProperties: false
214
+ },
215
+ errors
216
+ },
217
+ filters: {
218
+ input: NoInput,
219
+ output: {
220
+ type: "object",
221
+ properties: {
222
+ models: { type: "array", items: FilterOptionSchema },
223
+ providers: { type: "array", items: FilterOptionSchema }
224
+ },
225
+ required: ["models", "providers"],
226
+ additionalProperties: false
227
+ },
228
+ errors
229
+ },
230
+ dbInfo: {
231
+ input: NoInput,
232
+ output: DbInfoSchema,
233
+ errors
234
+ },
235
+ prune: {
236
+ input: {
237
+ type: "object",
238
+ properties: {
239
+ days: { type: "number", minimum: 1, maximum: 3650 },
240
+ confirm: { type: "boolean", enum: [true] }
241
+ },
242
+ required: ["days", "confirm"],
243
+ additionalProperties: false
244
+ },
245
+ output: PruneResultSchema,
246
+ errors
247
+ },
248
+ wipe: {
249
+ input: {
250
+ type: "object",
251
+ properties: { confirm: { type: "boolean", enum: [true] } },
252
+ required: ["confirm"],
253
+ additionalProperties: false
254
+ },
255
+ output: WipeResultSchema,
256
+ errors
257
+ },
258
+ vacuum: {
259
+ input: {
260
+ type: "object",
261
+ properties: { confirm: { type: "boolean", enum: [true] } },
262
+ required: ["confirm"],
263
+ additionalProperties: false
264
+ },
265
+ output: VacuumResultSchema,
266
+ errors
267
+ },
268
+ backfill: {
269
+ input: {
270
+ type: "object",
271
+ properties: { confirm: { type: "boolean", enum: [true] } },
272
+ required: ["confirm"],
273
+ additionalProperties: false
274
+ },
275
+ output: BackfillResultSchema,
276
+ errors
277
+ }
278
+ },
279
+ events: {
280
+ recorded: {
281
+ schema: {
282
+ type: "object",
283
+ properties: {
284
+ sessionID: { type: "string", maxLength: 200 },
285
+ at: { type: "number" }
286
+ },
287
+ required: ["at"],
288
+ additionalProperties: false
289
+ }
290
+ }
291
+ }
292
+ });
293
+
5
294
  // src/pricing.ts
6
295
  function money(value) {
7
296
  return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
@@ -1247,10 +1536,13 @@ function turns(db, options) {
1247
1536
  window += row.streamed_at - row.created_at;
1248
1537
  }
1249
1538
  const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
1539
+ const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
1540
+ const firstAt = bucket[0]?.created_at ?? promptAt;
1250
1541
  result.push({
1251
1542
  sessionID: last.session_id,
1252
1543
  promptAt,
1253
- endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
1544
+ endAt,
1545
+ durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
1254
1546
  promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
1255
1547
  providerID,
1256
1548
  modelID,
@@ -1547,9 +1839,2337 @@ function createRecorder(db, options) {
1547
1839
  return { handleEvent, pendingFor };
1548
1840
  }
1549
1841
 
1842
+ // src/service.ts
1843
+ import { basename } from "path";
1844
+
1845
+ // src/stats/aggregates.ts
1846
+ var STEP_AT = "COALESCE(created_at, recorded_at)";
1847
+ function normalize(rows, optional) {
1848
+ for (const row of rows) {
1849
+ for (const key of optional)
1850
+ if (row[key] === null)
1851
+ row[key] = undefined;
1852
+ }
1853
+ return rows;
1854
+ }
1855
+ function groupBy(items, key) {
1856
+ const groups = new Map;
1857
+ for (const item of items) {
1858
+ const group = key(item);
1859
+ const list = groups.get(group);
1860
+ if (list !== undefined)
1861
+ list.push(item);
1862
+ else
1863
+ groups.set(group, [item]);
1864
+ }
1865
+ return groups;
1866
+ }
1867
+ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,
1868
+ model_id AS modelID, variant,
1869
+ COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1870
+ COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1871
+ COALESCE(list_cost, 0) AS listCost,
1872
+ created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1873
+ var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
1874
+ var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1875
+ function stepRows(db, options) {
1876
+ const filter = buildWhere(options?.range, options?.filters);
1877
+ const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
1878
+ return normalize(rows, STEP_OPTIONAL);
1879
+ }
1880
+ function cachePairs(db, options) {
1881
+ const filter = buildWhere(options?.range, options?.filters);
1882
+ 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);
1883
+ const from = options?.range?.from;
1884
+ if (from === undefined || rows.length === 0)
1885
+ return rows;
1886
+ const seek = db.query(`SELECT ${PAIR_COLUMNS} FROM steps
1887
+ WHERE session_id = ? AND COALESCE(created_at, recorded_at) < ?
1888
+ ORDER BY COALESCE(created_at, recorded_at) DESC, message_id DESC LIMIT 1`);
1889
+ for (const sessionID of new Set(rows.map((row) => row.sessionID))) {
1890
+ const boundary = seek.get(sessionID, from);
1891
+ if (boundary === null)
1892
+ continue;
1893
+ const step = normalize([boundary], STEP_OPTIONAL)[0];
1894
+ step.boundary = true;
1895
+ rows.push(step);
1896
+ }
1897
+ rows.sort((left, right) => {
1898
+ if (left.sessionID !== right.sessionID)
1899
+ return left.sessionID < right.sessionID ? -1 : 1;
1900
+ if (left.at !== right.at)
1901
+ return left.at - right.at;
1902
+ return left.messageID < right.messageID ? -1 : left.messageID > right.messageID ? 1 : 0;
1903
+ });
1904
+ return rows;
1905
+ }
1906
+ function message(step) {
1907
+ return {
1908
+ type: "assistant",
1909
+ id: step.messageID,
1910
+ ...step.modelID === undefined ? {} : { model: { providerID: step.providerID ?? "", id: step.modelID, ...step.variant === undefined ? {} : { variant: step.variant } } },
1911
+ tokens: { cache: { read: step.cached } },
1912
+ time: {
1913
+ ...step.createdAt === undefined ? {} : { created: step.createdAt },
1914
+ ...step.streamedAt === undefined ? {} : { streamed: step.streamedAt },
1915
+ ...step.completedAt === undefined ? {} : { completed: step.completedAt }
1916
+ }
1917
+ };
1918
+ }
1919
+ function pairsOf(rows) {
1920
+ const pairs = [];
1921
+ for (let index = 1;index < rows.length; index += 1) {
1922
+ const previous = rows[index - 1];
1923
+ const current = rows[index];
1924
+ if (previous.sessionID !== current.sessionID)
1925
+ continue;
1926
+ pairs.push({ previous, current });
1927
+ }
1928
+ return pairs;
1929
+ }
1930
+ function usageOf(steps) {
1931
+ const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
1932
+ for (const step of steps) {
1933
+ usage.steps += 1;
1934
+ usage.input += step.input;
1935
+ usage.cached += step.cached;
1936
+ usage.cacheWrite += step.cacheWrite;
1937
+ usage.output += step.output;
1938
+ usage.reasoning += step.reasoning;
1939
+ usage.cost += step.cost;
1940
+ usage.listCost += step.listCost;
1941
+ }
1942
+ return usage;
1943
+ }
1944
+ function coverageOf(db, options) {
1945
+ const filter = buildWhere(options?.range, options?.filters);
1946
+ const row = db.query(`SELECT COUNT(*) AS steps,
1947
+ COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,
1948
+ COUNT(DISTINCT provider_id) AS providers,
1949
+ COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1950
+ COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1951
+ 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,
1952
+ MIN(${STEP_AT}) AS firstAt,
1953
+ MAX(${STEP_AT}) AS lastAt
1954
+ FROM steps ${filter.where}`).get(...filter.params);
1955
+ return {
1956
+ steps: row.steps,
1957
+ models: row.models,
1958
+ providers: row.providers,
1959
+ missingModel: row.missingModel,
1960
+ unsettled: row.unsettled,
1961
+ missingTps: row.missingTps,
1962
+ firstAt: row.firstAt ?? undefined,
1963
+ lastAt: row.lastAt ?? undefined
1964
+ };
1965
+ }
1966
+ function groupedRows(db, options) {
1967
+ const filter = buildWhere(options?.range, options?.filters);
1968
+ const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
1969
+ return normalize(rows, STEP_OPTIONAL);
1970
+ }
1971
+ function timingOf(step) {
1972
+ const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
1973
+ const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
1974
+ return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
1975
+ }
1976
+ function timingRows(db, options) {
1977
+ return groupedRows(db, options);
1978
+ }
1979
+ function latencyOf(rows) {
1980
+ const wall = [];
1981
+ const stream = [];
1982
+ const tps = [];
1983
+ for (const step of rows) {
1984
+ const timing = timingOf(step);
1985
+ if (timing.wall !== undefined)
1986
+ wall.push(timing.wall);
1987
+ if (timing.stream !== undefined)
1988
+ stream.push(timing.stream);
1989
+ if (timing.tps !== undefined)
1990
+ tps.push(timing.tps);
1991
+ }
1992
+ return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
1993
+ }
1994
+ function latencyGroupsOf(rows, by) {
1995
+ const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
1996
+ const groups = [];
1997
+ for (const [group, steps] of groupBy(rows, key)) {
1998
+ const wall = [];
1999
+ const stream = [];
2000
+ const tps = [];
2001
+ for (const step of steps) {
2002
+ const timing = timingOf(step);
2003
+ if (timing.wall !== undefined)
2004
+ wall.push(timing.wall);
2005
+ if (timing.stream !== undefined)
2006
+ stream.push(timing.stream);
2007
+ if (timing.tps !== undefined)
2008
+ tps.push(timing.tps);
2009
+ }
2010
+ const [modelID, variant] = group.split("#");
2011
+ groups.push({
2012
+ key: group,
2013
+ label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
2014
+ count: steps.length,
2015
+ usage: usageOf(steps),
2016
+ wall: latencyStats(wall),
2017
+ stream: latencyStats(stream),
2018
+ tps: latencyStats(tps)
2019
+ });
2020
+ }
2021
+ return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
2022
+ }
2023
+ var EMPTY_CACHE = { steps: 0, input: 0, cached: 0, cacheWrite: 0, prompt: 0, hit: undefined, hitP50: undefined };
2024
+ function cacheStatsOfSteps(steps) {
2025
+ let input = 0;
2026
+ let cached = 0;
2027
+ let cacheWrite = 0;
2028
+ const ratios = [];
2029
+ for (const step of steps) {
2030
+ input += step.input;
2031
+ cached += step.cached;
2032
+ cacheWrite += step.cacheWrite;
2033
+ const prompt = step.input + step.cached + step.cacheWrite;
2034
+ if (prompt > 0)
2035
+ ratios.push(step.cached / prompt);
2036
+ }
2037
+ const prompt = input + cached + cacheWrite;
2038
+ return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) };
2039
+ }
2040
+ function cacheStatsOf(db, options) {
2041
+ const rows = stepRows(db, options);
2042
+ return rows.length === 0 ? EMPTY_CACHE : cacheStatsOfSteps(rows);
2043
+ }
2044
+ function cacheStatsByModel(rows) {
2045
+ const out = [];
2046
+ const inRange = rows.filter((row) => row.boundary !== true);
2047
+ for (const [, group] of groupBy(inRange, (row) => modelKey(row.modelID ?? "(unknown)", row.variant))) {
2048
+ out.push({ modelID: group[0].modelID ?? "(unknown)", variant: group[0].variant, cache: cacheStatsOfSteps(group) });
2049
+ }
2050
+ return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID));
2051
+ }
2052
+ function switchesOf(rows) {
2053
+ const perModel = new Map;
2054
+ const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 };
2055
+ for (const { previous, current } of pairsOf(rows)) {
2056
+ if (previous.modelID === undefined || current.modelID === undefined)
2057
+ continue;
2058
+ const key = modelKey(current.modelID, current.variant);
2059
+ const row = perModel.get(key) ?? {
2060
+ modelID: current.modelID,
2061
+ variant: current.variant,
2062
+ steps: 0,
2063
+ pairs: 0,
2064
+ changes: 0,
2065
+ modelChanges: 0,
2066
+ providerChanges: 0,
2067
+ cacheLost: 0,
2068
+ cacheLostEvents: 0
2069
+ };
2070
+ row.steps += 1;
2071
+ row.pairs += 1;
2072
+ totals.pairs += 1;
2073
+ const modelChanged = key !== modelKey(previous.modelID, previous.variant);
2074
+ const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID;
2075
+ if (modelChanged)
2076
+ row.modelChanges += 1;
2077
+ if (providerChanged)
2078
+ row.providerChanges += 1;
2079
+ if (modelChanged || providerChanged) {
2080
+ row.changes += 1;
2081
+ totals.changes += 1;
2082
+ const lost = cacheDrop(message(previous), message(current), "model");
2083
+ if (lost !== undefined) {
2084
+ row.cacheLost += lost;
2085
+ row.cacheLostEvents += 1;
2086
+ totals.cacheLost += lost;
2087
+ totals.cacheLostEvents += 1;
2088
+ }
2089
+ }
2090
+ perModel.set(key, row);
2091
+ }
2092
+ return {
2093
+ rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),
2094
+ totals
2095
+ };
2096
+ }
2097
+ var GAP_BUCKETS = [
2098
+ ["<1m", 0, 60000],
2099
+ ["1\u20135m", 60000, 5 * 60000],
2100
+ ["5\u201315m", 5 * 60000, 15 * 60000],
2101
+ ["15\u201360m", 15 * 60000, 60 * 60000],
2102
+ ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
2103
+ [">6h", 6 * 60 * 60000, undefined]
2104
+ ];
2105
+ function bucketFor(gapMs) {
2106
+ const index = GAP_BUCKETS.findIndex(([, from, to]) => gapMs >= from && (to === undefined || gapMs < to));
2107
+ return index === -1 ? GAP_BUCKETS.length - 1 : index;
2108
+ }
2109
+ function gapReportOf(rows) {
2110
+ const buckets = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }));
2111
+ const providers = new Map;
2112
+ let samples = 0;
2113
+ for (const { previous, current } of pairsOf(rows)) {
2114
+ if (previous.modelID === undefined || current.modelID === undefined)
2115
+ continue;
2116
+ if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant))
2117
+ continue;
2118
+ if ((previous.providerID ?? "") !== (current.providerID ?? ""))
2119
+ continue;
2120
+ const gap = stepGap(message(previous), message(current));
2121
+ if (gap === undefined)
2122
+ continue;
2123
+ const lost = cacheDrop(message(previous), message(current));
2124
+ const bucket = buckets[bucketFor(gap)];
2125
+ bucket.samples += 1;
2126
+ samples += 1;
2127
+ if (lost === undefined)
2128
+ bucket.retained += 1;
2129
+ else {
2130
+ bucket.drops += 1;
2131
+ bucket.lostTokens += lost;
2132
+ }
2133
+ const provider = current.providerID ?? previous.providerID ?? "(unknown)";
2134
+ const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined };
2135
+ row.samples += 1;
2136
+ if (lost === undefined)
2137
+ row.retained += 1;
2138
+ else {
2139
+ row.drops += 1;
2140
+ row.lostTokens += lost;
2141
+ }
2142
+ providers.set(provider, row);
2143
+ }
2144
+ for (const bucket of buckets)
2145
+ bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined;
2146
+ for (const row of providers.values())
2147
+ row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined;
2148
+ return {
2149
+ buckets,
2150
+ providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),
2151
+ samples
2152
+ };
2153
+ }
2154
+ function ttlEvidenceOf(rows) {
2155
+ const evidence = new Map;
2156
+ for (const { previous, current } of pairsOf(rows)) {
2157
+ if (previous.modelID === undefined || current.modelID === undefined)
2158
+ continue;
2159
+ const key = `${current.providerID ?? ""}/${current.modelID}`;
2160
+ const before = `${previous.providerID ?? ""}/${previous.modelID}#${previous.variant ?? ""}`;
2161
+ const after = `${current.providerID ?? ""}/${current.modelID}#${current.variant ?? ""}`;
2162
+ if (before !== after)
2163
+ continue;
2164
+ const row = evidence.get(key) ?? {
2165
+ providerID: current.providerID ?? "(unknown)",
2166
+ modelID: current.modelID,
2167
+ samples: 0,
2168
+ maxHitGapMs: undefined,
2169
+ minDropGapMs: undefined
2170
+ };
2171
+ row.samples += 1;
2172
+ const gapMs = stepGap(message(previous), message(current));
2173
+ if (gapMs !== undefined) {
2174
+ const lost = cacheDrop(message(previous), message(current));
2175
+ if (lost === undefined)
2176
+ row.maxHitGapMs = row.maxHitGapMs === undefined ? gapMs : Math.max(row.maxHitGapMs, gapMs);
2177
+ else
2178
+ row.minDropGapMs = row.minDropGapMs === undefined ? gapMs : Math.min(row.minDropGapMs, gapMs);
2179
+ }
2180
+ evidence.set(key, row);
2181
+ }
2182
+ return [...evidence.values()].sort((left, right) => right.samples - left.samples || `${left.providerID}/${left.modelID}`.localeCompare(`${right.providerID}/${right.modelID}`));
2183
+ }
2184
+ function cacheDropsOf(db, rows, options) {
2185
+ const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS;
2186
+ const losses = [];
2187
+ for (const { previous, current } of pairsOf(rows)) {
2188
+ const tokens = cacheDrop(message(previous), message(current), "model");
2189
+ if (tokens === undefined)
2190
+ continue;
2191
+ losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) });
2192
+ }
2193
+ if (losses.length === 0)
2194
+ return [];
2195
+ const compactions = new Map;
2196
+ const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
2197
+ const events = db.query(`SELECT session_id, at FROM events
2198
+ WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
2199
+ ORDER BY at`).all(...sessionIDs);
2200
+ for (const event of events) {
2201
+ const list = compactions.get(event.session_id);
2202
+ if (list !== undefined)
2203
+ list.push(event.at);
2204
+ else
2205
+ compactions.set(event.session_id, [event.at]);
2206
+ }
2207
+ return losses.map((loss) => {
2208
+ const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
2209
+ const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
2210
+ const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
2211
+ return {
2212
+ sessionID: loss.current.sessionID,
2213
+ messageID: loss.current.messageID,
2214
+ providerID: loss.current.providerID,
2215
+ modelID: loss.current.modelID,
2216
+ variant: loss.current.variant,
2217
+ at: loss.current.at,
2218
+ tokens: loss.tokens,
2219
+ gapMs: loss.gapMs,
2220
+ prevCached: loss.previous.cached,
2221
+ reason
2222
+ };
2223
+ }).sort((left, right) => left.at - right.at);
2224
+ }
2225
+ function groupValues(steps) {
2226
+ const wall = [];
2227
+ const tps = [];
2228
+ for (const step of steps) {
2229
+ const timing = timingOf(step);
2230
+ if (timing.wall !== undefined)
2231
+ wall.push(timing.wall);
2232
+ if (timing.tps !== undefined)
2233
+ tps.push(timing.tps);
2234
+ }
2235
+ return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
2236
+ }
2237
+ function providerOf(steps, models) {
2238
+ const values = groupValues(steps);
2239
+ let firstAt;
2240
+ let lastAt;
2241
+ for (const step of steps) {
2242
+ if (firstAt === undefined || step.at < firstAt)
2243
+ firstAt = step.at;
2244
+ if (lastAt === undefined || step.at > lastAt)
2245
+ lastAt = step.at;
2246
+ }
2247
+ return {
2248
+ provider: steps[0].providerID,
2249
+ models: models.split("\x00"),
2250
+ share: 0,
2251
+ usage: usageOf(steps),
2252
+ cache: values.cache,
2253
+ tps: values.tps,
2254
+ wall: values.wall,
2255
+ firstAt,
2256
+ lastAt
2257
+ };
2258
+ }
2259
+ 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");
2260
+ function providerSummaryOf(rows) {
2261
+ const out = [];
2262
+ for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
2263
+ const summary = providerOf(steps, modelNames(steps));
2264
+ out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length });
2265
+ }
2266
+ return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? "").localeCompare(right.provider ?? ""));
2267
+ }
2268
+ function providerBreakdownOf(rows) {
2269
+ const out = [];
2270
+ for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
2271
+ for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
2272
+ const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
2273
+ out.push({
2274
+ ...providerOf(steps, modelNames(steps)),
2275
+ modelID,
2276
+ variant: variant === "" ? undefined : variant,
2277
+ share: steps.length / modelRows.length
2278
+ });
2279
+ }
2280
+ }
2281
+ return out.sort((left, right) => right.usage.steps - left.usage.steps || right.cache.cached - left.cache.cached);
2282
+ }
2283
+ function isoWeek(date) {
2284
+ const monday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
2285
+ monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);
2286
+ const thursday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 3);
2287
+ const firstThursday = new Date(thursday.getFullYear(), 0, 4);
2288
+ firstThursday.setDate(firstThursday.getDate() - (firstThursday.getDay() + 6) % 7 + 3);
2289
+ const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000));
2290
+ return { year: thursday.getFullYear(), week, monday };
2291
+ }
2292
+ function periodEnd(at, granularity) {
2293
+ const date = new Date(at);
2294
+ if (granularity === "month")
2295
+ return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime();
2296
+ if (granularity === "week")
2297
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime();
2298
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
2299
+ }
2300
+ function periodStart(at, granularity) {
2301
+ const date = new Date(at);
2302
+ const pad = (value) => String(value).padStart(2, "0");
2303
+ if (granularity === "month") {
2304
+ const start = new Date(date.getFullYear(), date.getMonth(), 1);
2305
+ return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() };
2306
+ }
2307
+ if (granularity === "week") {
2308
+ const { year, week, monday } = isoWeek(date);
2309
+ return { key: `${year}-W${pad(week)}`, label: `${year}-W${pad(week)}`, start: monday.getTime() };
2310
+ }
2311
+ const start = new Date(date.getFullYear(), date.getMonth(), date.getDate());
2312
+ const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
2313
+ return { key, label: key, start: start.getTime() };
2314
+ }
2315
+ function periodsOf(rows, granularity, otherRows = []) {
2316
+ const byKey = new Map;
2317
+ for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {
2318
+ const period = periodStart(steps[0].at, granularity);
2319
+ byKey.set(key, {
2320
+ key,
2321
+ label: period.label,
2322
+ at: period.start,
2323
+ steps: steps.length,
2324
+ sessions: new Set(steps.map((step) => step.sessionID)).size,
2325
+ usage: usageOf(steps),
2326
+ cache: cacheStatsOfSteps(steps)
2327
+ });
2328
+ }
2329
+ for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {
2330
+ const cost = group.reduce((sum, row) => sum + row.cost, 0);
2331
+ const existing = byKey.get(key);
2332
+ if (existing !== undefined) {
2333
+ existing.usage.cost += cost;
2334
+ existing.otherCost = (existing.otherCost ?? 0) + cost;
2335
+ continue;
2336
+ }
2337
+ const period = periodStart(group[0].at, granularity);
2338
+ byKey.set(key, {
2339
+ key,
2340
+ label: period.label,
2341
+ at: period.start,
2342
+ steps: 0,
2343
+ sessions: new Set(group.map((row) => row.sessionID)).size,
2344
+ usage: { ...usageOf([]), cost },
2345
+ cache: cacheStatsOfSteps([]),
2346
+ otherCost: cost
2347
+ });
2348
+ }
2349
+ return [...byKey.values()].sort((left, right) => left.at - right.at);
2350
+ }
2351
+
2352
+ // src/panel-data.ts
2353
+ var PANEL_NAME = "usage-insights";
2354
+ var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
2355
+ var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
2356
+ var GRANULARITIES = ["day", "week", "month"];
2357
+ var SORT_KEYS = {
2358
+ models: ["steps", "cached", "hit", "out", "cost"],
2359
+ providers: ["steps", "cached", "hit", "cost", "share", "tps"],
2360
+ latency: ["n", "tps", "wall"],
2361
+ sessions: ["last", "steps", "cached", "cost"],
2362
+ turns: ["time", "cost", "tokens"]
2363
+ };
2364
+ function sortKeys(view) {
2365
+ return SORT_KEYS[view] ?? [];
2366
+ }
2367
+ function defaultSort(view) {
2368
+ return sortKeys(view)[0] ?? "";
2369
+ }
2370
+ function nextSort(view, current, step) {
2371
+ const keys = sortKeys(view);
2372
+ if (keys.length === 0)
2373
+ return current;
2374
+ const index = keys.indexOf(current);
2375
+ if (index === -1)
2376
+ return keys[0];
2377
+ return keys[(index + step + keys.length) % keys.length];
2378
+ }
2379
+ function parseArgs(input) {
2380
+ const parsed = {};
2381
+ for (const token of (input ?? "").split(/\s+/)) {
2382
+ const value = token.trim().toLowerCase();
2383
+ if (value === "")
2384
+ continue;
2385
+ if (PANEL_VIEWS.includes(value))
2386
+ parsed.view = value;
2387
+ else if (RANGE_KEYS.includes(value))
2388
+ parsed.range = value;
2389
+ }
2390
+ return parsed;
2391
+ }
2392
+ function rangeLabel(key) {
2393
+ switch (key) {
2394
+ case "session":
2395
+ return "this session";
2396
+ case "today":
2397
+ return "today";
2398
+ case "7d":
2399
+ return "7 days";
2400
+ case "30d":
2401
+ return "30 days";
2402
+ case "all":
2403
+ return "all time";
2404
+ }
2405
+ }
2406
+ function nextIn(values, current, step) {
2407
+ const index = values.indexOf(current);
2408
+ if (index === -1)
2409
+ return values[0];
2410
+ return values[(index + step + values.length) % values.length];
2411
+ }
2412
+ var DEFAULT_SETTINGS = {
2413
+ view: "overview",
2414
+ range: "all",
2415
+ sort: "",
2416
+ sortDesc: true,
2417
+ granularity: "day",
2418
+ turnsScope: "session",
2419
+ modelID: "",
2420
+ providerID: ""
2421
+ };
2422
+ function sanitizeSettings(raw) {
2423
+ const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
2424
+ return {
2425
+ view: PANEL_VIEWS.includes(settings.view) ? settings.view : DEFAULT_SETTINGS.view,
2426
+ range: RANGE_KEYS.includes(settings.range) ? settings.range : DEFAULT_SETTINGS.range,
2427
+ sort: typeof settings.sort === "string" ? settings.sort : DEFAULT_SETTINGS.sort,
2428
+ sortDesc: settings.sortDesc === true,
2429
+ granularity: GRANULARITIES.includes(settings.granularity) ? settings.granularity : DEFAULT_SETTINGS.granularity,
2430
+ turnsScope: settings.turnsScope === "all" ? "all" : "session",
2431
+ modelID: typeof settings.modelID === "string" ? settings.modelID : "",
2432
+ providerID: typeof settings.providerID === "string" ? settings.providerID : ""
2433
+ };
2434
+ }
2435
+ function formatPercent(value, digits = 1) {
2436
+ if (value === undefined || !Number.isFinite(value))
2437
+ return "\u2013";
2438
+ return `${(value * 100).toFixed(digits)}%`;
2439
+ }
2440
+ function formatCount(value) {
2441
+ return Number.isFinite(value) ? Math.round(value).toLocaleString("en-US") : "\u2013";
2442
+ }
2443
+ function formatMs(value) {
2444
+ if (value === undefined || !Number.isFinite(value))
2445
+ return "\u2013";
2446
+ const ms = Math.max(0, value);
2447
+ if (ms < 1000)
2448
+ return `${Math.round(ms)}ms`;
2449
+ if (ms < 60000)
2450
+ return `${(ms / 1000).toFixed(1)}s`;
2451
+ return formatDuration(ms);
2452
+ }
2453
+ function formatTps(value) {
2454
+ if (value === undefined || !Number.isFinite(value) || value < 0)
2455
+ return "\u2013";
2456
+ return `${value.toFixed(1)}/s`;
2457
+ }
2458
+ function formatTpsCompact(value) {
2459
+ if (value === undefined || !Number.isFinite(value) || value < 0)
2460
+ return "\u2013";
2461
+ return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
2462
+ }
2463
+ function formatGap(value) {
2464
+ if (value === undefined || !Number.isFinite(value))
2465
+ return "\u2013";
2466
+ const gap = Math.max(0, value);
2467
+ if (gap < 60000)
2468
+ return `${Math.round(gap / 1000)}s`;
2469
+ if (gap < 3600000)
2470
+ return `${Math.round(gap / 60000)}m`;
2471
+ if (gap < 86400000)
2472
+ return `${(gap / 3600000).toFixed(1)}h`;
2473
+ return `${(gap / 86400000).toFixed(1)}d`;
2474
+ }
2475
+ function truncate(value, width) {
2476
+ if (width <= 1)
2477
+ return "";
2478
+ const clean = sanitizeText(value);
2479
+ if (clean.length <= width)
2480
+ return clean;
2481
+ return `${clean.slice(0, width - 1).trimEnd()}\u2026`;
2482
+ }
2483
+ function truncateMiddle(value, width) {
2484
+ if (width <= 1)
2485
+ return "";
2486
+ const clean = sanitizeText(value);
2487
+ if (clean.length <= width)
2488
+ return clean;
2489
+ const head = Math.ceil((width - 1) / 2);
2490
+ const tail = width - 1 - head;
2491
+ return `${clean.slice(0, head)}\u2026${clean.slice(clean.length - tail)}`;
2492
+ }
2493
+ function tableWidths(width, layouts) {
2494
+ for (const layout of layouts) {
2495
+ const total = layout.reduce((sum, column) => sum + column, 0) + layout.length - 1;
2496
+ if (total <= width)
2497
+ return [...layout];
2498
+ }
2499
+ const last = layouts[layouts.length - 1];
2500
+ return last === undefined ? [] : [...last];
2501
+ }
2502
+ function modelCell(modelID, variant, width) {
2503
+ return truncateMiddle(variant === undefined ? modelID : `${modelID} ${variant}`, width);
2504
+ }
2505
+ function padCell(value, width, align = "left") {
2506
+ if (value.length >= width)
2507
+ return value;
2508
+ const padding = " ".repeat(width - value.length);
2509
+ return align === "right" ? `${padding}${value}` : `${value}${padding}`;
2510
+ }
2511
+ function formatTableRow(cells, widths, aligns) {
2512
+ const parts = [];
2513
+ for (let index = 0;index < cells.length; index += 1) {
2514
+ const width = widths[index] ?? 8;
2515
+ const align = aligns?.[index] ?? "left";
2516
+ parts.push(padCell(truncate(cells[index] ?? "", width), width, align));
2517
+ }
2518
+ return parts.join(" ");
2519
+ }
2520
+ function count(n, singular, plural = `${singular}s`) {
2521
+ return `${formatCount(n)} ${n === 1 ? singular : plural}`;
2522
+ }
2523
+ function kvGrid(pairs, width) {
2524
+ const lines = [];
2525
+ const label = 11;
2526
+ const column = Math.floor(width / 2);
2527
+ for (let index = 0;index < pairs.length; index += 2) {
2528
+ const left = pairs[index];
2529
+ const right = pairs[index + 1];
2530
+ const leftText = `${padCell(left[0], label)}${left[1]}`;
2531
+ if (right === undefined) {
2532
+ lines.push({ text: leftText, tone: "base" });
2533
+ continue;
2534
+ }
2535
+ const rightText = `${padCell(right[0], label)}${right[1]}`;
2536
+ const gap = Math.max(2, column - leftText.length);
2537
+ if (leftText.length + gap + rightText.length <= width) {
2538
+ lines.push({ text: `${leftText}${" ".repeat(gap)}${rightText}`, tone: "base" });
2539
+ } else {
2540
+ lines.push({ text: leftText, tone: "base" });
2541
+ lines.push({ text: rightText, tone: "base" });
2542
+ }
2543
+ }
2544
+ return lines;
2545
+ }
2546
+ var HEADER_TONE = "accent";
2547
+ var SPARK = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
2548
+ function reduceSeries(values, maxBars = 48) {
2549
+ if (values.length <= maxBars)
2550
+ return [...values];
2551
+ const group = Math.ceil(values.length / maxBars);
2552
+ const reduced = [];
2553
+ for (let index = 0;index < values.length; index += group) {
2554
+ reduced.push(values.slice(index, index + group).reduce((sum, value) => sum + value, 0));
2555
+ }
2556
+ return reduced;
2557
+ }
2558
+ function sparkline(values, maxBars = 48) {
2559
+ if (values.length === 0)
2560
+ return "";
2561
+ const series = reduceSeries(values, maxBars);
2562
+ const max = Math.max(...series);
2563
+ if (max <= 0)
2564
+ return SPARK[0].repeat(series.length);
2565
+ return series.map((value) => SPARK[Math.min(SPARK.length - 1, Math.max(0, Math.round(value / max * (SPARK.length - 1))))]).join("");
2566
+ }
2567
+ function usageBuckets(usage) {
2568
+ const prompt = usage.input + usage.cached + usage.cacheWrite;
2569
+ return {
2570
+ steps: usage.steps,
2571
+ input: prompt - usage.cached,
2572
+ prompt,
2573
+ cached: usage.cached,
2574
+ cacheWrite: usage.cacheWrite,
2575
+ output: usage.output + usage.reasoning,
2576
+ reasoning: usage.reasoning,
2577
+ cost: usage.cost,
2578
+ listCost: usage.listCost ?? 0,
2579
+ hit: prompt > 0 ? usage.cached / prompt : undefined
2580
+ };
2581
+ }
2582
+ function viewBar(view, width = 200) {
2583
+ const key = (index) => String((index + 1) % 10);
2584
+ const full = PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name}`);
2585
+ const candidates = [full, PANEL_VIEWS.map((name, index) => name === view ? `[${key(index)} ${name}]` : `${key(index)} ${name.slice(0, 3)}`)];
2586
+ for (const parts of candidates) {
2587
+ const text = parts.join(" ");
2588
+ if (text.length <= width)
2589
+ return { text, tone: "muted" };
2590
+ }
2591
+ return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
2592
+ }
2593
+ function keysFor(of) {
2594
+ if (of === "db")
2595
+ return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
2596
+ if (of === "periods")
2597
+ return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2598
+ if (of === "turns")
2599
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2600
+ return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
2601
+ }
2602
+ function filterSummary(filters) {
2603
+ const parts = [];
2604
+ if (filters.modelID !== undefined && filters.modelID !== "")
2605
+ parts.push(`model=${filters.modelID}`);
2606
+ if (filters.providerID !== undefined && filters.providerID !== "")
2607
+ parts.push(`provider=${filters.providerID}`);
2608
+ return parts.length > 0 ? parts.join(" \xB7 ") : undefined;
2609
+ }
2610
+ function granularityLabel(granularity) {
2611
+ return granularity === "day" ? "per day" : granularity === "week" ? "per week" : "per month";
2612
+ }
2613
+ function helpLines(width) {
2614
+ const lines = [
2615
+ { text: "keys", tone: HEADER_TONE },
2616
+ { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
2617
+ { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
2618
+ { text: " t shift+t previous / next range" },
2619
+ { text: " s shift+s cycle sort column \xB7 reverse" },
2620
+ { text: " b periods bucket: day \u2192 week \u2192 month" },
2621
+ { text: " a turns scope: this session \u2194 all sessions" },
2622
+ { text: " m p filter by model / provider (x clears)" },
2623
+ { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
2624
+ { text: " e db: backfill list-price estimates for the $0 steps" },
2625
+ { text: "" },
2626
+ { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
2627
+ { text: " prompt everything the provider saw: cached + fresh + writes" },
2628
+ { text: " in the uncached part: fresh input + cache writes" },
2629
+ { text: " cached prompt read from the provider prompt cache" },
2630
+ { text: " write part of `in`: prompt written into that cache" },
2631
+ { text: " hit cached / prompt, weighted over the selection" },
2632
+ { text: " hit p50 median of the per-step hit: spots a split pattern" },
2633
+ { text: " out everything generated: visible output + reasoning" },
2634
+ { text: " reasoning part of `out`" },
2635
+ { text: " cost money, not tokens: a turn sums every step; $0 is left out" },
2636
+ { text: " other compaction/title usage: money with no assistant step;" },
2637
+ { text: " overview, periods and sessions include it; model rows do not" },
2638
+ { text: " \u2248 list-price estimate for steps the host reported as $0;" },
2639
+ { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
2640
+ { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
2641
+ { text: " tps out / streaming seconds, shown as p50" },
2642
+ { text: " switches how often a step's model or provider differs from the step" },
2643
+ { text: " before it in the same session (the models view's detail), with" },
2644
+ { text: " the cache a provider switch cost" },
2645
+ { text: "" },
2646
+ { text: "identity", tone: HEADER_TONE },
2647
+ { text: " provider the provider the model ran through, as OpenCode is configured" },
2648
+ { text: " (opencode, opencode-go, deepseek, \u2026). A gateway may re-route" },
2649
+ { text: " a request, but the upstream that ran the inference is not" },
2650
+ { text: " observable, so the provider is the identity every view shows." },
2651
+ { text: "" },
2652
+ { text: "database", tone: HEADER_TONE },
2653
+ { text: " the db view shows where the file lives, what it holds and how much" },
2654
+ { text: " of it is old: \u2191\u2193 pick a retention or wipe, enter asks before it" },
2655
+ { text: " deletes, e backfills list estimates, v gives the space back" },
2656
+ { text: " local time \xB7 SQLite in the OpenCode state directory" }
2657
+ ];
2658
+ return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
2659
+ }
2660
+ function usagePairs(usage, estimates = true) {
2661
+ if (usage === undefined)
2662
+ return [];
2663
+ const buckets = usageBuckets(usage);
2664
+ const pairs = [
2665
+ ["steps", formatCount(buckets.steps)],
2666
+ ["in", formatTokens(buckets.input)],
2667
+ ["prompt", formatTokens(buckets.prompt)],
2668
+ ["cached", formatTokens(buckets.cached)],
2669
+ ["hit", formatPercent(buckets.hit)],
2670
+ ["out", formatTokens(buckets.output)],
2671
+ ["write", formatTokens(buckets.cacheWrite)]
2672
+ ];
2673
+ if (buckets.reasoning > 0)
2674
+ pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
2675
+ pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
2676
+ const other = usage.otherCost ?? 0;
2677
+ if (other > 0)
2678
+ pairs.push(["other", `${formatCost(other)} comp/title`]);
2679
+ if ("tps" in usage && usage.tps !== undefined)
2680
+ pairs.push(["tps", formatTps(usage.tps)]);
2681
+ return pairs;
2682
+ }
2683
+ function overviewLines(data, width) {
2684
+ const lines = [];
2685
+ const estimates = data.estimates !== false;
2686
+ lines.push({
2687
+ text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
2688
+ tone: "muted"
2689
+ });
2690
+ lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
2691
+ if (data.activity !== undefined && data.activity.length > 1) {
2692
+ const series = reduceSeries(data.activity);
2693
+ lines.push({ text: "", tone: "muted" });
2694
+ lines.push({ text: `activity ${sparkline(series)} ${count(series.length, "bucket")}`, tone: "muted" });
2695
+ }
2696
+ if (data.session !== undefined) {
2697
+ lines.push({ text: "", tone: "muted" });
2698
+ lines.push({ text: "this session", tone: HEADER_TONE });
2699
+ lines.push(...kvGrid(buildOverviewPairs(data.session, "session", estimates), width));
2700
+ if (data.subagents !== undefined && data.subagents.length > 0) {
2701
+ const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0);
2702
+ const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
2703
+ const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
2704
+ lines.push({
2705
+ text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
2706
+ tone: "muted"
2707
+ });
2708
+ }
2709
+ }
2710
+ if (data.coverage !== undefined) {
2711
+ lines.push({ text: "", tone: "muted" });
2712
+ lines.push({ text: "data coverage", tone: HEADER_TONE });
2713
+ lines.push(...kvGrid(coveragePairs(data.coverage), width));
2714
+ }
2715
+ return lines;
2716
+ }
2717
+ function buildOverviewPairs(usage, scope, estimates = true) {
2718
+ const pairs = usagePairs(usage, estimates);
2719
+ if (scope === "all") {
2720
+ pairs.push(["first", usage.firstAt === undefined ? "\u2013" : new Date(usage.firstAt).toLocaleString("en-GB")]);
2721
+ pairs.push(["last", usage.lastAt === undefined ? "\u2013" : new Date(usage.lastAt).toLocaleString("en-GB")]);
2722
+ }
2723
+ return pairs;
2724
+ }
2725
+ function coveragePairs(coverage) {
2726
+ const share = (missing) => coverage.steps === 0 ? "\u2013" : `${(missing / coverage.steps * 100).toFixed(1)}%`;
2727
+ return [
2728
+ ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
2729
+ ["providers", formatCount(coverage.providers)],
2730
+ ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
2731
+ [
2732
+ "window",
2733
+ `${coverage.firstAt === undefined ? "\u2013" : new Date(coverage.firstAt).toLocaleString("en-GB")} \u2192 ${coverage.lastAt === undefined ? "\u2013" : new Date(coverage.lastAt).toLocaleString("en-GB")}`
2734
+ ]
2735
+ ];
2736
+ }
2737
+ function modelColumns(width) {
2738
+ const layouts = [
2739
+ { model: 30, steps: 6, prompt: 10, cached: 10, hit: 7, out: 9, cost: 9, spread: 24 },
2740
+ { model: 26, steps: 6, prompt: 9, cached: 9, hit: 7, out: 8, cost: 8, spread: 20 },
2741
+ { model: 20, steps: 6, prompt: 9, cached: 9, hit: 6, out: 8, cost: 8, spread: 0 },
2742
+ { model: 18, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 8, spread: 0 },
2743
+ { model: 14, steps: 5, prompt: 8, cached: 8, hit: 0, out: 7, cost: 0, spread: 0 }
2744
+ ];
2745
+ for (const layout of layouts) {
2746
+ const total = Object.values(layout).reduce((sum, column) => sum + column, 0) + Object.values(layout).filter((column) => column > 0).length - 1;
2747
+ if (total <= width)
2748
+ return layout;
2749
+ }
2750
+ return layouts[layouts.length - 1];
2751
+ }
2752
+ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
2753
+ const columns = modelColumns(width);
2754
+ const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
2755
+ const aligns = ["left", "right", "right", "right"];
2756
+ const header = ["model", "steps", "prompt", "cached"];
2757
+ if (columns.hit > 0) {
2758
+ widths.push(columns.hit);
2759
+ aligns.push("right");
2760
+ header.push("hit");
2761
+ }
2762
+ widths.push(columns.out);
2763
+ aligns.push("right");
2764
+ header.push("out");
2765
+ if (columns.cost > 0) {
2766
+ widths.push(columns.cost);
2767
+ aligns.push("right");
2768
+ header.push("cost");
2769
+ }
2770
+ if (columns.spread > 0) {
2771
+ widths.push(columns.spread);
2772
+ aligns.push("left");
2773
+ header.push("providers");
2774
+ }
2775
+ const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
2776
+ for (const model of rows.slice(0, limit)) {
2777
+ const key = modelKey(model.modelID, model.variant);
2778
+ const name = modelCell(model.modelID, model.variant, columns.model);
2779
+ const buckets = usageBuckets(model.totals);
2780
+ const providers = unique(model.providers.map((provider) => provider.providerID));
2781
+ const cache = extras?.cache?.get(key);
2782
+ const switches = extras?.switches?.get(key);
2783
+ const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
2784
+ if (columns.hit > 0)
2785
+ cells.push(formatPercent(cache?.hit ?? buckets.hit));
2786
+ cells.push(formatTokens(buckets.output));
2787
+ if (columns.cost > 0)
2788
+ cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
2789
+ if (columns.spread > 0)
2790
+ cells.push(providers.join(", "));
2791
+ lines.push({
2792
+ text: formatTableRow(cells, widths, aligns),
2793
+ tone: "base",
2794
+ row: { kind: "model", value: model.modelID, ...model.variant !== undefined ? { variant: model.variant } : {} }
2795
+ });
2796
+ const details = [];
2797
+ if (cache !== undefined)
2798
+ details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
2799
+ if (switches !== undefined && switches.changes > 0) {
2800
+ const scope = switches.providerChanges > 0 ? ` (${formatCount(switches.providerChanges)} provider)` : "";
2801
+ details.push(`${count(switches.changes, "switch", "switches")}${scope}`);
2802
+ if (switches.cacheLost > 0)
2803
+ details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
2804
+ }
2805
+ if (details.length > 0) {
2806
+ lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
2807
+ }
2808
+ }
2809
+ if (rows.length > limit)
2810
+ lines.push({ text: `\u2026 ${count(rows.length - limit, "more model")} \xB7 narrow the range or filter`, tone: "muted" });
2811
+ if (rows.length === 0)
2812
+ lines.push({ text: "no usage recorded for this range", tone: "muted" });
2813
+ return lines;
2814
+ }
2815
+ function unique(values) {
2816
+ return [...new Set(values)];
2817
+ }
2818
+ var tableWidth = (columns) => columns.reduce((sum, column) => sum + column.width, 0) + columns.length - 1;
2819
+ function fitColumns(columns, width) {
2820
+ const chosen = [...columns];
2821
+ while (chosen.length > 1 && tableWidth(chosen) > width) {
2822
+ const optional = [...chosen].reverse().findIndex((column) => column.optional === true);
2823
+ if (optional === -1)
2824
+ break;
2825
+ chosen.splice(chosen.length - 1 - optional, 1);
2826
+ }
2827
+ return chosen;
2828
+ }
2829
+ function renderTable(rows, columns, width, options) {
2830
+ const chosen = fitColumns(columns, width);
2831
+ const widths = chosen.map((column) => column.width);
2832
+ const aligns = chosen.map((column) => column.align ?? "left");
2833
+ const alignsTyped = aligns;
2834
+ const lines = [{ text: formatTableRow(chosen.map((column) => column.header), widths, alignsTyped), tone: HEADER_TONE }];
2835
+ if (rows.length === 0)
2836
+ lines.push({ text: options.empty, tone: "muted" });
2837
+ for (const row of rows.slice(0, options.limit)) {
2838
+ const identity = options.row?.(row);
2839
+ lines.push({
2840
+ text: formatTableRow(chosen.map((column) => column.cell(row)), widths, alignsTyped),
2841
+ tone: options.tone?.(row) ?? "base",
2842
+ ...identity === undefined ? {} : { row: identity }
2843
+ });
2844
+ }
2845
+ if (rows.length > options.limit)
2846
+ lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
2847
+ return lines;
2848
+ }
2849
+ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
2850
+ const lines = renderTable(rows, [
2851
+ { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
2852
+ { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
2853
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2854
+ { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2855
+ { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2856
+ { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2857
+ { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2858
+ { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2859
+ { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2860
+ { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2861
+ ], width, {
2862
+ limit,
2863
+ empty: "no usage recorded for this range",
2864
+ row: (row) => row.provider === undefined ? undefined : { kind: "provider", value: row.provider },
2865
+ tone: (row) => row.provider === undefined ? "muted" : "base"
2866
+ });
2867
+ return lines;
2868
+ }
2869
+ function providerLines(rows, width, limit = 40, estimates = true) {
2870
+ return renderTable(rows, [
2871
+ { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
2872
+ { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
2873
+ { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
2874
+ { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
2875
+ { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
2876
+ { header: "cached", width: 10, align: "right", cell: (row) => formatTokens(row.cache.cached) },
2877
+ { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
2878
+ { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
2879
+ { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
2880
+ { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
2881
+ ], width, {
2882
+ limit,
2883
+ empty: "no usage recorded for this range",
2884
+ row: (row) => ({ kind: "model", value: row.modelID, ...row.variant !== undefined ? { variant: row.variant } : {} }),
2885
+ tone: (row) => row.provider === undefined ? "muted" : "base"
2886
+ });
2887
+ }
2888
+ function cacheLines(data, width) {
2889
+ const lines = [];
2890
+ const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
2891
+ lines.push({ text: `reuse losses ${count(data.drops.length, "event")} \xB7 ${formatTokens(total)} tokens`, tone: total > 0 ? "warning" : "base" });
2892
+ for (const reason of ["expired", "compaction", "unknown"]) {
2893
+ const group = data.drops.filter((drop) => drop.reason === reason);
2894
+ if (group.length === 0)
2895
+ continue;
2896
+ const tokens = group.reduce((sum, drop) => sum + drop.tokens, 0);
2897
+ lines.push({ text: ` ${padCell(reason, 11)}${formatCount(group.length)} \xB7 ${formatTokens(tokens)}`, tone: reason === "expired" ? "warning" : "muted" });
2898
+ }
2899
+ if (data.drops.length === 0)
2900
+ lines.push({ text: " none: prompt cache held through every gap", tone: "muted" });
2901
+ if (data.models !== undefined && data.models.length > 0) {
2902
+ lines.push({ text: "", tone: "muted" });
2903
+ lines.push({ text: "reuse by model", tone: HEADER_TONE });
2904
+ const widths = width >= 100 ? [30, 7, 11, 10, 8, 8, 10] : [18, 6, 9, 9, 7, 7, 9];
2905
+ lines.push({ text: formatTableRow(["model", "steps", "prompt", "cached", "write", "hit", "hit p50"], widths, ["left", "right", "right", "right", "right", "right", "right"]), tone: "muted" });
2906
+ for (const row of data.models.slice(0, 10)) {
2907
+ const name = modelCell(row.usage.modelID, row.usage.variant, widths[0]);
2908
+ lines.push({
2909
+ text: formatTableRow([name, formatCount(row.cache.steps), formatTokens(row.cache.prompt), formatTokens(row.cache.cached), formatTokens(row.cache.cacheWrite), formatPercent(row.cache.hit), formatPercent(row.cache.hitP50)], widths, ["left", "right", "right", "right", "right", "right", "right"]),
2910
+ tone: "base",
2911
+ row: { kind: "model", value: row.usage.modelID, ...row.usage.variant !== undefined ? { variant: row.usage.variant } : {} }
2912
+ });
2913
+ }
2914
+ }
2915
+ if (data.gap !== undefined && data.gap.samples > 0) {
2916
+ lines.push({ text: "", tone: "muted" });
2917
+ lines.push({ text: "cache survival against idle time", tone: HEADER_TONE });
2918
+ const widths = [9, 8, 9, 9, 10];
2919
+ lines.push({ text: formatTableRow(["gap", "pairs", "kept", "drops", "lost"], widths, ["left", "right", "right", "right", "right"]), tone: "muted" });
2920
+ for (const bucket of data.gap.buckets) {
2921
+ if (bucket.samples === 0)
2922
+ continue;
2923
+ lines.push({
2924
+ text: formatTableRow([bucket.label, formatCount(bucket.samples), formatPercent(bucket.retainedRatio, 0), formatCount(bucket.drops), formatTokens(bucket.lostTokens)], widths, ["left", "right", "right", "right", "right"]),
2925
+ tone: bucket.drops > 0 ? "warning" : "base"
2926
+ });
2927
+ }
2928
+ if (data.gap.providers.length > 1) {
2929
+ lines.push({ text: "", tone: "muted" });
2930
+ lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
2931
+ const providerWidths = [26, 8, 9, 9];
2932
+ lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
2933
+ for (const row of data.gap.providers.slice(0, 8)) {
2934
+ lines.push({
2935
+ text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
2936
+ tone: "base"
2937
+ });
2938
+ }
2939
+ }
2940
+ }
2941
+ lines.push({ text: "", tone: "muted" });
2942
+ lines.push({ text: "observed cache TTL bounds", tone: HEADER_TONE });
2943
+ if (data.evidence.length === 0) {
2944
+ lines.push({ text: " no comparable step pairs yet", tone: "muted" });
2945
+ } else {
2946
+ const widths = [Math.max(18, Math.floor(width * 0.4)), 14, 12, 9];
2947
+ lines.push({ text: formatTableRow(["model", "hits up to", "drops from", "samples"], widths, ["left", "right", "right", "right"]), tone: "muted" });
2948
+ for (const row of data.evidence.slice(0, 10)) {
2949
+ lines.push({
2950
+ text: formatTableRow([`${row.providerID}/${row.modelID}`, formatGap(row.maxHitGapMs), formatGap(row.minDropGapMs), formatCount(row.samples)], widths, ["left", "right", "right", "right"]),
2951
+ tone: "base"
2952
+ });
2953
+ }
2954
+ }
2955
+ if (data.drops.length > 0) {
2956
+ lines.push({ text: "", tone: "muted" });
2957
+ lines.push({ text: "recent losses", tone: HEADER_TONE });
2958
+ for (const drop of [...data.drops].sort((a, b) => b.at - a.at).slice(0, 8)) {
2959
+ const when = new Date(drop.at).toLocaleTimeString("en-GB");
2960
+ lines.push({
2961
+ text: formatTableRow([when, `${drop.providerID ?? ""}/${drop.modelID ?? ""}`, `\u2212${formatTokens(drop.tokens)}`, `${formatGap(drop.gapMs)} idle \xB7 ${drop.reason}`], [10, Math.max(20, Math.floor(width * 0.42)), 10, 24], ["left", "left", "right", "left"]),
2962
+ tone: drop.reason === "expired" ? "warning" : "base"
2963
+ });
2964
+ }
2965
+ }
2966
+ return lines;
2967
+ }
2968
+ function periodLines(rows, width, granularity, limit = 40, estimates = true, totalSessions) {
2969
+ const lines = [];
2970
+ const totals = rows.reduce((sum, row) => {
2971
+ sum.steps += row.usage.steps;
2972
+ sum.sessions += row.sessions;
2973
+ sum.input += row.usage.input;
2974
+ sum.cached += row.usage.cached;
2975
+ sum.cacheWrite += row.usage.cacheWrite;
2976
+ sum.output += row.usage.output;
2977
+ sum.reasoning += row.usage.reasoning;
2978
+ sum.cost += row.usage.cost;
2979
+ sum.listCost += row.usage.listCost;
2980
+ return sum;
2981
+ }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
2982
+ const overall = usageBuckets(totals);
2983
+ lines.push({
2984
+ text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
2985
+ tone: "muted"
2986
+ });
2987
+ if (rows.length > 1) {
2988
+ lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
2989
+ lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
2990
+ lines.push({
2991
+ text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
2992
+ tone: "muted"
2993
+ });
2994
+ }
2995
+ const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
2996
+ const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
2997
+ const aligns = widths.map((_, index) => index === 0 ? "left" : "right");
2998
+ const header = withSessions ? ["period", "steps", "sess", "prompt", "cached", "hit", "out", "cost"] : ["period", "steps", "prompt", "cached", "hit", "out", "cost"];
2999
+ lines.push({ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE });
3000
+ const newest = [...rows].sort((left, right) => right.at - left.at).slice(0, limit);
3001
+ for (const row of newest) {
3002
+ const buckets = usageBuckets(row.usage);
3003
+ const cells = [
3004
+ row.label,
3005
+ formatCount(row.steps),
3006
+ ...withSessions ? [formatCount(row.sessions)] : [],
3007
+ formatTokens(buckets.prompt),
3008
+ formatTokens(buckets.cached),
3009
+ formatPercent(buckets.hit, 0),
3010
+ formatTokens(buckets.output),
3011
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3012
+ ];
3013
+ lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
3014
+ }
3015
+ lines.push({ text: "", tone: "muted" });
3016
+ lines.push({
3017
+ text: formatTableRow([
3018
+ "total",
3019
+ formatCount(totals.steps),
3020
+ ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
3021
+ formatTokens(overall.prompt),
3022
+ formatTokens(overall.cached),
3023
+ formatPercent(overall.hit, 0),
3024
+ formatTokens(overall.output),
3025
+ formatSpend(overall.cost, estimates ? overall.listCost : 0)
3026
+ ], widths, aligns),
3027
+ tone: HEADER_TONE
3028
+ });
3029
+ if (rows.length === 0)
3030
+ lines.push({ text: "no usage recorded for this range", tone: "muted" });
3031
+ return lines;
3032
+ }
3033
+ function latencyLines(report, width, groups, limit = 12, estimates = true) {
3034
+ const lines = [];
3035
+ lines.push({
3036
+ text: formatTableRow(["wall", "p50", formatMs(report.wall.p50), "p90", formatMs(report.wall.p90), "p99", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`], [10, 4, 9, 4, 9, 4, 9, 12]),
3037
+ tone: "base"
3038
+ });
3039
+ lines.push({
3040
+ text: formatTableRow(["stream", "p50", formatMs(report.stream.p50), "p90", formatMs(report.stream.p90), "p99", formatMs(report.stream.p99)], [10, 4, 9, 4, 9, 4, 9]),
3041
+ tone: "base"
3042
+ });
3043
+ lines.push({
3044
+ text: formatTableRow(["throughput", "p50", formatTps(report.tps.p50), "p90", formatTps(report.tps.p90), "p99", formatTps(report.tps.p99)], [10, 4, 9, 4, 9, 4, 9]),
3045
+ tone: "base"
3046
+ });
3047
+ lines.push({ text: "", tone: "muted" });
3048
+ lines.push({
3049
+ text: truncate("wall = request to completed \xB7 stream = request to last chunk \xB7 throughput = output+reasoning tokens/s", width),
3050
+ tone: "muted"
3051
+ });
3052
+ if (report.wall.count === 0)
3053
+ lines.push({ text: "no completed steps for this range", tone: "muted" });
3054
+ if (groups !== undefined && groups.length > 0) {
3055
+ lines.push({ text: "", tone: "muted" });
3056
+ lines.push({ text: "by group", tone: HEADER_TONE });
3057
+ const widths = width >= 110 ? [24, 6, 9, 9, 9, 9, 9, 9] : [16, 5, 8, 8, 8, 8, 8, 8];
3058
+ const aligns = ["left", "right", "right", "right", "right", "right", "right", "right"];
3059
+ lines.push({ text: formatTableRow(["group", "n", "wall p50", "wall p90", "stream", "tps p50", "tps p90", "cost"], widths, aligns), tone: "muted" });
3060
+ for (const row of groups.slice(0, limit)) {
3061
+ const thin = row.count < 5;
3062
+ lines.push({
3063
+ text: formatTableRow([
3064
+ row.label,
3065
+ formatCount(row.count),
3066
+ formatMs(row.wall.p50),
3067
+ formatMs(row.wall.p90),
3068
+ formatMs(row.stream.p50),
3069
+ formatTps(row.tps.p50),
3070
+ formatTps(row.tps.p90),
3071
+ formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
3072
+ ], widths, aligns),
3073
+ tone: thin ? "muted" : "base",
3074
+ row: { kind: "model", value: row.key }
3075
+ });
3076
+ }
3077
+ lines.push({ text: "n < 5 is dimmed: too few samples to compare", tone: "muted" });
3078
+ }
3079
+ return lines;
3080
+ }
3081
+ function sessionsLines(rows, width, options) {
3082
+ const limit = options?.limit ?? 20;
3083
+ const estimates = options?.estimates !== false;
3084
+ const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
3085
+ const aligns = ["left", "right", "right", "right", "right", "right", "right"];
3086
+ const lines = [
3087
+ { text: formatTableRow(["title", "steps", "prompt", "cached", "hit", "out", "cost"], widths, aligns), tone: HEADER_TONE }
3088
+ ];
3089
+ const byID = new Map(rows.map((row) => [row.sessionID, row]));
3090
+ const ordered = rows.filter((row) => row.parentID === undefined || !byID.has(row.parentID));
3091
+ const children = rows.filter((row) => row.parentID !== undefined && byID.has(row.parentID));
3092
+ const orderedAll = [...ordered, ...children];
3093
+ for (const row of orderedAll.slice(0, limit)) {
3094
+ const child = row.parentID !== undefined && byID.has(row.parentID);
3095
+ const title = truncate(row.title ?? row.sessionID, Math.max(8, widths[0] - (child ? 2 : 0)));
3096
+ const buckets = usageBuckets(row);
3097
+ lines.push({
3098
+ text: formatTableRow([
3099
+ `${child ? "\u21B3 " : ""}${title}`,
3100
+ formatCount(buckets.steps),
3101
+ formatTokens(buckets.prompt),
3102
+ formatTokens(buckets.cached),
3103
+ formatPercent(buckets.hit, 0),
3104
+ formatTokens(buckets.output),
3105
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
3106
+ ], widths, aligns),
3107
+ tone: child ? "muted" : "base",
3108
+ row: { kind: "session", value: row.sessionID }
3109
+ });
3110
+ const details = [
3111
+ row.directory ?? "",
3112
+ row.models.length > 1 ? count(row.models.length, "model") : "",
3113
+ (row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost)}` : ""
3114
+ ].filter((part) => part !== "").join(" \xB7 ");
3115
+ lines.push({ text: truncate(`${" ".repeat(child ? 2 : 0)} ${details}`, width), tone: "muted" });
3116
+ }
3117
+ if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {
3118
+ const share = rows.reduce((sum, row) => sum + row.steps, 0);
3119
+ lines.push({ text: "", tone: "muted" });
3120
+ lines.push({
3121
+ text: `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${formatSpend(options.rollup.subagentCost, estimates ? options.rollup.subagentListCost ?? 0 : 0)}`,
3122
+ tone: "muted"
3123
+ });
3124
+ }
3125
+ if (rows.length > limit)
3126
+ lines.push({ text: `\u2026 ${count(rows.length - limit, "more session")} \xB7 narrow the range`, tone: "muted" });
3127
+ if (rows.length === 0)
3128
+ lines.push({ text: "no sessions recorded for this range", tone: "muted" });
3129
+ return lines;
3130
+ }
3131
+ function dbLines(data, width) {
3132
+ const lines = [];
3133
+ const size = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
3134
+ lines.push({ text: truncate(data.info.path, width), tone: "base" });
3135
+ lines.push({
3136
+ text: `${size(data.info.bytes)}${data.info.walBytes === undefined ? "" : ` + ${size(data.info.walBytes)} wal`} \xB7 schema v${data.info.schemaVersion}`,
3137
+ tone: "muted"
3138
+ });
3139
+ lines.push({ text: "", tone: "muted" });
3140
+ lines.push({ text: "what it holds", tone: HEADER_TONE });
3141
+ for (const table of data.info.tables) {
3142
+ lines.push({ text: ` ${padCell(table.name, 12)}${formatCount(table.rows)} rows`, tone: table.rows === 0 ? "muted" : "base" });
3143
+ }
3144
+ lines.push({
3145
+ text: ` window ${data.info.firstAt === undefined ? "\u2013" : new Date(data.info.firstAt).toLocaleDateString("en-GB")} \u2192 ${data.info.lastAt === undefined ? "\u2013" : new Date(data.info.lastAt).toLocaleDateString("en-GB")}`,
3146
+ tone: "muted"
3147
+ });
3148
+ lines.push({ text: "", tone: "muted" });
3149
+ lines.push({ text: "clean up", tone: HEADER_TONE });
3150
+ lines.push({
3151
+ 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),
3152
+ tone: "muted",
3153
+ hint: true
3154
+ });
3155
+ if (data.estimates !== false) {
3156
+ lines.push({
3157
+ 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),
3158
+ tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
3159
+ });
3160
+ }
3161
+ const widths = [10, 13, 10];
3162
+ lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
3163
+ for (const option of data.info.removable) {
3164
+ const before = new Date(data.now - option.days * 24 * 60 * 60 * 1000).toLocaleDateString("en-GB");
3165
+ lines.push({
3166
+ text: formatTableRow([`${option.days} days`, `${formatCount(option.steps)} steps`, before], widths, ["left", "right", "left"]),
3167
+ tone: option.steps === 0 ? "muted" : "base",
3168
+ row: { kind: "prune", value: String(option.days) }
3169
+ });
3170
+ }
3171
+ const steps = data.info.tables.find((table) => table.name === "steps")?.rows ?? 0;
3172
+ const sessions = data.info.tables.find((table) => table.name === "sessions")?.rows ?? 0;
3173
+ lines.push({ text: "", tone: "muted" });
3174
+ lines.push({
3175
+ text: truncate(` wipe everything \xB7 ${formatCount(steps)} steps \xB7 ${formatCount(sessions)} sessions \xB7 cannot be undone`, width),
3176
+ tone: steps === 0 && sessions === 0 ? "muted" : "warning",
3177
+ row: { kind: "wipe", value: "all" }
3178
+ });
3179
+ if (data.busy === true) {
3180
+ lines.push({ text: "", tone: "muted" });
3181
+ lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
3182
+ }
3183
+ return lines;
3184
+ }
3185
+ function turnStats(turn) {
3186
+ return {
3187
+ endAt: turn.endAt,
3188
+ startAt: turn.promptAt ?? turn.endAt,
3189
+ promptAt: turn.promptAt,
3190
+ promptGapMs: turn.promptGapMs,
3191
+ providerID: turn.providerID,
3192
+ modelID: turn.modelID,
3193
+ variant: turn.variant,
3194
+ providerChanged: turn.providerChanged,
3195
+ modelChanged: turn.modelChanged,
3196
+ totals: turn.totals,
3197
+ latest: turn.latest,
3198
+ session: undefined,
3199
+ drops: turn.drops.map((drop) => ({ messageID: drop.messageID, tokens: drop.tokens, prevCached: 0, gapMs: drop.gapMs })),
3200
+ cacheDropTokens: turn.drops.reduce((sum, drop) => sum + drop.tokens, 0),
3201
+ cacheExpired: turn.drops.length > 0,
3202
+ steps: turn.steps
3203
+ };
3204
+ }
3205
+ function turnsLines(rows, width, options) {
3206
+ const lines = [];
3207
+ const warning = rows.filter((turn) => turn.drops.length > 0).length;
3208
+ lines.push({
3209
+ text: `${count(rows.length, "turn")} \xB7 newest first${warning > 0 ? ` \xB7 ${count(warning, "turn")} with a cache loss` : ""}`,
3210
+ tone: "muted"
3211
+ });
3212
+ const showSession = options?.sessionTitles !== undefined;
3213
+ for (const turn of rows) {
3214
+ const line = formatLine(turnStats(turn), {
3215
+ ...options,
3216
+ fields: { ...options?.fields, session: false }
3217
+ });
3218
+ const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
3219
+ lines.push({
3220
+ text: truncate(`${title}${line}`, width),
3221
+ tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
3222
+ row: { kind: "turn", value: turn.sessionID }
3223
+ });
3224
+ }
3225
+ if (rows.length === 0)
3226
+ lines.push({ text: "no finished turns for this range", tone: "muted" });
3227
+ return lines;
3228
+ }
3229
+ function sessionSummaryLines(usage, budget = 34, estimates = true) {
3230
+ const buckets = usageBuckets(usage);
3231
+ const steps = formatCount(buckets.steps);
3232
+ const input = formatTokens(buckets.input);
3233
+ const cached = formatTokens(buckets.cached);
3234
+ const out = formatTokens(buckets.output);
3235
+ const hit = formatPercent(buckets.hit);
3236
+ const tps = formatTpsCompact(usage.tps);
3237
+ const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
3238
+ const first = [
3239
+ ` ${steps} steps \xB7 in ${input}`,
3240
+ ` ${steps} steps`
3241
+ ].find((text) => text.length <= budget);
3242
+ const second = [
3243
+ ` cached ${cached} \xB7 out ${out}`,
3244
+ ` cached ${cached}`
3245
+ ].find((text) => text.length <= budget);
3246
+ const last = [
3247
+ ` hit ${hit} \xB7 ${tps} \xB7 ${cost}`,
3248
+ ` hit ${hit} \xB7 ${cost}`,
3249
+ ` ${cost}`
3250
+ ].find((text) => text.length <= budget);
3251
+ return [
3252
+ { text: truncate("session", budget), tone: HEADER_TONE },
3253
+ { text: truncate(first ?? ` ${steps} steps`, budget), tone: "muted" },
3254
+ { text: truncate(second ?? ` cached ${cached}`, budget), tone: "base" },
3255
+ { text: truncate(last ?? ` ${cost}`, budget), tone: "base" },
3256
+ { text: "", tone: "muted" }
3257
+ ];
3258
+ }
3259
+ function sidebarLines(rows, options) {
3260
+ const budget = options?.budget ?? 34;
3261
+ const labels = { input: options?.labels?.input ?? "in", output: options?.labels?.output ?? "out" };
3262
+ const lines = [];
3263
+ for (const [index, turn] of rows.entries()) {
3264
+ const clock = turn.endAt !== undefined ? formatClock(turn.endAt).slice(0, 5) : "--:--";
3265
+ const provider = turn.providerID ?? "unknown";
3266
+ const display = displayTotals(turn.latest);
3267
+ const input = formatTokens(display.input);
3268
+ const prompt = formatTokens(display.prompt);
3269
+ const output = formatTokens(display.output);
3270
+ const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
3271
+ const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
3272
+ const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
3273
+ const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
3274
+ const header = `${clock} ${provider}`;
3275
+ const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
3276
+ const volumes = [
3277
+ ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
3278
+ ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
3279
+ ` ${labels.input} ${input}`
3280
+ ];
3281
+ const facts = [
3282
+ ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`} \xB7 ${cost}${suffix}`,
3283
+ ` hit ${hit}${tps === undefined ? "" : ` \xB7 ${tps}`}${suffix}`,
3284
+ ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
3285
+ ` hit ${hit}${suffix}`
3286
+ ];
3287
+ lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
3288
+ const edge = index === 0 || index === rows.length - 1;
3289
+ if (edge || turn.modelChanged || turn.providerChanged) {
3290
+ const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
3291
+ lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
3292
+ }
3293
+ lines.push({
3294
+ text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
3295
+ tone: "muted"
3296
+ });
3297
+ lines.push({
3298
+ text: truncate(facts.find((text) => text.length <= budget) ?? facts[facts.length - 1], budget),
3299
+ tone: turn.drops.length > 0 ? "warning" : "muted"
3300
+ });
3301
+ }
3302
+ if (rows.length === 0)
3303
+ lines.push({ text: "no finished turns yet", tone: "muted" });
3304
+ return lines;
3305
+ }
3306
+
3307
+ // src/panel-build.ts
3308
+ function detailLabel(row) {
3309
+ switch (row.kind) {
3310
+ case "model":
3311
+ return `model ${row.variant !== undefined ? `${row.value} ${row.variant}` : row.value}`;
3312
+ case "session":
3313
+ case "turn":
3314
+ return `session ${row.value}`;
3315
+ case "period":
3316
+ return `period ${row.value}`;
3317
+ case "provider":
3318
+ return `provider ${row.value}`;
3319
+ case "prune":
3320
+ return `prune older than ${row.value} days`;
3321
+ case "wipe":
3322
+ return "wipe all recorded usage";
3323
+ }
3324
+ }
3325
+ function buildPanel(request) {
3326
+ try {
3327
+ return build(request);
3328
+ } catch (error) {
3329
+ const message = error instanceof Error ? error.message : String(error);
3330
+ return [{ text: `stats query failed: ${message}`, tone: "warning" }];
3331
+ }
3332
+ }
3333
+ function build(request) {
3334
+ const { db, view, now, sessionStart, width } = request;
3335
+ const estimates = request.estimates !== false;
3336
+ const scoped = request.range === "session" && request.sessionID !== "";
3337
+ const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
3338
+ const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
3339
+ if (request.detail !== undefined)
3340
+ return buildDetail(request, range, filters, estimates);
3341
+ switch (view) {
3342
+ case "overview": {
3343
+ const usage = overview(db, range, filters);
3344
+ const sessionUsage = request.sessionID === "" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID });
3345
+ const childIDs = request.sessionID === "" ? [] : childSessionIDs(db, request.sessionID);
3346
+ const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs);
3347
+ return overviewLines({
3348
+ usage,
3349
+ session: sessionUsage,
3350
+ ...children.length > 0 ? { subagents: children } : {},
3351
+ range: request.range,
3352
+ activity: activityOf(db, range, filters, now),
3353
+ coverage: coverageOf(db, { range, filters }),
3354
+ estimates
3355
+ }, width);
3356
+ }
3357
+ case "models": {
3358
+ const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
3359
+ const pairs = cachePairs(db, { range, filters });
3360
+ const switches = switchesOf(pairs);
3361
+ return modelsLines(rows, width, {
3362
+ cache: cacheByModel(pairs),
3363
+ switches: switchesByModel(switches.rows)
3364
+ }, 40, estimates);
3365
+ }
3366
+ case "providers":
3367
+ return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
3368
+ case "cache": {
3369
+ const pairs = cachePairs(db, { range, filters });
3370
+ return cacheLines({
3371
+ drops: cacheDropsOf(db, pairs),
3372
+ evidence: ttlEvidenceOf(pairs),
3373
+ gap: gapReportOf(pairs),
3374
+ models: topCacheModels(pairs)
3375
+ }, width);
3376
+ }
3377
+ case "periods": {
3378
+ const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters));
3379
+ const sessions = overview(db, range, filters).sessions;
3380
+ return periodLines(rows, width, request.granularity, 40, estimates, sessions);
3381
+ }
3382
+ case "latency": {
3383
+ const timings = timingRows(db, { range, filters });
3384
+ const by = filters.modelID !== undefined ? "provider" : "model";
3385
+ return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
3386
+ }
3387
+ case "sessions": {
3388
+ const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates);
3389
+ const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
3390
+ return sessionsLines(rows, width, {
3391
+ limit: 20,
3392
+ estimates,
3393
+ rollup: {
3394
+ subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),
3395
+ subagentCost: child.reduce((sum, row) => sum + row.cost, 0),
3396
+ subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0)
3397
+ }
3398
+ });
3399
+ }
3400
+ case "db":
3401
+ 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);
3402
+ case "turns": {
3403
+ const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
3404
+ const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
3405
+ const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
3406
+ return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
3407
+ }
3408
+ }
3409
+ }
3410
+ function rangeForRequest(key, now) {
3411
+ switch (key) {
3412
+ case "today": {
3413
+ const start = new Date(now);
3414
+ start.setHours(0, 0, 0, 0);
3415
+ return { from: start.getTime() };
3416
+ }
3417
+ case "7d":
3418
+ return { from: now - 7 * 24 * 60 * 60 * 1000 };
3419
+ case "30d":
3420
+ return { from: now - 30 * 24 * 60 * 60 * 1000 };
3421
+ default:
3422
+ return;
3423
+ }
3424
+ }
3425
+ function buildDetail(request, range, filters, estimates) {
3426
+ const row = request.detail;
3427
+ const db = request.db;
3428
+ const width = request.width;
3429
+ const head = { text: detailLabel(row), tone: "accent" };
3430
+ const back = { text: "backspace returns \xB7 the header shows where you came from", tone: "muted" };
3431
+ if (row.kind === "model") {
3432
+ const scoped = { ...filters, modelKey: modelKey(row.value, row.variant) };
3433
+ const stats = cacheStatsOf(db, { range, filters: scoped });
3434
+ const steps = stepRows(db, { range, filters: scoped });
3435
+ return [
3436
+ head,
3437
+ {
3438
+ text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 write ${formatTokens(stats.cacheWrite)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3439
+ tone: "muted"
3440
+ },
3441
+ { text: "", tone: "muted" },
3442
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3443
+ { text: "", tone: "muted" },
3444
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
3445
+ { text: "", tone: "muted" },
3446
+ back
3447
+ ];
3448
+ }
3449
+ if (row.kind === "session" || row.kind === "turn") {
3450
+ const rows = turns(db, { sessionID: row.value, limit: 80 });
3451
+ return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: "", tone: "muted" }, back];
3452
+ }
3453
+ if (row.kind === "provider") {
3454
+ const scoped = { ...filters, provider: row.value };
3455
+ const steps = stepRows(db, { range, filters: scoped });
3456
+ const stats = cacheStatsOf(db, { range, filters: scoped });
3457
+ return [
3458
+ head,
3459
+ {
3460
+ text: `steps ${stats.steps} \xB7 in ${formatTokens(stats.prompt - stats.cached)} \xB7 prompt ${formatTokens(stats.prompt)} \xB7 cached ${formatTokens(stats.cached)} \xB7 hit ${percent(stats.hit)} \xB7 p50 ${percent(stats.hitP50)}`,
3461
+ tone: "muted"
3462
+ },
3463
+ { text: "", tone: "muted" },
3464
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
3465
+ { text: "", tone: "muted" },
3466
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
3467
+ { text: "", tone: "muted" },
3468
+ back
3469
+ ];
3470
+ }
3471
+ if (row.kind === "period") {
3472
+ const periods = periodsOf(stepRows(db, { range, filters }), request.granularity);
3473
+ const period = periods.find((entry) => entry.key === row.value);
3474
+ const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at);
3475
+ const to = period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY);
3476
+ const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters });
3477
+ return [
3478
+ head,
3479
+ { text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
3480
+ { text: "", tone: "muted" },
3481
+ ...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),
3482
+ { text: "", tone: "muted" },
3483
+ back
3484
+ ];
3485
+ }
3486
+ return [head, back];
3487
+ }
3488
+ function percent(value) {
3489
+ return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
3490
+ }
3491
+ function sortModels(rows, sort, desc, estimates = true) {
3492
+ const sign = desc ? 1 : -1;
3493
+ const pick = (model) => {
3494
+ if (sort === "cached")
3495
+ return model.totals.cached;
3496
+ if (sort === "hit") {
3497
+ const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite;
3498
+ return prompt > 0 ? model.totals.cached / prompt : -1;
3499
+ }
3500
+ if (sort === "out")
3501
+ return model.totals.output + model.totals.reasoning;
3502
+ if (sort === "cost")
3503
+ return estimates ? spend(model.totals) : model.totals.cost;
3504
+ return model.totals.steps;
3505
+ };
3506
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3507
+ }
3508
+ function sortProviders(rows, sort, desc, estimates = true) {
3509
+ const sign = desc ? 1 : -1;
3510
+ const pick = (row) => {
3511
+ if (sort === "cached")
3512
+ return row.cache.cached;
3513
+ if (sort === "hit")
3514
+ return row.cache.hit ?? -1;
3515
+ if (sort === "cost")
3516
+ return estimates ? spend(row.usage) : row.usage.cost;
3517
+ if (sort === "share")
3518
+ return row.share;
3519
+ if (sort === "tps")
3520
+ return row.tps ?? -1;
3521
+ return row.usage.steps;
3522
+ };
3523
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3524
+ }
3525
+ function sortLatency(rows, sort, desc) {
3526
+ const sign = desc ? 1 : -1;
3527
+ const pick = (row) => {
3528
+ if (sort === "tps")
3529
+ return row.tps.p50 ?? -1;
3530
+ if (sort === "wall")
3531
+ return row.wall.p50 ?? -1;
3532
+ return row.count;
3533
+ };
3534
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3535
+ }
3536
+ function sortSessions(rows, sort, desc, estimates = true) {
3537
+ const sign = desc ? 1 : -1;
3538
+ const pick = (row) => {
3539
+ if (sort === "steps")
3540
+ return row.steps;
3541
+ if (sort === "cached")
3542
+ return row.cached;
3543
+ if (sort === "cost")
3544
+ return estimates ? spend(row) : row.cost;
3545
+ return row.lastAt ?? 0;
3546
+ };
3547
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3548
+ }
3549
+ function sortTurns(rows, sort, desc, estimates = true) {
3550
+ const sign = desc ? 1 : -1;
3551
+ const pick = (row) => {
3552
+ if (sort === "cost")
3553
+ return estimates ? spend(row.totals) : row.totals.cost;
3554
+ if (sort === "tokens")
3555
+ return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning;
3556
+ return row.endAt ?? 0;
3557
+ };
3558
+ return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
3559
+ }
3560
+ function cacheByModel(pairs) {
3561
+ const map = new Map;
3562
+ for (const row of cacheStatsByModel(pairs)) {
3563
+ map.set(modelKey(row.modelID, row.variant), row.cache);
3564
+ }
3565
+ return map;
3566
+ }
3567
+ function switchesByModel(rows) {
3568
+ return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]));
3569
+ }
3570
+ function topCacheModels(pairs) {
3571
+ return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
3572
+ }
3573
+ function activityOf(db, range, filters, now) {
3574
+ const filter = buildWhere(range, filters, STEP_TIME);
3575
+ const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params);
3576
+ const from = range?.from ?? earliest?.at ?? 0;
3577
+ const to = range?.to ?? now;
3578
+ const span = Math.max(1, to - from);
3579
+ const ladder = [3600000, 3 * 3600000, 6 * 3600000, 12 * 3600000, 86400000, 3 * 86400000, 7 * 86400000, 30 * 86400000];
3580
+ const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1];
3581
+ const rows = db.query(`SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps
3582
+ FROM steps ${filter.where}
3583
+ GROUP BY bucket ORDER BY bucket`).all(bucket, ...filter.params);
3584
+ if (rows.length === 0)
3585
+ return [];
3586
+ const first = Math.floor(from / bucket);
3587
+ const last = rows[rows.length - 1].bucket;
3588
+ const series = [];
3589
+ for (let index = first;index <= last; index += 1) {
3590
+ series.push(rows.find((row) => row.bucket === index)?.steps ?? 0);
3591
+ }
3592
+ return series;
3593
+ }
3594
+
3595
+ // src/stats/maintenance.ts
3596
+ import { statSync as statSync2 } from "fs";
3597
+ var STEP_TIME2 = "COALESCE(created_at, recorded_at)";
3598
+ var DAY = 24 * 60 * 60 * 1000;
3599
+ function size(path) {
3600
+ try {
3601
+ return statSync2(path).size;
3602
+ } catch {
3603
+ return 0;
3604
+ }
3605
+ }
3606
+ function hasTable(db, name) {
3607
+ try {
3608
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
3609
+ } catch {
3610
+ return false;
3611
+ }
3612
+ }
3613
+ function dbInfo(db, path, now = Date.now()) {
3614
+ const tables = TABLES.map((table) => ({
3615
+ name: table,
3616
+ rows: hasTable(db, table) ? db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n : 0
3617
+ }));
3618
+ const window = db.query(`SELECT MIN(${STEP_TIME2}) AS first, MAX(${STEP_TIME2}) AS last FROM steps`).get();
3619
+ const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
3620
+ return {
3621
+ path,
3622
+ unpriced: hasListCost(db) ? db.query(`SELECT COUNT(*) AS n FROM steps
3623
+ WHERE cost = 0 AND list_cost IS NULL
3624
+ AND provider_id IS NOT NULL AND provider_id <> ''
3625
+ AND model_id IS NOT NULL AND model_id <> ''
3626
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n : 0,
3627
+ bytes: size(path),
3628
+ walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
3629
+ schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
3630
+ tables,
3631
+ firstAt: window.first ?? undefined,
3632
+ lastAt: window.last ?? undefined,
3633
+ removable: [30, 90, 365].map((days) => ({
3634
+ days,
3635
+ steps: db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${STEP_TIME2} < ?`).get(now - days * DAY).n
3636
+ }))
3637
+ };
3638
+ }
3639
+ var PRUNE_BATCH = 5000;
3640
+ function deleteBatched(db, table, where, cutoff) {
3641
+ const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`);
3642
+ let removed = 0;
3643
+ for (;; ) {
3644
+ const changes = statement.run(cutoff).changes;
3645
+ removed += changes;
3646
+ if (changes < PRUNE_BATCH)
3647
+ break;
3648
+ }
3649
+ return removed;
3650
+ }
3651
+ function deleteAllBatched(db, table) {
3652
+ const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} LIMIT ${PRUNE_BATCH})`);
3653
+ let removed = 0;
3654
+ for (;; ) {
3655
+ const changes = statement.run().changes;
3656
+ removed += changes;
3657
+ if (changes < PRUNE_BATCH)
3658
+ break;
3659
+ }
3660
+ return removed;
3661
+ }
3662
+ function pruneOlderThan(db, cutoff) {
3663
+ return {
3664
+ steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
3665
+ prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
3666
+ events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
3667
+ usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
3668
+ };
3669
+ }
3670
+ function wipeAll(db) {
3671
+ return {
3672
+ steps: deleteAllBatched(db, "steps"),
3673
+ prompts: deleteAllBatched(db, "prompts"),
3674
+ events: deleteAllBatched(db, "events"),
3675
+ usage: hasTable(db, "usage") ? deleteAllBatched(db, "usage") : 0,
3676
+ sessions: hasTable(db, "sessions") ? deleteAllBatched(db, "sessions") : 0
3677
+ };
3678
+ }
3679
+ function footprint(path) {
3680
+ return size(path) + size(`${path}-wal`);
3681
+ }
3682
+ function vacuum(db, path) {
3683
+ const before = footprint(path);
3684
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
3685
+ db.exec("VACUUM");
3686
+ const after = footprint(path);
3687
+ return { before, after, freed: Math.max(0, before - after) };
3688
+ }
3689
+ function hasListCost(db) {
3690
+ try {
3691
+ return db.query("PRAGMA table_info(steps)").all().some((column) => column.name === "list_cost");
3692
+ } catch {
3693
+ return false;
3694
+ }
3695
+ }
3696
+ var BACKFILL_BATCH = 1000;
3697
+ function backfillListCost(db, price) {
3698
+ if (!hasListCost(db))
3699
+ return { candidates: 0, updated: 0 };
3700
+ const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
3701
+ WHERE cost = 0 AND list_cost IS NULL
3702
+ AND provider_id IS NOT NULL AND provider_id <> ''
3703
+ AND model_id IS NOT NULL AND model_id <> ''
3704
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
3705
+ if (candidates === 0)
3706
+ return { candidates: 0, updated: 0 };
3707
+ const select = db.query(`SELECT rowid, provider_id, model_id,
3708
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3709
+ FROM steps
3710
+ WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
3711
+ AND provider_id IS NOT NULL AND provider_id <> ''
3712
+ AND model_id IS NOT NULL AND model_id <> ''
3713
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
3714
+ ORDER BY rowid
3715
+ LIMIT ?`);
3716
+ const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
3717
+ let cursor = 0;
3718
+ let updated = 0;
3719
+ for (;; ) {
3720
+ const rows = select.all(cursor, BACKFILL_BATCH);
3721
+ if (rows.length === 0)
3722
+ break;
3723
+ db.transaction(() => {
3724
+ for (const row of rows) {
3725
+ const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
3726
+ input: row.input_tokens ?? 0,
3727
+ output: row.output_tokens ?? 0,
3728
+ reasoning: row.reasoning_tokens ?? 0,
3729
+ cacheRead: row.cache_read ?? 0,
3730
+ cacheWrite: row.cache_write ?? 0
3731
+ });
3732
+ if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
3733
+ continue;
3734
+ if (update.run(estimate, row.rowid).changes > 0)
3735
+ updated += 1;
3736
+ }
3737
+ })();
3738
+ cursor = rows[rows.length - 1].rowid;
3739
+ if (rows.length < BACKFILL_BATCH)
3740
+ break;
3741
+ }
3742
+ return { candidates, updated };
3743
+ }
3744
+
3745
+ // src/service.ts
3746
+ var DAY2 = 24 * 60 * 60 * 1000;
3747
+ var MAX_DAYS = 3650;
3748
+
3749
+ class ServiceError extends Error {
3750
+ code;
3751
+ constructor(code, message) {
3752
+ super(message);
3753
+ this.name = "ServiceError";
3754
+ this.code = code;
3755
+ }
3756
+ }
3757
+ function clamp(value, minimum, maximum) {
3758
+ if (!Number.isFinite(value))
3759
+ return minimum;
3760
+ return Math.min(maximum, Math.max(minimum, Math.round(value)));
3761
+ }
3762
+ function sessionStart(db, sessionID) {
3763
+ const session = db.query("SELECT started_at AS at FROM sessions WHERE session_id = ?").get(sessionID);
3764
+ if (session?.at !== null && session?.at !== undefined)
3765
+ return session.at;
3766
+ const step = db.query("SELECT MIN(COALESCE(created_at, recorded_at)) AS at FROM steps WHERE session_id = ?").get(sessionID);
3767
+ return step?.at ?? undefined;
3768
+ }
3769
+ function redact(info, exposePaths) {
3770
+ if (exposePaths)
3771
+ return info;
3772
+ return { ...info, path: basename(info.path) };
3773
+ }
3774
+ function filtersOf(settings) {
3775
+ return {
3776
+ ...settings.modelID !== "" ? { modelID: settings.modelID } : {},
3777
+ ...settings.providerID !== "" ? { provider: settings.providerID } : {}
3778
+ };
3779
+ }
3780
+ function writeDb(path, run) {
3781
+ let db;
3782
+ try {
3783
+ db = openStatsDbWrite(path);
3784
+ return run(db);
3785
+ } catch (error) {
3786
+ if (error instanceof ServiceError)
3787
+ throw error;
3788
+ throw new ServiceError("busy", "the database is busy; try again in a moment");
3789
+ } finally {
3790
+ db?.close();
3791
+ }
3792
+ }
3793
+ function createService(db, options) {
3794
+ const settingsOf = (input) => sanitizeSettings(input.settings);
3795
+ function infoOf() {
3796
+ return redact(dbInfo(db(), options.path), options.exposePaths);
3797
+ }
3798
+ function panel(input) {
3799
+ const settings = settingsOf(input);
3800
+ const database = settings.view === "db" ? infoOf() : undefined;
3801
+ const width = clampPanelWidth(input.width);
3802
+ const filters = filtersOf(settings);
3803
+ const request = {
3804
+ db: db(),
3805
+ view: settings.view,
3806
+ range: settings.range,
3807
+ filters,
3808
+ granularity: settings.granularity,
3809
+ turnsScope: settings.turnsScope,
3810
+ sort: settings.sort === "" ? defaultSort(settings.view) : settings.sort,
3811
+ sortDesc: settings.sortDesc,
3812
+ sessionID: input.sessionID,
3813
+ sessionStart: sessionStart(db(), input.sessionID),
3814
+ now: Date.now(),
3815
+ format: { ...options.format, estimates: options.pricing },
3816
+ estimates: options.pricing,
3817
+ ...input.detail !== undefined ? { detail: input.detail } : {},
3818
+ ...database !== undefined ? { database } : {},
3819
+ busy: input.busy === true,
3820
+ width
3821
+ };
3822
+ return { lines: buildPanel(request), ...database !== undefined ? { database } : {} };
3823
+ }
3824
+ function turnHistory(input) {
3825
+ const handle = db();
3826
+ const width = clamp(input.width, 20, 120);
3827
+ const limit = clampTurnsLimit(input.limit);
3828
+ const summary = sessionSummaryLines(overview(handle, undefined, { sessionID: input.sessionID }), width, options.pricing);
3829
+ const history = sidebarLines(turns(handle, { sessionID: input.sessionID, limit }), {
3830
+ ...options.format,
3831
+ estimates: options.pricing,
3832
+ budget: width
3833
+ });
3834
+ return { summary, history };
3835
+ }
3836
+ function listCost(input) {
3837
+ if (!options.pricing)
3838
+ return { cost: 0 };
3839
+ return { cost: sessionListCost(db(), input.sessionID) };
3840
+ }
3841
+ function filters() {
3842
+ return filterOptions(db());
3843
+ }
3844
+ function requireMaintenance() {
3845
+ if (!options.maintenance)
3846
+ throw new ServiceError("disabled", "database maintenance is disabled");
3847
+ }
3848
+ function requireConfirm(confirm) {
3849
+ if (confirm !== true)
3850
+ throw new ServiceError("invalid", "confirmation is required");
3851
+ }
3852
+ function prune(input) {
3853
+ requireMaintenance();
3854
+ requireConfirm(input.confirm);
3855
+ const days = clamp(input.days, 1, MAX_DAYS);
3856
+ return writeDb(options.path, (handle) => pruneOlderThan(handle, Date.now() - days * DAY2));
3857
+ }
3858
+ function wipe(input) {
3859
+ requireMaintenance();
3860
+ requireConfirm(input.confirm);
3861
+ return writeDb(options.path, (handle) => wipeAll(handle));
3862
+ }
3863
+ function compact(input) {
3864
+ requireMaintenance();
3865
+ requireConfirm(input.confirm);
3866
+ return writeDb(options.path, (handle) => vacuum(handle, options.path));
3867
+ }
3868
+ function backfill(input, table) {
3869
+ if (!options.pricing)
3870
+ throw new ServiceError("disabled", "list-price estimates are turned off");
3871
+ requireMaintenance();
3872
+ requireConfirm(input.confirm);
3873
+ const prices = table ?? options.priceTable?.();
3874
+ if (prices === undefined)
3875
+ throw new ServiceError("unavailable", "the model catalog is unavailable");
3876
+ return writeDb(options.path, (handle) => backfillListCost(handle, (ref, tokens) => costOf(prices, ref, tokens)));
3877
+ }
3878
+ return {
3879
+ panel,
3880
+ turnHistory,
3881
+ listCost,
3882
+ filters,
3883
+ dbInfo: infoOf,
3884
+ prune,
3885
+ wipe,
3886
+ compact,
3887
+ backfill
3888
+ };
3889
+ }
3890
+
3891
+ // src/stats-client.ts
3892
+ import { existsSync } from "fs";
3893
+ import { fileURLToPath } from "url";
3894
+
3895
+ class StatsError extends Error {
3896
+ code;
3897
+ constructor(code, message) {
3898
+ super(message);
3899
+ this.name = "StatsError";
3900
+ this.code = code;
3901
+ }
3902
+ }
3903
+ var QUEUE_LIMIT = 8;
3904
+ var READ_TIMEOUT_MS = 1e4;
3905
+ var MAINTENANCE_TIMEOUT_MS = 5 * 60000;
3906
+ var START_TIMEOUT_MS = 5000;
3907
+ var MAINTENANCE_METHODS = new Set(["prune", "wipe", "vacuum", "backfill"]);
3908
+ function defaultWorkerUrl() {
3909
+ try {
3910
+ const js = new URL("./stats-worker.js", import.meta.url);
3911
+ if (existsSync(fileURLToPath(js)))
3912
+ return js;
3913
+ const ts = new URL("./stats-worker.ts", import.meta.url);
3914
+ if (existsSync(fileURLToPath(ts)))
3915
+ return ts;
3916
+ } catch {}
3917
+ return;
3918
+ }
3919
+
3920
+ class StatsClient {
3921
+ config;
3922
+ worker;
3923
+ startPromise;
3924
+ starting;
3925
+ startAbort;
3926
+ fallbackService;
3927
+ fallbackMode = false;
3928
+ stopped = false;
3929
+ nextID = 1;
3930
+ pending = new Map;
3931
+ constructor(config) {
3932
+ this.config = config;
3933
+ }
3934
+ request(method, input, options = {}) {
3935
+ if (this.stopped)
3936
+ return Promise.reject(new StatsError("unavailable", "the usage service is stopped"));
3937
+ if (this.fallbackMode)
3938
+ return Promise.resolve().then(() => this.callService(method, input));
3939
+ return this.ensureWorker().then(() => {
3940
+ if (this.stopped)
3941
+ throw new StatsError("unavailable", "the usage service is stopped");
3942
+ if (this.fallbackMode)
3943
+ return this.callService(method, input);
3944
+ if (this.pending.size >= QUEUE_LIMIT)
3945
+ throw new StatsError("busy", "too many usage requests are already running");
3946
+ return this.send(method, input, options.signal);
3947
+ });
3948
+ }
3949
+ stop() {
3950
+ if (this.stopped)
3951
+ return;
3952
+ this.stopped = true;
3953
+ this.rejectAll(new StatsError("unavailable", "the usage service stopped"));
3954
+ this.startAbort?.();
3955
+ this.worker?.terminate();
3956
+ this.worker = undefined;
3957
+ this.starting = undefined;
3958
+ this.startPromise = undefined;
3959
+ }
3960
+ callService(method, input) {
3961
+ const service = this.fallbackService ??= this.config.fallback();
3962
+ switch (method) {
3963
+ case "panel":
3964
+ return service.panel(input);
3965
+ case "turns":
3966
+ return service.turnHistory(input);
3967
+ case "listCost":
3968
+ return service.listCost(input);
3969
+ case "filters":
3970
+ return service.filters();
3971
+ case "dbInfo":
3972
+ return service.dbInfo();
3973
+ case "prune":
3974
+ return service.prune(input);
3975
+ case "wipe":
3976
+ return service.wipe(input);
3977
+ case "vacuum":
3978
+ return service.compact(input);
3979
+ case "backfill":
3980
+ return service.backfill(input, this.config.priceTable?.());
3981
+ }
3982
+ }
3983
+ ensureWorker() {
3984
+ if (this.worker !== undefined)
3985
+ return Promise.resolve();
3986
+ if (this.startPromise !== undefined)
3987
+ return this.startPromise;
3988
+ const url = this.config.workerUrl?.() ?? defaultWorkerUrl();
3989
+ if (url === undefined) {
3990
+ this.useFallback("the worker entrypoint was not found");
3991
+ return Promise.resolve();
3992
+ }
3993
+ const ctor = globalThis.Worker;
3994
+ if (ctor === undefined) {
3995
+ this.useFallback("this runtime has no worker support");
3996
+ return Promise.resolve();
3997
+ }
3998
+ this.startPromise = new Promise((resolve) => {
3999
+ let settled = false;
4000
+ let worker;
4001
+ try {
4002
+ worker = new ctor(url);
4003
+ } catch (error) {
4004
+ this.useFallback(error instanceof Error ? error.message : "the usage worker could not be created");
4005
+ resolve();
4006
+ return;
4007
+ }
4008
+ this.starting = worker;
4009
+ let timer;
4010
+ const finish = (ok, reason) => {
4011
+ if (settled)
4012
+ return;
4013
+ settled = true;
4014
+ if (timer !== undefined)
4015
+ clearTimeout(timer);
4016
+ this.startPromise = undefined;
4017
+ this.starting = undefined;
4018
+ this.startAbort = undefined;
4019
+ if (this.stopped) {
4020
+ worker.terminate();
4021
+ this.worker = undefined;
4022
+ resolve();
4023
+ return;
4024
+ }
4025
+ if (!ok) {
4026
+ worker.terminate();
4027
+ this.useFallback(reason ?? "the usage worker did not start");
4028
+ }
4029
+ resolve();
4030
+ };
4031
+ this.startAbort = () => finish(false, "the usage service stopped");
4032
+ timer = setTimeout(() => finish(false, "the usage worker did not start in time"), this.config.timeouts?.start ?? START_TIMEOUT_MS);
4033
+ worker.onmessage = (event) => {
4034
+ const message = event.data;
4035
+ if (message?.type === "ready") {
4036
+ if (settled) {
4037
+ worker.terminate();
4038
+ return;
4039
+ }
4040
+ this.worker = worker;
4041
+ this.attach(worker);
4042
+ finish(true);
4043
+ return;
4044
+ }
4045
+ if (message?.type === "error") {
4046
+ finish(false, message.error?.message ?? "the usage worker failed to start");
4047
+ }
4048
+ };
4049
+ worker.onerror = (event) => {
4050
+ finish(false, event.message || "the usage worker failed to start");
4051
+ };
4052
+ try {
4053
+ worker.postMessage({ type: "init", dbPath: this.config.dbPath, options: this.config.options });
4054
+ } catch (error) {
4055
+ finish(false, error instanceof Error ? error.message : "the usage worker could not be initialized");
4056
+ }
4057
+ });
4058
+ return this.startPromise;
4059
+ }
4060
+ attach(worker) {
4061
+ worker.onmessage = (event) => this.receive(event.data);
4062
+ worker.onerror = (event) => {
4063
+ this.config.log?.(`usage worker failed: ${event.message}`);
4064
+ this.worker = undefined;
4065
+ this.rejectAll(new StatsError("unavailable", "the usage worker stopped"));
4066
+ };
4067
+ }
4068
+ receive(message) {
4069
+ if (message === null || typeof message !== "object")
4070
+ return;
4071
+ const payload = message;
4072
+ if (typeof payload.id !== "number")
4073
+ return;
4074
+ const pending = this.pending.get(payload.id);
4075
+ if (pending === undefined)
4076
+ return;
4077
+ this.settle(payload.id, pending);
4078
+ if (payload.ok === true) {
4079
+ pending.resolve(payload.result);
4080
+ return;
4081
+ }
4082
+ const code = payload.error?.code ?? "unavailable";
4083
+ pending.reject(new StatsError(code, payload.error?.message ?? "the usage request failed"));
4084
+ }
4085
+ timeoutFor(method) {
4086
+ if (MAINTENANCE_METHODS.has(method)) {
4087
+ return this.config.timeouts?.maintenance ?? MAINTENANCE_TIMEOUT_MS;
4088
+ }
4089
+ return this.config.timeouts?.read ?? READ_TIMEOUT_MS;
4090
+ }
4091
+ send(method, input, signal) {
4092
+ const worker = this.worker;
4093
+ if (worker === undefined)
4094
+ throw new StatsError("unavailable", "the usage worker is not running");
4095
+ const id = this.nextID++;
4096
+ const prices = method === "backfill" ? this.config.priceTable?.() : undefined;
4097
+ return new Promise((resolve, reject) => {
4098
+ const pending = {
4099
+ resolve,
4100
+ reject,
4101
+ timer: setTimeout(() => {
4102
+ this.settle(id, pending);
4103
+ pending.reject(new StatsError("unavailable", "the usage request timed out"));
4104
+ this.hardReset("the usage request timed out");
4105
+ }, this.timeoutFor(method))
4106
+ };
4107
+ if (signal !== undefined) {
4108
+ if (signal.aborted) {
4109
+ clearTimeout(pending.timer);
4110
+ reject(new StatsError("unavailable", "the usage request was cancelled"));
4111
+ return;
4112
+ }
4113
+ const abort = () => {
4114
+ this.settle(id, pending);
4115
+ reject(new StatsError("unavailable", "the usage request was cancelled"));
4116
+ };
4117
+ signal.addEventListener("abort", abort, { once: true });
4118
+ pending.removeAbort = () => signal.removeEventListener("abort", abort);
4119
+ }
4120
+ this.pending.set(id, pending);
4121
+ try {
4122
+ worker.postMessage({
4123
+ id,
4124
+ method,
4125
+ input,
4126
+ ...prices !== undefined ? { prices: [...prices.entries()] } : {}
4127
+ });
4128
+ } catch {
4129
+ this.settle(id, pending);
4130
+ pending.reject(new StatsError("unavailable", "the usage worker stopped"));
4131
+ }
4132
+ });
4133
+ }
4134
+ settle(id, pending) {
4135
+ clearTimeout(pending.timer);
4136
+ pending.removeAbort?.();
4137
+ this.pending.delete(id);
4138
+ }
4139
+ rejectAll(error) {
4140
+ for (const [id, pending] of this.pending) {
4141
+ this.settle(id, pending);
4142
+ pending.reject(error);
4143
+ }
4144
+ }
4145
+ hardReset(message) {
4146
+ this.config.log?.(message);
4147
+ this.rejectAll(new StatsError("unavailable", message));
4148
+ this.worker?.terminate();
4149
+ this.worker = undefined;
4150
+ this.starting?.terminate();
4151
+ this.starting = undefined;
4152
+ this.startPromise = undefined;
4153
+ }
4154
+ useFallback(reason) {
4155
+ this.fallbackMode = true;
4156
+ this.config.log?.(`usage worker unavailable, using the in-process service: ${reason}`);
4157
+ }
4158
+ }
4159
+
1550
4160
  // src/index.ts
1551
4161
  var PRICE_TTL_MS = 5 * 60 * 1000;
1552
4162
  var PRICE_RETRY_MS = 30 * 1000;
4163
+ var RECORDED_EVENTS = new Set([
4164
+ "session.created",
4165
+ "session.renamed",
4166
+ "session.moved",
4167
+ "session.inbox.enqueued",
4168
+ "session.step.ended",
4169
+ "session.step.failed",
4170
+ "session.usage.recorded",
4171
+ "session.compaction.ended"
4172
+ ]);
1553
4173
  function createPriceSource(ctx) {
1554
4174
  let table;
1555
4175
  let refreshing = false;
@@ -1579,6 +4199,7 @@ function createPriceSource(ctx) {
1579
4199
  refresh();
1580
4200
  return table === undefined ? undefined : costOf(table, ref, tokens);
1581
4201
  },
4202
+ table: () => table,
1582
4203
  refresh
1583
4204
  };
1584
4205
  }
@@ -1589,21 +4210,115 @@ function tryOpen(path) {
1589
4210
  return;
1590
4211
  }
1591
4212
  }
4213
+ function rpcFailure(context, error) {
4214
+ if (error instanceof StatsError || error instanceof ServiceError)
4215
+ return context.error(error.code, error.message);
4216
+ return context.error("unavailable", "the usage database is unavailable");
4217
+ }
1592
4218
  var src_default = Plugin.define({
1593
4219
  id: "usage-insights",
1594
4220
  async setup(ctx) {
1595
4221
  const options = ctx.options ?? {};
1596
4222
  if (options.enabled === false)
1597
4223
  return;
1598
- const db = tryOpen(resolveDbPath(options.db));
4224
+ const path = resolveDbPath(options.db);
4225
+ const db = tryOpen(path);
1599
4226
  if (db === undefined)
1600
4227
  return;
1601
4228
  try {
1602
4229
  db.exec("PRAGMA busy_timeout = 1000");
1603
4230
  } catch {}
1604
4231
  const pricing = options.pricing !== "off";
4232
+ const maintenance = options.maintenance !== false;
4233
+ const exposePaths = options.exposePaths === true;
1605
4234
  const source = pricing ? createPriceSource(ctx) : undefined;
1606
4235
  source?.refresh(true);
4236
+ const format = {
4237
+ ...options.labels !== undefined ? { labels: options.labels } : {},
4238
+ ...options.fields !== undefined ? { fields: options.fields } : {},
4239
+ ...options.turnTotals !== undefined ? { turnTotals: options.turnTotals } : {}
4240
+ };
4241
+ const serviceOptions = { pricing, maintenance, exposePaths, format };
4242
+ const stats = new StatsClient({
4243
+ dbPath: path,
4244
+ options: serviceOptions,
4245
+ priceTable: () => source?.table(),
4246
+ fallback: () => createService(() => db, {
4247
+ ...serviceOptions,
4248
+ path,
4249
+ priceTable: () => source?.table()
4250
+ }),
4251
+ log: (message) => console.warn(`[usage-insights] ${message}`)
4252
+ });
4253
+ const registration = await ctx.rpc.register(UsageInsights, {
4254
+ panel: async (input, context) => {
4255
+ try {
4256
+ return await stats.request("panel", input);
4257
+ } catch (error) {
4258
+ return rpcFailure(context, error);
4259
+ }
4260
+ },
4261
+ turns: async (input, context) => {
4262
+ try {
4263
+ return await stats.request("turns", input);
4264
+ } catch (error) {
4265
+ return rpcFailure(context, error);
4266
+ }
4267
+ },
4268
+ listCost: async (input, context) => {
4269
+ try {
4270
+ return await stats.request("listCost", input);
4271
+ } catch (error) {
4272
+ return rpcFailure(context, error);
4273
+ }
4274
+ },
4275
+ filters: async (_input, context) => {
4276
+ try {
4277
+ return await stats.request("filters", {});
4278
+ } catch (error) {
4279
+ return rpcFailure(context, error);
4280
+ }
4281
+ },
4282
+ dbInfo: async (_input, context) => {
4283
+ try {
4284
+ return await stats.request("dbInfo", {});
4285
+ } catch (error) {
4286
+ return rpcFailure(context, error);
4287
+ }
4288
+ },
4289
+ prune: async (input, context) => {
4290
+ try {
4291
+ return await stats.request("prune", input);
4292
+ } catch (error) {
4293
+ return rpcFailure(context, error);
4294
+ }
4295
+ },
4296
+ wipe: async (input, context) => {
4297
+ try {
4298
+ return await stats.request("wipe", input);
4299
+ } catch (error) {
4300
+ return rpcFailure(context, error);
4301
+ }
4302
+ },
4303
+ vacuum: async (input, context) => {
4304
+ try {
4305
+ return await stats.request("vacuum", input);
4306
+ } catch (error) {
4307
+ return rpcFailure(context, error);
4308
+ }
4309
+ },
4310
+ backfill: async (input, context) => {
4311
+ try {
4312
+ return await stats.request("backfill", input);
4313
+ } catch (error) {
4314
+ return rpcFailure(context, error);
4315
+ }
4316
+ }
4317
+ }).catch((error) => {
4318
+ stats.stop();
4319
+ db.close();
4320
+ throw error;
4321
+ });
1607
4322
  const recorder = createRecorder(db, source === undefined ? undefined : { price: source.price });
1608
4323
  const abort = new AbortController;
1609
4324
  const stream = (async () => {
@@ -1613,13 +4328,20 @@ var src_default = Plugin.define({
1613
4328
  if (event.type === "model.updated")
1614
4329
  source?.refresh(true);
1615
4330
  recorder.handleEvent(event);
4331
+ if (RECORDED_EVENTS.has(event.type)) {
4332
+ const data = event.data;
4333
+ const sessionID = typeof data?.sessionID === "string" ? data.sessionID : undefined;
4334
+ registration.events.emit("recorded", { at: Date.now(), ...sessionID !== undefined ? { sessionID } : {} }).catch(() => {});
4335
+ }
1616
4336
  } catch {}
1617
4337
  }
1618
4338
  } catch {}
1619
4339
  })();
1620
4340
  return async () => {
1621
4341
  abort.abort();
4342
+ await registration.dispose();
1622
4343
  await stream;
4344
+ stats.stop();
1623
4345
  db.close();
1624
4346
  };
1625
4347
  }
@@ -1628,4 +4350,4 @@ export {
1628
4350
  src_default as default
1629
4351
  };
1630
4352
 
1631
- //# debugId=54D17612579BB39464756E2164756E21
4353
+ //# debugId=15B300D932EB268164756E2164756E21