opencode-usage-insights 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tui.js CHANGED
@@ -5,7 +5,7 @@ import { createElement as _$createElement3 } from "@opentui/solid";
5
5
  import { createComponent as _$createComponent3 } from "@opentui/solid";
6
6
  import { Plugin } from "@opencode/plugin/tui";
7
7
  import { StyledText, fg } from "@opentui/core";
8
- import { Show, createMemo as createMemo3, createRenderEffect as createRenderEffect2, createSignal as createSignal2 } from "solid-js";
8
+ import { Show as Show3, createEffect as createEffect3, createMemo as createMemo3, createRenderEffect as createRenderEffect2, createSignal as createSignal3 } from "solid-js";
9
9
 
10
10
  // src/core.ts
11
11
  var PROMPT_BOUNDARIES = new Set(["user", "synthetic", "system"]);
@@ -31,14 +31,23 @@ function transcriptTail(messages, count) {
31
31
  segments.unshift({ assistants: current, prompt: undefined });
32
32
  return segments;
33
33
  }
34
+ function countOf(value) {
35
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
36
+ }
37
+ function amountOf(value) {
38
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
39
+ }
40
+ function stampOf(value) {
41
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
42
+ }
34
43
  function tokenCounts(message) {
35
44
  const tokens = message.tokens;
36
45
  return {
37
- input: tokens?.input ?? 0,
38
- output: tokens?.output ?? 0,
39
- reasoning: tokens?.reasoning ?? 0,
40
- read: tokens?.cache?.read ?? 0,
41
- write: tokens?.cache?.write ?? 0
46
+ input: countOf(tokens?.input),
47
+ output: countOf(tokens?.output),
48
+ reasoning: countOf(tokens?.reasoning),
49
+ read: countOf(tokens?.cache?.read),
50
+ write: countOf(tokens?.cache?.write)
42
51
  };
43
52
  }
44
53
  function totalize(steps) {
@@ -50,8 +59,8 @@ function totalize(steps) {
50
59
  totals.output += counts.output;
51
60
  totals.reasoning += counts.reasoning;
52
61
  totals.cacheWrite += counts.write;
53
- totals.cost += step.cost ?? 0;
54
- totals.listCost += step.listCost ?? 0;
62
+ totals.cost += amountOf(step.cost);
63
+ totals.listCost += amountOf(step.listCost);
55
64
  }
56
65
  return totals;
57
66
  }
@@ -61,16 +70,16 @@ function identityKey(model) {
61
70
  return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
62
71
  }
63
72
  function cacheRead(message) {
64
- return message?.tokens?.cache?.read ?? 0;
73
+ return countOf(message?.tokens?.cache?.read);
65
74
  }
66
75
  function stepCreated(message) {
67
- return message?.time?.created;
76
+ return stampOf(message?.time?.created);
68
77
  }
69
78
  function stepEnd(message) {
70
79
  const time = message?.time;
71
80
  if (!time)
72
81
  return;
73
- return time.completed ?? time.streamed ?? time.created;
82
+ return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
74
83
  }
75
84
  function cacheDrop(reference, current, scope = "provider") {
76
85
  if (!reference)
@@ -97,9 +106,9 @@ function stepGap(reference, current) {
97
106
  return Math.max(0, started - ended);
98
107
  }
99
108
  function tokensPerSecond(produced, from, to) {
100
- if (from === undefined || to === undefined || to <= from)
109
+ if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
101
110
  return;
102
- if (produced <= 0)
111
+ if (!Number.isFinite(produced) || produced <= 0)
103
112
  return;
104
113
  return produced / (to - from) * 1000;
105
114
  }
@@ -143,7 +152,7 @@ function computeTurn(messages, session) {
143
152
  return {
144
153
  endAt: stepEnd(lastStep),
145
154
  startAt: stepCreated(settled[0] ?? lastStep),
146
- promptAt: last.prompt?.time?.created,
155
+ promptAt: stampOf(last.prompt?.time?.created),
147
156
  promptGapMs: promptGap(last.prompt, previous?.prompt),
148
157
  providerID: provider,
149
158
  modelID: lastStep.model?.id,
@@ -160,8 +169,8 @@ function computeTurn(messages, session) {
160
169
  };
161
170
  }
162
171
  function promptGap(current, previous) {
163
- const now = current?.time?.created;
164
- const before = previous?.time?.created;
172
+ const now = stampOf(current?.time?.created);
173
+ const before = stampOf(previous?.time?.created);
165
174
  if (now === undefined || before === undefined)
166
175
  return;
167
176
  return Math.max(0, now - before);
@@ -199,11 +208,15 @@ var DEFAULT_FIELDS = {
199
208
  cacheExpiry: true
200
209
  };
201
210
  function formatClock(ms) {
211
+ if (!Number.isFinite(ms))
212
+ return "--:--";
202
213
  const date = new Date(ms);
203
214
  const pad = (value) => String(value).padStart(2, "0");
204
215
  return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
205
216
  }
206
217
  function formatDuration(ms) {
218
+ if (!Number.isFinite(ms))
219
+ return "\u2013";
207
220
  const totalSeconds = Math.max(0, Math.floor(ms / 1000));
208
221
  const seconds = totalSeconds % 60;
209
222
  const minutes = Math.floor(totalSeconds / 60) % 60;
@@ -218,7 +231,7 @@ function formatDuration(ms) {
218
231
  return `${seconds}s`;
219
232
  }
220
233
  function formatTokens(value) {
221
- const n = Math.max(0, Math.round(value));
234
+ const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
222
235
  if (n < 1000)
223
236
  return String(n);
224
237
  if (n < 999500) {
@@ -235,8 +248,10 @@ function trimZeros(value) {
235
248
  return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
236
249
  }
237
250
  function formatCost(value) {
238
- if (value <= 0)
251
+ if (!Number.isFinite(value) || value <= 0)
239
252
  return "$0";
253
+ if (value < 0.00005)
254
+ return "<$0.0001";
240
255
  if (value < 1)
241
256
  return `$${value.toFixed(4)}`;
242
257
  return `$${value.toFixed(2)}`;
@@ -336,6 +351,20 @@ function formatLine(stats, options) {
336
351
  return formatLineSegments(stats, options).map((segment) => segment.text).join(" \xB7 ");
337
352
  }
338
353
 
354
+ // src/limits.ts
355
+ var MAX_PANEL_WIDTH = 200;
356
+ var MAX_TURNS = 50;
357
+ function clampPanelWidth(value) {
358
+ if (!Number.isFinite(value))
359
+ return 20;
360
+ return Math.min(MAX_PANEL_WIDTH, Math.max(20, Math.round(value)));
361
+ }
362
+ function clampTurnsLimit(value) {
363
+ if (!Number.isFinite(value))
364
+ return 1;
365
+ return Math.min(MAX_TURNS, Math.max(1, Math.round(value)));
366
+ }
367
+
339
368
  // src/text.ts
340
369
  var TEXT_LIMIT = 512;
341
370
  function sanitizeText(value, limit = TEXT_LIMIT) {
@@ -429,18 +458,24 @@ function toModelRef(model) {
429
458
  return { providerID: model.providerID, id: model.id };
430
459
  return { providerID: model.providerID, id: model.id, variant: model.variant };
431
460
  }
461
+ function countOf2(value) {
462
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
463
+ }
464
+ function amountOf2(value) {
465
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
466
+ }
432
467
  function sessionTotals(info, listCost = 0) {
433
468
  if (info === undefined)
434
469
  return;
435
470
  const tokens = info.tokens;
436
471
  return {
437
- input: tokens?.input ?? 0,
438
- cached: tokens?.cache?.read ?? 0,
439
- output: tokens?.output ?? 0,
440
- reasoning: tokens?.reasoning ?? 0,
441
- cacheWrite: tokens?.cache?.write ?? 0,
442
- cost: info.cost ?? 0,
443
- listCost,
472
+ input: countOf2(tokens?.input),
473
+ cached: countOf2(tokens?.cache?.read),
474
+ output: countOf2(tokens?.output),
475
+ reasoning: countOf2(tokens?.reasoning),
476
+ cacheWrite: countOf2(tokens?.cache?.write),
477
+ cost: amountOf2(info.cost),
478
+ listCost: amountOf2(listCost),
444
479
  steps: 0
445
480
  };
446
481
  }
@@ -470,6 +505,66 @@ function sessionListCost(db, sessionID) {
470
505
  const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
471
506
  return row?.listCost ?? 0;
472
507
  }
508
+ var EMPTY_OTHER = { entries: 0, cost: 0 };
509
+ function hasUsageTable(db) {
510
+ try {
511
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'").get() !== null;
512
+ } catch {
513
+ return false;
514
+ }
515
+ }
516
+ function otherWhere(range, filters) {
517
+ if (filters?.modelID !== undefined && filters.modelID !== "")
518
+ return;
519
+ if (filters?.modelKey !== undefined && filters.modelKey !== "")
520
+ return;
521
+ if (filters?.provider !== undefined && filters.provider !== "")
522
+ return;
523
+ const span = rangeWhere(range, "at");
524
+ const clauses = span.where === "" ? [] : [span.where.slice("WHERE ".length)];
525
+ const params = [...span.params];
526
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
527
+ clauses.push("session_id = ?");
528
+ params.push(filters.sessionID);
529
+ }
530
+ return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
531
+ }
532
+ function otherUsage(db, range, filters) {
533
+ const filter = otherWhere(range, filters);
534
+ if (filter === undefined || !hasUsageTable(db))
535
+ return { ...EMPTY_OTHER };
536
+ try {
537
+ const row = db.query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`).get(...filter.params);
538
+ return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 };
539
+ } catch {
540
+ return { ...EMPTY_OTHER };
541
+ }
542
+ }
543
+ function otherUsageBySession(db, range, filters) {
544
+ const out = new Map;
545
+ const filter = otherWhere(range, filters);
546
+ if (filter === undefined || !hasUsageTable(db))
547
+ return out;
548
+ try {
549
+ const rows = db.query(`SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost
550
+ FROM usage ${filter.where}
551
+ GROUP BY session_id`).all(...filter.params);
552
+ for (const row of rows)
553
+ out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 });
554
+ } catch {}
555
+ return out;
556
+ }
557
+ function otherUsageRows(db, range, filters) {
558
+ const filter = otherWhere(range, filters);
559
+ if (filter === undefined || !hasUsageTable(db))
560
+ return [];
561
+ const where = filter.where === "" ? "WHERE at IS NOT NULL" : `${filter.where} AND at IS NOT NULL`;
562
+ try {
563
+ return db.query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`).all(...filter.params);
564
+ } catch {
565
+ return [];
566
+ }
567
+ }
473
568
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
474
569
  var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
475
570
  function modelKey(modelID, variant) {
@@ -547,12 +642,22 @@ function overview(db, range, filters) {
547
642
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
548
643
  FROM steps ${steps.where}`).get(...steps.params);
549
644
  const prompts = rangeWhere(range, "created_at");
550
- const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${prompts.where}`).get(...prompts.params);
645
+ const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
646
+ const promptParams = [...prompts.params];
647
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
648
+ promptClauses.push("session_id = ?");
649
+ promptParams.push(filters.sessionID);
650
+ }
651
+ const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
652
+ const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
551
653
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
654
+ const other = otherUsage(db, range, filters);
552
655
  return {
553
656
  ...usage,
657
+ cost: usage.cost + other.cost,
554
658
  sessions: row?.sessions ?? 0,
555
659
  prompts: promptRow?.prompts ?? 0,
660
+ otherCost: other.cost,
556
661
  firstAt: row?.firstAt ?? undefined,
557
662
  lastAt: row?.lastAt ?? undefined,
558
663
  cacheHitRatio: cacheHitRatio(usage),
@@ -603,7 +708,7 @@ function addUsage(target, source) {
603
708
  target.listCost += source.listCost;
604
709
  }
605
710
  function billedTokens(usage) {
606
- return usage.input + usage.cached + usage.output;
711
+ return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning;
607
712
  }
608
713
  function percentile(values, p) {
609
714
  if (values.length === 0)
@@ -629,6 +734,17 @@ function sessions(db, options) {
629
734
  const limit = options?.limit ?? 20;
630
735
  const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
631
736
  const params = [...filter.params];
737
+ const promptRange = [];
738
+ const promptParams = [];
739
+ if (range?.from !== undefined) {
740
+ promptRange.push("p.created_at >= ?");
741
+ promptParams.push(range.from);
742
+ }
743
+ if (range?.to !== undefined) {
744
+ promptRange.push("p.created_at < ?");
745
+ promptParams.push(range.to);
746
+ }
747
+ const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(" AND ")}` : "";
632
748
  if (options?.sessionIDs !== undefined) {
633
749
  const ids = options.sessionIDs.slice(0, 500);
634
750
  clauses.push(`st.session_id IN (${ids.map(() => "?").join(", ")})`);
@@ -637,7 +753,7 @@ function sessions(db, options) {
637
753
  const rows = db.query(`SELECT st.session_id, s.title, s.directory, s.parent_id,
638
754
  GROUP_CONCAT(DISTINCT st.provider_id) AS providers,
639
755
  GROUP_CONCAT(DISTINCT st.model_id) AS models,
640
- (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id) AS prompts,
756
+ (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,
641
757
  COUNT(*) AS steps,
642
758
  COALESCE(SUM(st.input_tokens), 0) AS input,
643
759
  COALESCE(SUM(st.cache_read), 0) AS cached,
@@ -653,11 +769,14 @@ function sessions(db, options) {
653
769
  ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
654
770
  GROUP BY st.session_id
655
771
  ORDER BY last_at DESC
656
- LIMIT ?`).all(...params, limit);
772
+ LIMIT ?`).all(...promptParams, ...params, limit);
773
+ const other = otherUsageBySession(db, range, options?.filters);
657
774
  return rows.map((row) => {
658
775
  const usage = usageFrom(row);
776
+ const extra = other.get(row.session_id)?.cost ?? 0;
659
777
  return {
660
778
  ...usage,
779
+ cost: usage.cost + extra,
661
780
  sessionID: row.session_id,
662
781
  parentID: row.parent_id ?? undefined,
663
782
  title: row.title ?? undefined,
@@ -665,6 +784,7 @@ function sessions(db, options) {
665
784
  providers: row.providers ? row.providers.split(",").filter(Boolean) : [],
666
785
  models: row.models ? row.models.split(",").filter(Boolean) : [],
667
786
  prompts: row.prompts ?? 0,
787
+ otherCost: extra,
668
788
  firstAt: row.first_at ?? undefined,
669
789
  lastAt: row.last_at ?? undefined,
670
790
  cacheHitRatio: cacheHitRatio(usage)
@@ -708,118 +828,134 @@ function stepMessage(row) {
708
828
  };
709
829
  }
710
830
  function turns(db, options) {
711
- const limit = options?.limit ?? 50;
831
+ const requested = options?.limit ?? 50;
832
+ const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50;
712
833
  const filter = buildWhere(options?.range, options?.filters);
713
- const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
714
- const params = [...filter.params];
834
+ const baseClauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
835
+ const baseParams = [...filter.params];
715
836
  if (options?.sessionID !== undefined) {
716
- clauses.push("session_id = ?");
717
- params.push(options.sessionID);
718
- }
719
- const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, limit + 1);
720
- if (floor !== undefined) {
721
- clauses.push(`${STEP_TIME} >= ?`);
722
- params.push(floor);
723
- }
724
- const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
725
- input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
726
- created_at, streamed_at, recorded_at, completed_at, finish
727
- FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
728
- ORDER BY session_id, ${STEP_TIME}`).all(...params);
729
- const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
730
- const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
731
- const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
732
- const promptsBySession = new Map;
733
- for (const row of promptRows) {
734
- if (row.created_at === null)
735
- continue;
736
- const list = promptsBySession.get(row.session_id) ?? [];
737
- list.push(row.created_at);
738
- promptsBySession.set(row.session_id, list);
739
- }
740
- const result = [];
741
- let sessionID;
742
- let bucket = [];
743
- let promptIndex = -2;
744
- let promptAt;
745
- let previousPromptAt;
746
- function close() {
747
- const last = bucket[bucket.length - 1];
748
- if (last === undefined || !turnFinished(last.finish)) {
837
+ baseClauses.push("session_id = ?");
838
+ baseParams.push(options.sessionID);
839
+ }
840
+ function read(promptCount) {
841
+ const clauses = [...baseClauses];
842
+ const params = [...baseParams];
843
+ const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount);
844
+ if (floor !== undefined) {
845
+ clauses.push(`${STEP_TIME} >= ?`);
846
+ params.push(floor);
847
+ }
848
+ const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
849
+ input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
850
+ created_at, streamed_at, recorded_at, completed_at, finish
851
+ FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
852
+ ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
853
+ const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
854
+ const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
855
+ const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
856
+ const promptsBySession = new Map;
857
+ for (const row of promptRows) {
858
+ if (row.created_at === null)
859
+ continue;
860
+ const list = promptsBySession.get(row.session_id) ?? [];
861
+ list.push(row.created_at);
862
+ promptsBySession.set(row.session_id, list);
863
+ }
864
+ const result = [];
865
+ let sessionID;
866
+ let bucket = [];
867
+ let promptIndex = -2;
868
+ let promptAt;
869
+ function close() {
870
+ const last = bucket[bucket.length - 1];
871
+ if (last === undefined || !turnFinished(last.finish)) {
872
+ bucket = [];
873
+ return;
874
+ }
875
+ const totals = emptyUsage();
876
+ for (const row of bucket)
877
+ addUsage(totals, stepUsage(row));
878
+ const drops = [];
879
+ let reference;
880
+ for (const row of bucket) {
881
+ const message = stepMessage(row);
882
+ const drop = cacheDrop(reference, message);
883
+ if (drop !== undefined) {
884
+ drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
885
+ }
886
+ reference = message;
887
+ }
888
+ const providerID = last.provider_id ?? undefined;
889
+ const modelID = last.model_id ?? undefined;
890
+ const variant = last.variant ?? undefined;
891
+ let produced = 0;
892
+ let window = 0;
893
+ for (const row of bucket) {
894
+ if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
895
+ continue;
896
+ produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
897
+ window += row.streamed_at - row.created_at;
898
+ }
899
+ const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
900
+ const endAt = last.completed_at ?? last.created_at ?? last.recorded_at;
901
+ const firstAt = bucket[0]?.created_at ?? promptAt;
902
+ result.push({
903
+ sessionID: last.session_id,
904
+ promptAt,
905
+ endAt,
906
+ durationMs: firstAt !== undefined && endAt > firstAt ? endAt - firstAt : undefined,
907
+ promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
908
+ providerID,
909
+ modelID,
910
+ variant,
911
+ providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
912
+ modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
913
+ steps: bucket.length,
914
+ latest: stepUsage(last),
915
+ totals,
916
+ drops,
917
+ finish: last.finish ?? undefined,
918
+ tps: tokensPerSecond(produced, 0, window)
919
+ });
749
920
  bucket = [];
750
- return;
751
921
  }
752
- const totals = emptyUsage();
753
- for (const row of bucket)
754
- addUsage(totals, stepUsage(row));
755
- const drops = [];
756
- let reference;
757
- for (const row of bucket) {
758
- const message = stepMessage(row);
759
- const drop = cacheDrop(reference, message);
760
- if (drop !== undefined) {
761
- drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
922
+ for (const row of steps) {
923
+ if (row.session_id !== sessionID) {
924
+ close();
925
+ sessionID = row.session_id;
926
+ promptIndex = -2;
927
+ promptAt = undefined;
762
928
  }
763
- reference = message;
764
- }
765
- const providerID = last.provider_id ?? undefined;
766
- const modelID = last.model_id ?? undefined;
767
- const variant = last.variant ?? undefined;
768
- let produced = 0;
769
- let window = 0;
770
- for (const row of bucket) {
771
- if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
772
- continue;
773
- produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
774
- window += row.streamed_at - row.created_at;
775
- }
776
- const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
777
- result.push({
778
- sessionID: last.session_id,
779
- promptAt,
780
- endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
781
- promptGapMs: promptAt !== undefined && previousPromptAt !== undefined ? Math.max(0, promptAt - previousPromptAt) : undefined,
782
- providerID,
783
- modelID,
784
- variant,
785
- providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
786
- modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
787
- steps: bucket.length,
788
- latest: stepUsage(last),
789
- totals,
790
- drops,
791
- finish: last.finish ?? undefined,
792
- tps: tokensPerSecond(produced, 0, window)
793
- });
794
- bucket = [];
795
- }
796
- for (const row of steps) {
797
- if (row.session_id !== sessionID) {
798
- close();
799
- sessionID = row.session_id;
800
- promptIndex = -2;
801
- promptAt = undefined;
802
- previousPromptAt = undefined;
803
- }
804
- const time = row.created_at ?? row.recorded_at;
805
- const prompts = promptsBySession.get(row.session_id) ?? [];
806
- let index = -1;
807
- for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
808
- if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
809
- index = candidate;
810
- break;
929
+ const time = row.created_at ?? row.recorded_at;
930
+ const prompts = promptsBySession.get(row.session_id) ?? [];
931
+ let index = -1;
932
+ for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
933
+ if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
934
+ index = candidate;
935
+ break;
936
+ }
811
937
  }
938
+ if (index !== promptIndex) {
939
+ close();
940
+ promptIndex = index;
941
+ promptAt = index >= 0 ? prompts[index] : undefined;
942
+ }
943
+ bucket.push(row);
812
944
  }
813
- if (index !== promptIndex) {
814
- close();
815
- promptIndex = index;
816
- promptAt = index >= 0 ? prompts[index] : undefined;
817
- previousPromptAt = index >= 1 ? prompts[index - 1] : undefined;
818
- }
819
- bucket.push(row);
945
+ close();
946
+ const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
947
+ return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
948
+ }
949
+ let promptCount = Math.max(1, limit + 1);
950
+ for (;; ) {
951
+ const { rows, complete } = read(promptCount);
952
+ if (rows.length >= limit || complete)
953
+ return rows.slice(0, limit);
954
+ const next = promptCount * 2 + 1;
955
+ if (!Number.isFinite(next) || next <= promptCount)
956
+ return rows.slice(0, limit);
957
+ promptCount = next;
820
958
  }
821
- close();
822
- return result.reverse().slice(0, limit);
823
959
  }
824
960
  function promptFloor(db, sessionID, count) {
825
961
  const rows = db.query("SELECT created_at FROM prompts WHERE session_id = ? AND created_at IS NOT NULL ORDER BY created_at DESC LIMIT ?").all(sessionID, count);
@@ -835,6 +971,28 @@ var PANEL_NAME = "usage-insights";
835
971
  var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
836
972
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
837
973
  var GRANULARITIES = ["day", "week", "month"];
974
+ var SORT_KEYS = {
975
+ models: ["steps", "cached", "hit", "out", "cost"],
976
+ providers: ["steps", "cached", "hit", "cost", "share", "tps"],
977
+ latency: ["n", "tps", "wall"],
978
+ sessions: ["last", "steps", "cached", "cost"],
979
+ turns: ["time", "cost", "tokens"]
980
+ };
981
+ function sortKeys(view) {
982
+ return SORT_KEYS[view] ?? [];
983
+ }
984
+ function defaultSort(view) {
985
+ return sortKeys(view)[0] ?? "";
986
+ }
987
+ function nextSort(view, current, step) {
988
+ const keys = sortKeys(view);
989
+ if (keys.length === 0)
990
+ return current;
991
+ const index = keys.indexOf(current);
992
+ if (index === -1)
993
+ return keys[0];
994
+ return keys[(index + step + keys.length) % keys.length];
995
+ }
838
996
  function parseArgs(input) {
839
997
  const parsed = {};
840
998
  for (const token of (input ?? "").split(/\s+/)) {
@@ -892,38 +1050,44 @@ function sanitizeSettings(raw) {
892
1050
  };
893
1051
  }
894
1052
  function formatPercent(value, digits = 1) {
895
- return value === undefined ? "\u2013" : `${(value * 100).toFixed(digits)}%`;
1053
+ if (value === undefined || !Number.isFinite(value))
1054
+ return "\u2013";
1055
+ return `${(value * 100).toFixed(digits)}%`;
896
1056
  }
897
1057
  function formatCount(value) {
898
- return Math.round(value).toLocaleString("en-US");
1058
+ return Number.isFinite(value) ? Math.round(value).toLocaleString("en-US") : "\u2013";
899
1059
  }
900
1060
  function formatMs(value) {
901
- if (value === undefined)
1061
+ if (value === undefined || !Number.isFinite(value))
902
1062
  return "\u2013";
903
- if (value < 1000)
904
- return `${Math.round(value)}ms`;
905
- if (value < 60000)
906
- return `${(value / 1000).toFixed(1)}s`;
907
- return formatDuration(value);
1063
+ const ms = Math.max(0, value);
1064
+ if (ms < 1000)
1065
+ return `${Math.round(ms)}ms`;
1066
+ if (ms < 60000)
1067
+ return `${(ms / 1000).toFixed(1)}s`;
1068
+ return formatDuration(ms);
908
1069
  }
909
1070
  function formatTps(value) {
910
- return value === undefined ? "\u2013" : `${value.toFixed(1)}/s`;
1071
+ if (value === undefined || !Number.isFinite(value) || value < 0)
1072
+ return "\u2013";
1073
+ return `${value.toFixed(1)}/s`;
911
1074
  }
912
1075
  function formatTpsCompact(value) {
913
- if (value === undefined)
1076
+ if (value === undefined || !Number.isFinite(value) || value < 0)
914
1077
  return "\u2013";
915
1078
  return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
916
1079
  }
917
1080
  function formatGap(value) {
918
- if (value === undefined)
1081
+ if (value === undefined || !Number.isFinite(value))
919
1082
  return "\u2013";
920
- if (value < 60000)
921
- return `${Math.round(value / 1000)}s`;
922
- if (value < 3600000)
923
- return `${Math.round(value / 60000)}m`;
924
- if (value < 86400000)
925
- return `${(value / 3600000).toFixed(1)}h`;
926
- return `${(value / 86400000).toFixed(1)}d`;
1083
+ const gap = Math.max(0, value);
1084
+ if (gap < 60000)
1085
+ return `${Math.round(gap / 1000)}s`;
1086
+ if (gap < 3600000)
1087
+ return `${Math.round(gap / 60000)}m`;
1088
+ if (gap < 86400000)
1089
+ return `${(gap / 3600000).toFixed(1)}h`;
1090
+ return `${(gap / 86400000).toFixed(1)}d`;
927
1091
  }
928
1092
  function truncate(value, width) {
929
1093
  if (width <= 1)
@@ -1045,7 +1209,7 @@ function viewBar(view, width = 200) {
1045
1209
  }
1046
1210
  function keysFor(of) {
1047
1211
  if (of === "db")
1048
- return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 e backfill estimates \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
1212
+ return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 the last row wipes \xB7 e backfill \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
1049
1213
  if (of === "periods")
1050
1214
  return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1051
1215
  if (of === "turns")
@@ -1086,6 +1250,8 @@ function helpLines(width) {
1086
1250
  { text: " out everything generated: visible output + reasoning" },
1087
1251
  { text: " reasoning part of `out`" },
1088
1252
  { text: " cost money, not tokens: a turn sums every step; $0 is left out" },
1253
+ { text: " other compaction/title usage: money with no assistant step;" },
1254
+ { text: " overview, periods and sessions include it; model rows do not" },
1089
1255
  { text: " \u2248 list-price estimate for steps the host reported as $0;" },
1090
1256
  { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
1091
1257
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
@@ -1102,8 +1268,8 @@ function helpLines(width) {
1102
1268
  { text: "" },
1103
1269
  { text: "database", tone: HEADER_TONE },
1104
1270
  { text: " the db view shows where the file lives, what it holds and how much" },
1105
- { text: " of it is old: \u2191\u2193 pick a retention, enter prunes from its cutoff date," },
1106
- { text: " e backfills list estimates, v gives the space back" },
1271
+ { text: " of it is old: \u2191\u2193 pick a retention or wipe, enter asks before it" },
1272
+ { text: " deletes, e backfills list estimates, v gives the space back" },
1107
1273
  { text: " local time \xB7 SQLite in the OpenCode state directory" }
1108
1274
  ];
1109
1275
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
@@ -1124,6 +1290,9 @@ function usagePairs(usage, estimates = true) {
1124
1290
  if (buckets.reasoning > 0)
1125
1291
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
1126
1292
  pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
1293
+ const other = usage.otherCost ?? 0;
1294
+ if (other > 0)
1295
+ pairs.push(["other", `${formatCost(other)} comp/title`]);
1127
1296
  if ("tps" in usage && usage.tps !== undefined)
1128
1297
  pairs.push(["tps", formatTps(usage.tps)]);
1129
1298
  return pairs;
@@ -1413,7 +1582,7 @@ function cacheLines(data, width) {
1413
1582
  }
1414
1583
  return lines;
1415
1584
  }
1416
- function periodLines(rows, width, granularity, limit = 40, estimates = true) {
1585
+ function periodLines(rows, width, granularity, limit = 40, estimates = true, totalSessions) {
1417
1586
  const lines = [];
1418
1587
  const totals = rows.reduce((sum, row) => {
1419
1588
  sum.steps += row.usage.steps;
@@ -1465,7 +1634,7 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true) {
1465
1634
  text: formatTableRow([
1466
1635
  "total",
1467
1636
  formatCount(totals.steps),
1468
- ...withSessions ? [formatCount(totals.sessions)] : [],
1637
+ ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
1469
1638
  formatTokens(overall.prompt),
1470
1639
  formatTokens(overall.cached),
1471
1640
  formatPercent(overall.hit, 0),
@@ -1555,7 +1724,11 @@ function sessionsLines(rows, width, options) {
1555
1724
  tone: child ? "muted" : "base",
1556
1725
  row: { kind: "session", value: row.sessionID }
1557
1726
  });
1558
- const details = [row.directory ?? "", row.models.length > 1 ? count(row.models.length, "model") : ""].filter((part) => part !== "").join(" \xB7 ");
1727
+ const details = [
1728
+ row.directory ?? "",
1729
+ row.models.length > 1 ? count(row.models.length, "model") : "",
1730
+ (row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost)}` : ""
1731
+ ].filter((part) => part !== "").join(" \xB7 ");
1559
1732
  lines.push({ text: truncate(`${" ".repeat(child ? 2 : 0)} ${details}`, width), tone: "muted" });
1560
1733
  }
1561
1734
  if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {
@@ -1591,10 +1764,14 @@ function dbLines(data, width) {
1591
1764
  });
1592
1765
  lines.push({ text: "", tone: "muted" });
1593
1766
  lines.push({ text: "clean up", tone: HEADER_TONE });
1594
- lines.push({ text: truncate(" \u2191\u2193 pick a retention \xB7 enter prunes the steps older than it (asks first) \xB7 v gives the space back", width), tone: "muted" });
1767
+ lines.push({
1768
+ text: truncate(` \u2191\u2193 pick a retention \xB7 enter prunes from its cutoff \xB7 the wipe row deletes everything (asks first)${data.estimates === false ? "" : " \xB7 e backfills list estimates"} \xB7 v gives the space back`, width),
1769
+ tone: "muted",
1770
+ hint: true
1771
+ });
1595
1772
  if (data.estimates !== false) {
1596
1773
  lines.push({
1597
- text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price \xB7 e retries`, width),
1774
+ text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price`, width),
1598
1775
  tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
1599
1776
  });
1600
1777
  }
@@ -1608,6 +1785,14 @@ function dbLines(data, width) {
1608
1785
  row: { kind: "prune", value: String(option.days) }
1609
1786
  });
1610
1787
  }
1788
+ const steps = data.info.tables.find((table) => table.name === "steps")?.rows ?? 0;
1789
+ const sessions = data.info.tables.find((table) => table.name === "sessions")?.rows ?? 0;
1790
+ lines.push({ text: "", tone: "muted" });
1791
+ lines.push({
1792
+ text: truncate(` wipe everything \xB7 ${formatCount(steps)} steps \xB7 ${formatCount(sessions)} sessions \xB7 cannot be undone`, width),
1793
+ tone: steps === 0 && sessions === 0 ? "muted" : "warning",
1794
+ row: { kind: "wipe", value: "all" }
1795
+ });
1611
1796
  if (data.busy === true) {
1612
1797
  lines.push({ text: "", tone: "muted" });
1613
1798
  lines.push({ text: "the recorder is writing: try the vacuum again in a moment", tone: "warning" });
@@ -1703,6 +1888,8 @@ function sidebarLines(rows, options) {
1703
1888
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
1704
1889
  const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
1705
1890
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
1891
+ const header = `${clock} ${provider}`;
1892
+ const timed = turn.durationMs === undefined ? undefined : `${header} \xB7 ${formatMs(turn.durationMs)}`;
1706
1893
  const volumes = [
1707
1894
  ` ${labels.input} ${input} (${prompt}) \xB7 ${labels.output} ${output}`,
1708
1895
  ` ${labels.input} ${input} \xB7 ${labels.output} ${output}`,
@@ -1714,7 +1901,7 @@ function sidebarLines(rows, options) {
1714
1901
  ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
1715
1902
  ` hit ${hit}${suffix}`
1716
1903
  ];
1717
- lines.push({ text: truncate(`${clock} ${provider}`, budget), tone: turn.providerChanged ? "warning" : "base" });
1904
+ lines.push({ text: truncate(timed !== undefined && timed.length <= budget ? timed : header, budget), tone: turn.providerChanged ? "warning" : "base" });
1718
1905
  const edge = index === 0 || index === rows.length - 1;
1719
1906
  if (edge || turn.modelChanged || turn.providerChanged) {
1720
1907
  const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
@@ -1735,1210 +1922,310 @@ function sidebarLines(rows, options) {
1735
1922
  }
1736
1923
 
1737
1924
  // src/panel.tsx
1925
+ import { insert as _$insert } from "@opentui/solid";
1738
1926
  import { effect as _$effect } from "@opentui/solid";
1927
+ import { createTextNode as _$createTextNode } from "@opentui/solid";
1739
1928
  import { insertNode as _$insertNode } from "@opentui/solid";
1740
- import { insert as _$insert } from "@opentui/solid";
1741
1929
  import { createComponent as _$createComponent } from "@opentui/solid";
1742
1930
  import { use as _$use } from "@opentui/solid";
1743
1931
  import { setProp as _$setProp } from "@opentui/solid";
1744
1932
  import { createElement as _$createElement } from "@opentui/solid";
1745
1933
  import { TextAttributes } from "@opentui/core";
1746
- import { For, createMemo, createRenderEffect, createSignal } from "solid-js";
1934
+ import { For, Show, createEffect, createMemo, createRenderEffect, createSignal } from "solid-js";
1747
1935
 
1748
- // src/stats/aggregates.ts
1749
- var STEP_AT = "COALESCE(created_at, recorded_at)";
1750
- function normalize(rows, optional) {
1751
- for (const row of rows) {
1752
- for (const key of optional)
1753
- if (row[key] === null)
1754
- row[key] = undefined;
1755
- }
1756
- return rows;
1757
- }
1758
- function groupBy(items, key) {
1759
- const groups = new Map;
1760
- for (const item of items) {
1761
- const group = key(item);
1762
- const list = groups.get(group);
1763
- if (list !== undefined)
1764
- list.push(item);
1765
- else
1766
- groups.set(group, [item]);
1767
- }
1768
- return groups;
1769
- }
1770
- var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,
1771
- model_id AS modelID, variant,
1772
- COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1773
- COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1774
- COALESCE(list_cost, 0) AS listCost,
1775
- created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1776
- var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
1777
- var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1778
- function stepRows(db, options) {
1779
- const filter = buildWhere(options?.range, options?.filters);
1780
- const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
1781
- return normalize(rows, STEP_OPTIONAL);
1782
- }
1783
- function cachePairs(db, options) {
1784
- const filter = buildWhere(options?.range, options?.filters);
1785
- 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);
1786
- const from = options?.range?.from;
1787
- if (from === undefined || rows.length === 0)
1788
- return rows;
1789
- const seek = db.query(`SELECT ${PAIR_COLUMNS} FROM steps
1790
- WHERE session_id = ? AND COALESCE(created_at, recorded_at) < ?
1791
- ORDER BY COALESCE(created_at, recorded_at) DESC, message_id DESC LIMIT 1`);
1792
- for (const sessionID of new Set(rows.map((row) => row.sessionID))) {
1793
- const boundary = seek.get(sessionID, from);
1794
- if (boundary === null)
1795
- continue;
1796
- const step = normalize([boundary], STEP_OPTIONAL)[0];
1797
- step.boundary = true;
1798
- rows.push(step);
1799
- }
1800
- rows.sort((left, right) => {
1801
- if (left.sessionID !== right.sessionID)
1802
- return left.sessionID < right.sessionID ? -1 : 1;
1803
- if (left.at !== right.at)
1804
- return left.at - right.at;
1805
- return left.messageID < right.messageID ? -1 : left.messageID > right.messageID ? 1 : 0;
1806
- });
1807
- return rows;
1808
- }
1809
- function message(step) {
1810
- return {
1811
- type: "assistant",
1812
- id: step.messageID,
1813
- ...step.modelID === undefined ? {} : { model: { providerID: step.providerID ?? "", id: step.modelID, ...step.variant === undefined ? {} : { variant: step.variant } } },
1814
- tokens: { cache: { read: step.cached } },
1815
- time: {
1816
- ...step.createdAt === undefined ? {} : { created: step.createdAt },
1817
- ...step.streamedAt === undefined ? {} : { streamed: step.streamedAt },
1818
- ...step.completedAt === undefined ? {} : { completed: step.completedAt }
1819
- }
1820
- };
1821
- }
1822
- function pairsOf(rows) {
1823
- const pairs = [];
1824
- for (let index = 1;index < rows.length; index += 1) {
1825
- const previous = rows[index - 1];
1826
- const current = rows[index];
1827
- if (previous.sessionID !== current.sessionID)
1828
- continue;
1829
- pairs.push({ previous, current });
1830
- }
1831
- return pairs;
1832
- }
1833
- function usageOf(steps) {
1834
- const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
1835
- for (const step of steps) {
1836
- usage.steps += 1;
1837
- usage.input += step.input;
1838
- usage.cached += step.cached;
1839
- usage.cacheWrite += step.cacheWrite;
1840
- usage.output += step.output;
1841
- usage.reasoning += step.reasoning;
1842
- usage.cost += step.cost;
1843
- usage.listCost += step.listCost;
1844
- }
1845
- return usage;
1846
- }
1847
- function coverageOf(db, options) {
1848
- const filter = buildWhere(options?.range, options?.filters);
1849
- const row = db.query(`SELECT COUNT(*) AS steps,
1850
- COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,
1851
- COUNT(DISTINCT provider_id) AS providers,
1852
- COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1853
- COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1854
- 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,
1855
- MIN(${STEP_AT}) AS firstAt,
1856
- MAX(${STEP_AT}) AS lastAt
1857
- FROM steps ${filter.where}`).get(...filter.params);
1858
- return {
1859
- steps: row.steps,
1860
- models: row.models,
1861
- providers: row.providers,
1862
- missingModel: row.missingModel,
1863
- unsettled: row.unsettled,
1864
- missingTps: row.missingTps,
1865
- firstAt: row.firstAt ?? undefined,
1866
- lastAt: row.lastAt ?? undefined
1867
- };
1868
- }
1869
- function groupedRows(db, options) {
1870
- const filter = buildWhere(options?.range, options?.filters);
1871
- const rows = db.query(`SELECT ${STEP_COLUMNS} FROM steps ${filter.where}`).all(...filter.params);
1872
- return normalize(rows, STEP_OPTIONAL);
1873
- }
1874
- function timingOf(step) {
1875
- const wall = step.createdAt !== undefined && step.completedAt !== undefined ? step.completedAt - step.createdAt : undefined;
1876
- const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
1877
- return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
1878
- }
1879
- function timingRows(db, options) {
1880
- return groupedRows(db, options);
1881
- }
1882
- function latencyOf(rows) {
1883
- const wall = [];
1884
- const stream = [];
1885
- const tps = [];
1886
- for (const step of rows) {
1887
- const timing = timingOf(step);
1888
- if (timing.wall !== undefined)
1889
- wall.push(timing.wall);
1890
- if (timing.stream !== undefined)
1891
- stream.push(timing.stream);
1892
- if (timing.tps !== undefined)
1893
- tps.push(timing.tps);
1894
- }
1895
- return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
1896
- }
1897
- function latencyGroupsOf(rows, by) {
1898
- const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
1899
- const groups = [];
1900
- for (const [group, steps] of groupBy(rows, key)) {
1901
- const wall = [];
1902
- const stream = [];
1903
- const tps = [];
1904
- for (const step of steps) {
1905
- const timing = timingOf(step);
1906
- if (timing.wall !== undefined)
1907
- wall.push(timing.wall);
1908
- if (timing.stream !== undefined)
1909
- stream.push(timing.stream);
1910
- if (timing.tps !== undefined)
1911
- tps.push(timing.tps);
1912
- }
1913
- const [modelID, variant] = group.split("#");
1914
- groups.push({
1915
- key: group,
1916
- label: by === "model" ? variant === undefined || variant === "" ? modelID : `${modelID} ${variant}` : group,
1917
- count: steps.length,
1918
- usage: usageOf(steps),
1919
- wall: latencyStats(wall),
1920
- stream: latencyStats(stream),
1921
- tps: latencyStats(tps)
1922
- });
1923
- }
1924
- return groups.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
1925
- }
1926
- var EMPTY_CACHE = { steps: 0, input: 0, cached: 0, cacheWrite: 0, prompt: 0, hit: undefined, hitP50: undefined };
1927
- function cacheStatsOfSteps(steps) {
1928
- let input = 0;
1929
- let cached = 0;
1930
- let cacheWrite = 0;
1931
- const ratios = [];
1932
- for (const step of steps) {
1933
- input += step.input;
1934
- cached += step.cached;
1935
- cacheWrite += step.cacheWrite;
1936
- const prompt = step.input + step.cached + step.cacheWrite;
1937
- if (prompt > 0)
1938
- ratios.push(step.cached / prompt);
1939
- }
1940
- const prompt = input + cached + cacheWrite;
1941
- return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) };
1942
- }
1943
- function cacheStatsOf(db, options) {
1944
- const rows = stepRows(db, options);
1945
- return rows.length === 0 ? EMPTY_CACHE : cacheStatsOfSteps(rows);
1946
- }
1947
- function cacheStatsByModel(rows) {
1948
- const out = [];
1949
- const inRange = rows.filter((row) => row.boundary !== true);
1950
- for (const [, group] of groupBy(inRange, (row) => modelKey(row.modelID ?? "(unknown)", row.variant))) {
1951
- out.push({ modelID: group[0].modelID ?? "(unknown)", variant: group[0].variant, cache: cacheStatsOfSteps(group) });
1952
- }
1953
- return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID));
1954
- }
1955
- function switchesOf(rows) {
1956
- const perModel = new Map;
1957
- const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 };
1958
- for (const { previous, current } of pairsOf(rows)) {
1959
- if (previous.modelID === undefined || current.modelID === undefined)
1960
- continue;
1961
- const key = modelKey(current.modelID, current.variant);
1962
- const row = perModel.get(key) ?? {
1963
- modelID: current.modelID,
1964
- variant: current.variant,
1965
- steps: 0,
1966
- pairs: 0,
1967
- changes: 0,
1968
- modelChanges: 0,
1969
- providerChanges: 0,
1970
- cacheLost: 0,
1971
- cacheLostEvents: 0
1972
- };
1973
- row.steps += 1;
1974
- row.pairs += 1;
1975
- totals.pairs += 1;
1976
- const modelChanged = key !== modelKey(previous.modelID, previous.variant);
1977
- const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID;
1978
- if (modelChanged)
1979
- row.modelChanges += 1;
1980
- if (providerChanged)
1981
- row.providerChanges += 1;
1982
- if (modelChanged || providerChanged) {
1983
- row.changes += 1;
1984
- totals.changes += 1;
1985
- const lost = cacheDrop(message(previous), message(current), "model");
1986
- if (lost !== undefined) {
1987
- row.cacheLost += lost;
1988
- row.cacheLostEvents += 1;
1989
- totals.cacheLost += lost;
1990
- totals.cacheLostEvents += 1;
1936
+ // src/rpc.ts
1937
+ import { Rpc } from "@opencode/plugin/rpc";
1938
+ var Tone = { type: "string", enum: ["base", "muted", "warning", "accent"] };
1939
+ var PanelRowSchema = {
1940
+ type: "object",
1941
+ properties: {
1942
+ kind: { type: "string", enum: ["model", "session", "period", "provider", "turn", "prune", "wipe"] },
1943
+ value: { type: "string", maxLength: 500 },
1944
+ variant: { type: "string", maxLength: 200 }
1945
+ },
1946
+ required: ["kind", "value"],
1947
+ additionalProperties: false
1948
+ };
1949
+ var PanelLineSchema = {
1950
+ type: "object",
1951
+ properties: {
1952
+ text: { type: "string" },
1953
+ tone: Tone,
1954
+ hint: { type: "boolean" },
1955
+ row: PanelRowSchema
1956
+ },
1957
+ required: ["text"],
1958
+ additionalProperties: false
1959
+ };
1960
+ var PanelSettingsSchema = {
1961
+ type: "object",
1962
+ properties: {
1963
+ view: { type: "string", enum: ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"] },
1964
+ range: { type: "string", enum: ["session", "today", "7d", "30d", "all"] },
1965
+ sort: { type: "string", maxLength: 40 },
1966
+ sortDesc: { type: "boolean" },
1967
+ granularity: { type: "string", enum: ["day", "week", "month"] },
1968
+ turnsScope: { type: "string", enum: ["session", "all"] },
1969
+ modelID: { type: "string", maxLength: 300 },
1970
+ providerID: { type: "string", maxLength: 300 }
1971
+ },
1972
+ required: ["view", "range", "sort", "sortDesc", "granularity", "turnsScope", "modelID", "providerID"],
1973
+ additionalProperties: false
1974
+ };
1975
+ var TableSizeSchema = {
1976
+ type: "object",
1977
+ properties: {
1978
+ name: { type: "string" },
1979
+ rows: { type: "number" }
1980
+ },
1981
+ required: ["name", "rows"],
1982
+ additionalProperties: false
1983
+ };
1984
+ var DbInfoSchema = {
1985
+ type: "object",
1986
+ properties: {
1987
+ path: { type: "string" },
1988
+ bytes: { type: "number" },
1989
+ walBytes: { type: "number" },
1990
+ schemaVersion: { type: "number" },
1991
+ tables: { type: "array", items: TableSizeSchema },
1992
+ firstAt: { type: "number" },
1993
+ lastAt: { type: "number" },
1994
+ removable: {
1995
+ type: "array",
1996
+ items: {
1997
+ type: "object",
1998
+ properties: { days: { type: "number" }, steps: { type: "number" } },
1999
+ required: ["days", "steps"],
2000
+ additionalProperties: false
1991
2001
  }
1992
- }
1993
- perModel.set(key, row);
1994
- }
1995
- return {
1996
- rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),
1997
- totals
1998
- };
1999
- }
2000
- var GAP_BUCKETS = [
2001
- ["<1m", 0, 60000],
2002
- ["1\u20135m", 60000, 5 * 60000],
2003
- ["5\u201315m", 5 * 60000, 15 * 60000],
2004
- ["15\u201360m", 15 * 60000, 60 * 60000],
2005
- ["1\u20136h", 60 * 60000, 6 * 60 * 60000],
2006
- [">6h", 6 * 60 * 60000, undefined]
2007
- ];
2008
- function bucketFor(gapMs) {
2009
- const index = GAP_BUCKETS.findIndex(([, from, to]) => gapMs >= from && (to === undefined || gapMs < to));
2010
- return index === -1 ? GAP_BUCKETS.length - 1 : index;
2011
- }
2012
- function gapReportOf(rows) {
2013
- const buckets = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }));
2014
- const providers = new Map;
2015
- let samples = 0;
2016
- for (const { previous, current } of pairsOf(rows)) {
2017
- if (previous.modelID === undefined || current.modelID === undefined)
2018
- continue;
2019
- if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant))
2020
- continue;
2021
- if ((previous.providerID ?? "") !== (current.providerID ?? ""))
2022
- continue;
2023
- const gap = stepGap(message(previous), message(current));
2024
- if (gap === undefined)
2025
- continue;
2026
- const lost = cacheDrop(message(previous), message(current));
2027
- const bucket = buckets[bucketFor(gap)];
2028
- bucket.samples += 1;
2029
- samples += 1;
2030
- if (lost === undefined)
2031
- bucket.retained += 1;
2032
- else {
2033
- bucket.drops += 1;
2034
- bucket.lostTokens += lost;
2035
- }
2036
- const provider = current.providerID ?? previous.providerID ?? "(unknown)";
2037
- const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined };
2038
- row.samples += 1;
2039
- if (lost === undefined)
2040
- row.retained += 1;
2041
- else {
2042
- row.drops += 1;
2043
- row.lostTokens += lost;
2044
- }
2045
- providers.set(provider, row);
2046
- }
2047
- for (const bucket of buckets)
2048
- bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined;
2049
- for (const row of providers.values())
2050
- row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined;
2051
- return {
2052
- buckets,
2053
- providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),
2054
- samples
2055
- };
2056
- }
2057
- function ttlEvidenceOf(rows) {
2058
- const evidence = new Map;
2059
- for (const { previous, current } of pairsOf(rows)) {
2060
- if (previous.modelID === undefined || current.modelID === undefined)
2061
- continue;
2062
- const key = `${current.providerID ?? ""}/${current.modelID}`;
2063
- const before = `${previous.providerID ?? ""}/${previous.modelID}#${previous.variant ?? ""}`;
2064
- const after = `${current.providerID ?? ""}/${current.modelID}#${current.variant ?? ""}`;
2065
- if (before !== after)
2066
- continue;
2067
- const row = evidence.get(key) ?? {
2068
- providerID: current.providerID ?? "(unknown)",
2069
- modelID: current.modelID,
2070
- samples: 0,
2071
- maxHitGapMs: undefined,
2072
- minDropGapMs: undefined
2073
- };
2074
- row.samples += 1;
2075
- const gapMs = stepGap(message(previous), message(current));
2076
- if (gapMs !== undefined) {
2077
- const lost = cacheDrop(message(previous), message(current));
2078
- if (lost === undefined)
2079
- row.maxHitGapMs = row.maxHitGapMs === undefined ? gapMs : Math.max(row.maxHitGapMs, gapMs);
2080
- else
2081
- row.minDropGapMs = row.minDropGapMs === undefined ? gapMs : Math.min(row.minDropGapMs, gapMs);
2082
- }
2083
- evidence.set(key, row);
2084
- }
2085
- return [...evidence.values()].sort((left, right) => right.samples - left.samples || `${left.providerID}/${left.modelID}`.localeCompare(`${right.providerID}/${right.modelID}`));
2086
- }
2087
- function cacheDropsOf(db, rows, options) {
2088
- const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS;
2089
- const losses = [];
2090
- for (const { previous, current } of pairsOf(rows)) {
2091
- const tokens = cacheDrop(message(previous), message(current), "model");
2092
- if (tokens === undefined)
2093
- continue;
2094
- losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) });
2095
- }
2096
- if (losses.length === 0)
2097
- return [];
2098
- const compactions = new Map;
2099
- const sessionIDs = [...new Set(losses.map((loss) => loss.current.sessionID))];
2100
- const events = db.query(`SELECT session_id, at FROM events
2101
- WHERE kind = 'compaction' AND at IS NOT NULL AND session_id IN (${sessionIDs.map(() => "?").join(", ")})
2102
- ORDER BY at`).all(...sessionIDs);
2103
- for (const event of events) {
2104
- const list = compactions.get(event.session_id);
2105
- if (list !== undefined)
2106
- list.push(event.at);
2107
- else
2108
- compactions.set(event.session_id, [event.at]);
2109
- }
2110
- return losses.map((loss) => {
2111
- const ended = loss.previous.completedAt ?? loss.previous.streamedAt ?? loss.previous.createdAt;
2112
- const compacted = (compactions.get(loss.current.sessionID) ?? []).some((time) => ended !== undefined && time >= ended && time <= loss.current.at);
2113
- const reason = compacted ? "compaction" : loss.gapMs !== undefined && loss.gapMs >= ttlHint ? "expired" : "unknown";
2114
- return {
2115
- sessionID: loss.current.sessionID,
2116
- messageID: loss.current.messageID,
2117
- providerID: loss.current.providerID,
2118
- modelID: loss.current.modelID,
2119
- variant: loss.current.variant,
2120
- at: loss.current.at,
2121
- tokens: loss.tokens,
2122
- gapMs: loss.gapMs,
2123
- prevCached: loss.previous.cached,
2124
- reason
2125
- };
2126
- }).sort((left, right) => left.at - right.at);
2127
- }
2128
- function groupValues(steps) {
2129
- const wall = [];
2130
- const tps = [];
2131
- for (const step of steps) {
2132
- const timing = timingOf(step);
2133
- if (timing.wall !== undefined)
2134
- wall.push(timing.wall);
2135
- if (timing.tps !== undefined)
2136
- tps.push(timing.tps);
2137
- }
2138
- return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
2139
- }
2140
- function providerOf(steps, models) {
2141
- const values = groupValues(steps);
2142
- const times = steps.map((step) => step.at);
2143
- return {
2144
- provider: steps[0].providerID,
2145
- models: models.split("\x00"),
2146
- share: 0,
2147
- usage: usageOf(steps),
2148
- cache: values.cache,
2149
- tps: values.tps,
2150
- wall: values.wall,
2151
- firstAt: times.length > 0 ? Math.min(...times) : undefined,
2152
- lastAt: times.length > 0 ? Math.max(...times) : undefined
2153
- };
2154
- }
2155
- 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");
2156
- function providerSummaryOf(rows) {
2157
- const out = [];
2158
- for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
2159
- const summary = providerOf(steps, modelNames(steps));
2160
- out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length });
2161
- }
2162
- return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? "").localeCompare(right.provider ?? ""));
2163
- }
2164
- function providerBreakdownOf(rows) {
2165
- const out = [];
2166
- for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
2167
- for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
2168
- const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
2169
- out.push({
2170
- ...providerOf(steps, modelNames(steps)),
2171
- modelID,
2172
- variant: variant === "" ? undefined : variant,
2173
- share: steps.length / modelRows.length
2174
- });
2175
- }
2176
- }
2177
- return out.sort((left, right) => right.usage.steps - left.usage.steps || right.cache.cached - left.cache.cached);
2178
- }
2179
- function isoWeek(date) {
2180
- const monday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
2181
- monday.setDate(monday.getDate() - (monday.getDay() + 6) % 7);
2182
- const thursday = new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 3);
2183
- const firstThursday = new Date(thursday.getFullYear(), 0, 4);
2184
- firstThursday.setDate(firstThursday.getDate() - (firstThursday.getDay() + 6) % 7 + 3);
2185
- const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000));
2186
- return { year: thursday.getFullYear(), week, monday };
2187
- }
2188
- function periodStart(at, granularity) {
2189
- const date = new Date(at);
2190
- const pad = (value) => String(value).padStart(2, "0");
2191
- if (granularity === "month") {
2192
- const start = new Date(date.getFullYear(), date.getMonth(), 1);
2193
- return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() };
2194
- }
2195
- if (granularity === "week") {
2196
- const { year, week, monday } = isoWeek(date);
2197
- return { key: `${year}-W${pad(week)}`, label: `${year}-W${pad(week)}`, start: monday.getTime() };
2198
- }
2199
- const start = new Date(date.getFullYear(), date.getMonth(), date.getDate());
2200
- const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
2201
- return { key, label: key, start: start.getTime() };
2202
- }
2203
- function periodsOf(rows, granularity) {
2204
- const out = [];
2205
- for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {
2206
- const period = periodStart(steps[0].at, granularity);
2207
- out.push({
2208
- key,
2209
- label: period.label,
2210
- at: period.start,
2211
- steps: steps.length,
2212
- sessions: new Set(steps.map((step) => step.sessionID)).size,
2213
- usage: usageOf(steps),
2214
- cache: cacheStatsOfSteps(steps)
2215
- });
2216
- }
2217
- return out.sort((left, right) => left.at - right.at);
2218
- }
2219
-
2220
- // src/panel-build.ts
2221
- var SORT_KEYS = {
2222
- models: ["steps", "cached", "hit", "out", "cost"],
2223
- providers: ["steps", "cached", "hit", "cost", "share", "tps"],
2224
- latency: ["n", "tps", "wall"],
2225
- sessions: ["last", "steps", "cached", "cost"],
2226
- turns: ["time", "cost", "tokens"]
2002
+ },
2003
+ unpriced: { type: "number" }
2004
+ },
2005
+ required: ["path", "bytes", "schemaVersion", "tables", "removable", "unpriced"],
2006
+ additionalProperties: false
2227
2007
  };
2228
- function sortKeys(view) {
2229
- return SORT_KEYS[view] ?? [];
2230
- }
2231
- function defaultSort(view) {
2232
- return sortKeys(view)[0] ?? "";
2233
- }
2234
- function nextSort(view, current, step) {
2235
- const keys = sortKeys(view);
2236
- if (keys.length === 0)
2237
- return current;
2238
- const index = keys.indexOf(current);
2239
- if (index === -1)
2240
- return keys[0];
2241
- return keys[(index + step + keys.length) % keys.length];
2242
- }
2243
- function detailLabel(row) {
2244
- switch (row.kind) {
2245
- case "model":
2246
- return `model ${row.variant !== undefined ? `${row.value} ${row.variant}` : row.value}`;
2247
- case "session":
2248
- case "turn":
2249
- return `session ${row.value}`;
2250
- case "period":
2251
- return `period ${row.value}`;
2252
- case "provider":
2253
- return `provider ${row.value}`;
2254
- case "prune":
2255
- return `prune older than ${row.value} days`;
2256
- }
2257
- }
2258
- function buildPanel(request) {
2259
- try {
2260
- return build(request);
2261
- } catch (error) {
2262
- const message = error instanceof Error ? error.message : String(error);
2263
- return [{ text: `stats query failed: ${message}`, tone: "warning" }];
2264
- }
2265
- }
2266
- function build(request) {
2267
- const { db, view, now, sessionStart, width } = request;
2268
- const estimates = request.estimates !== false;
2269
- const scoped = request.range === "session" && request.sessionID !== "";
2270
- const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
2271
- const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
2272
- if (request.detail !== undefined)
2273
- return buildDetail(request, range, filters, estimates);
2274
- switch (view) {
2275
- case "overview": {
2276
- const usage = overview(db, range, filters);
2277
- const sessionUsage = request.sessionID === "" ? undefined : overview(db, undefined, { ...request.filters, sessionID: request.sessionID });
2278
- const childIDs = request.sessionID === "" ? [] : childSessionIDs(db, request.sessionID);
2279
- const children = childIDs.length === 0 ? [] : sessionUsageOf(db, childIDs);
2280
- return overviewLines({
2281
- usage,
2282
- session: sessionUsage,
2283
- ...children.length > 0 ? { subagents: children } : {},
2284
- range: request.range,
2285
- activity: activityOf(db, range, now),
2286
- coverage: coverageOf(db, { range, filters }),
2287
- estimates
2288
- }, width);
2289
- }
2290
- case "models": {
2291
- const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
2292
- const pairs = cachePairs(db, { range, filters });
2293
- const switches = switchesOf(pairs);
2294
- return modelsLines(rows, width, {
2295
- cache: cacheByModel(pairs),
2296
- switches: switchesByModel(switches.rows)
2297
- }, 40, estimates);
2298
- }
2299
- case "providers":
2300
- return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
2301
- case "cache": {
2302
- const pairs = cachePairs(db, { range, filters });
2303
- return cacheLines({
2304
- drops: cacheDropsOf(db, pairs),
2305
- evidence: ttlEvidenceOf(pairs),
2306
- gap: gapReportOf(pairs),
2307
- models: topCacheModels(pairs)
2308
- }, width);
2309
- }
2310
- case "periods":
2311
- return periodLines(periodsOf(stepRows(db, { range, filters }), request.granularity), width, request.granularity, 40, estimates);
2312
- case "latency": {
2313
- const timings = timingRows(db, { range, filters });
2314
- const by = filters.modelID !== undefined ? "provider" : "model";
2315
- return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
2316
- }
2317
- case "sessions": {
2318
- const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates);
2319
- const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
2320
- return sessionsLines(rows, width, {
2321
- limit: 20,
2322
- estimates,
2323
- rollup: {
2324
- subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),
2325
- subagentCost: child.reduce((sum, row) => sum + row.cost, 0),
2326
- subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0)
2327
- }
2328
- });
2329
- }
2330
- case "db":
2331
- 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);
2332
- case "turns": {
2333
- const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
2334
- const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
2335
- const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
2336
- return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
2337
- }
2338
- }
2339
- }
2340
- function rangeForRequest(key, now) {
2341
- switch (key) {
2342
- case "today": {
2343
- const start = new Date(now);
2344
- start.setHours(0, 0, 0, 0);
2345
- return { from: start.getTime() };
2346
- }
2347
- case "7d":
2348
- return { from: now - 7 * 24 * 60 * 60 * 1000 };
2349
- case "30d":
2350
- return { from: now - 30 * 24 * 60 * 60 * 1000 };
2351
- default:
2352
- return;
2353
- }
2354
- }
2355
- function buildDetail(request, range, filters, estimates) {
2356
- const row = request.detail;
2357
- const db = request.db;
2358
- const width = request.width;
2359
- const head = { text: detailLabel(row), tone: "accent" };
2360
- const back = { text: "backspace returns \xB7 the header shows where you came from", tone: "muted" };
2361
- if (row.kind === "model") {
2362
- const scoped = { ...filters, modelKey: modelKey(row.value, row.variant) };
2363
- const stats = cacheStatsOf(db, { range, filters: scoped });
2364
- const steps = stepRows(db, { range, filters: scoped });
2365
- return [
2366
- head,
2367
- {
2368
- 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)}`,
2369
- tone: "muted"
2008
+ var FilterOptionSchema = {
2009
+ type: "object",
2010
+ properties: { value: { type: "string" }, steps: { type: "number" } },
2011
+ required: ["value", "steps"],
2012
+ additionalProperties: false
2013
+ };
2014
+ var PruneResultSchema = {
2015
+ type: "object",
2016
+ properties: {
2017
+ steps: { type: "number" },
2018
+ prompts: { type: "number" },
2019
+ events: { type: "number" },
2020
+ usage: { type: "number" }
2021
+ },
2022
+ required: ["steps", "prompts", "events", "usage"],
2023
+ additionalProperties: false
2024
+ };
2025
+ var WipeResultSchema = {
2026
+ type: "object",
2027
+ properties: {
2028
+ steps: { type: "number" },
2029
+ prompts: { type: "number" },
2030
+ events: { type: "number" },
2031
+ usage: { type: "number" },
2032
+ sessions: { type: "number" }
2033
+ },
2034
+ required: ["steps", "prompts", "events", "usage", "sessions"],
2035
+ additionalProperties: false
2036
+ };
2037
+ var BackfillResultSchema = {
2038
+ type: "object",
2039
+ properties: {
2040
+ candidates: { type: "number" },
2041
+ updated: { type: "number" }
2042
+ },
2043
+ required: ["candidates", "updated"],
2044
+ additionalProperties: false
2045
+ };
2046
+ var VacuumResultSchema = {
2047
+ type: "object",
2048
+ properties: {
2049
+ before: { type: "number" },
2050
+ after: { type: "number" },
2051
+ freed: { type: "number" }
2052
+ },
2053
+ required: ["before", "after", "freed"],
2054
+ additionalProperties: false
2055
+ };
2056
+ var NoInput = { type: "object", properties: {}, additionalProperties: false };
2057
+ var ErrorSchema = {
2058
+ type: "object",
2059
+ properties: { message: { type: "string", maxLength: 500 } },
2060
+ additionalProperties: false
2061
+ };
2062
+ var errors = {
2063
+ busy: ErrorSchema,
2064
+ unavailable: ErrorSchema,
2065
+ disabled: ErrorSchema,
2066
+ invalid: ErrorSchema
2067
+ };
2068
+ var UsageInsights = Rpc.define({
2069
+ id: "usage-insights",
2070
+ methods: {
2071
+ panel: {
2072
+ input: {
2073
+ type: "object",
2074
+ properties: {
2075
+ sessionID: { type: "string", maxLength: 200 },
2076
+ settings: PanelSettingsSchema,
2077
+ detail: PanelRowSchema,
2078
+ width: { type: "number", minimum: 20, maximum: MAX_PANEL_WIDTH },
2079
+ busy: { type: "boolean" }
2080
+ },
2081
+ required: ["sessionID", "settings", "width"],
2082
+ additionalProperties: false
2370
2083
  },
2371
- { text: "", tone: "muted" },
2372
- ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2373
- { text: "", tone: "muted" },
2374
- ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
2375
- { text: "", tone: "muted" },
2376
- back
2377
- ];
2378
- }
2379
- if (row.kind === "session" || row.kind === "turn") {
2380
- const rows = turns(db, { sessionID: row.value, limit: 80 });
2381
- return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: "", tone: "muted" }, back];
2382
- }
2383
- if (row.kind === "provider") {
2384
- const scoped = { ...filters, provider: row.value };
2385
- const steps = stepRows(db, { range, filters: scoped });
2386
- const stats = cacheStatsOf(db, { range, filters: scoped });
2387
- return [
2388
- head,
2389
- {
2390
- 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)}`,
2391
- tone: "muted"
2084
+ output: {
2085
+ type: "object",
2086
+ properties: {
2087
+ lines: { type: "array", items: PanelLineSchema },
2088
+ database: DbInfoSchema
2089
+ },
2090
+ required: ["lines"],
2091
+ additionalProperties: false
2392
2092
  },
2393
- { text: "", tone: "muted" },
2394
- ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2395
- { text: "", tone: "muted" },
2396
- ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
2397
- { text: "", tone: "muted" },
2398
- back
2399
- ];
2400
- }
2401
- if (row.kind === "period") {
2402
- const periods = periodsOf(stepRows(db, { range, filters }), request.granularity);
2403
- const period = periods.find((entry) => entry.key === row.value);
2404
- return [
2405
- head,
2406
- { text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
2407
- { text: "", tone: "muted" },
2408
- ...providerSummaryLines(providerSummaryOf(stepRows(db, { range, filters })), width, 40, estimates),
2409
- { text: "", tone: "muted" },
2410
- back
2411
- ];
2412
- }
2413
- return [head, back];
2414
- }
2415
- function percent(value) {
2416
- return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
2417
- }
2418
- function sortModels(rows, sort, desc, estimates = true) {
2419
- const sign = desc ? -1 : 1;
2420
- const pick = (model) => {
2421
- if (sort === "cached")
2422
- return model.totals.cached;
2423
- if (sort === "out")
2424
- return model.totals.output;
2425
- if (sort === "cost")
2426
- return estimates ? spend(model.totals) : model.totals.cost;
2427
- return model.totals.steps;
2428
- };
2429
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2430
- }
2431
- function sortProviders(rows, sort, desc, estimates = true) {
2432
- const sign = desc ? -1 : 1;
2433
- const pick = (row) => {
2434
- if (sort === "cached")
2435
- return row.cache.cached;
2436
- if (sort === "hit")
2437
- return row.cache.hit ?? -1;
2438
- if (sort === "cost")
2439
- return estimates ? spend(row.usage) : row.usage.cost;
2440
- if (sort === "share")
2441
- return row.share;
2442
- if (sort === "tps")
2443
- return row.tps ?? -1;
2444
- return row.usage.steps;
2445
- };
2446
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2447
- }
2448
- function sortLatency(rows, sort, desc) {
2449
- const sign = desc ? -1 : 1;
2450
- const pick = (row) => {
2451
- if (sort === "tps")
2452
- return row.tps.p50 ?? -1;
2453
- if (sort === "wall")
2454
- return row.wall.p50 ?? -1;
2455
- return row.count;
2456
- };
2457
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2458
- }
2459
- function sortSessions(rows, sort, desc, estimates = true) {
2460
- const sign = desc ? -1 : 1;
2461
- const pick = (row) => {
2462
- if (sort === "steps")
2463
- return row.steps;
2464
- if (sort === "cached")
2465
- return row.cached;
2466
- if (sort === "cost")
2467
- return estimates ? spend(row) : row.cost;
2468
- return row.lastAt ?? 0;
2469
- };
2470
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2471
- }
2472
- function sortTurns(rows, sort, desc, estimates = true) {
2473
- const sign = desc ? -1 : 1;
2474
- const pick = (row) => {
2475
- if (sort === "cost")
2476
- return estimates ? spend(row.totals) : row.totals.cost;
2477
- if (sort === "tokens")
2478
- return row.totals.cached + row.totals.input + row.totals.output;
2479
- return row.endAt ?? 0;
2480
- };
2481
- return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2482
- }
2483
- function cacheByModel(pairs) {
2484
- const map = new Map;
2485
- for (const row of cacheStatsByModel(pairs)) {
2486
- map.set(modelKey(row.modelID, row.variant), row.cache);
2487
- }
2488
- return map;
2489
- }
2490
- function switchesByModel(rows) {
2491
- return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]));
2492
- }
2493
- function topCacheModels(pairs) {
2494
- return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
2495
- }
2496
- function activityOf(db, range, now) {
2497
- const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps`).get();
2498
- const from = range?.from ?? earliest?.at ?? 0;
2499
- const to = range?.to ?? now;
2500
- const span = Math.max(1, to - from);
2501
- const ladder = [3600000, 3 * 3600000, 6 * 3600000, 12 * 3600000, 86400000, 3 * 86400000, 7 * 86400000, 30 * 86400000];
2502
- const bucket = ladder.find((size) => span / size <= 48) ?? ladder[ladder.length - 1];
2503
- const rows = db.query(`SELECT CAST(COALESCE(created_at, recorded_at) / ? AS INTEGER) AS bucket, COUNT(*) AS steps
2504
- FROM steps
2505
- WHERE COALESCE(created_at, recorded_at) >= ?
2506
- GROUP BY bucket ORDER BY bucket`).all(bucket, from);
2507
- if (rows.length === 0)
2508
- return [];
2509
- const first = Math.floor(from / bucket);
2510
- const last = rows[rows.length - 1].bucket;
2511
- const series = [];
2512
- for (let index = first;index <= last; index += 1) {
2513
- series.push(rows.find((row) => row.bucket === index)?.steps ?? 0);
2514
- }
2515
- return series;
2516
- }
2517
-
2518
- // src/stats/maintenance.ts
2519
- import { statSync as statSync2 } from "fs";
2520
-
2521
- // src/stats/db.ts
2522
- import { Database } from "bun:sqlite";
2523
- import { chmodSync, mkdirSync } from "fs";
2524
- import { dirname } from "path";
2525
-
2526
- // src/stats/paths.ts
2527
- import { homedir } from "os";
2528
- import { join } from "path";
2529
- import { statSync } from "fs";
2530
- function defaultDbPath(env = process.env, platform = process.platform) {
2531
- const name = join("opencode", "opencode-usage-insights", "usage.db");
2532
- if (platform === "win32") {
2533
- return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
2534
- }
2535
- if (platform === "darwin") {
2536
- return join(homedir(), "Library", "Application Support", name);
2537
- }
2538
- return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
2539
- }
2540
- function expandHome(path, home = homedir()) {
2541
- if (path === "~")
2542
- return home;
2543
- if (path.startsWith("~/") || path.startsWith("~\\"))
2544
- return join(home, path.slice(2));
2545
- return path;
2546
- }
2547
- function resolveDbPath(configured, env = process.env, platform = process.platform) {
2548
- const home = env.HOME ?? env.USERPROFILE ?? homedir();
2549
- if (configured)
2550
- return expandHome(configured, home);
2551
- if (env.OPENCODE_USAGE_INSIGHTS_DB)
2552
- return expandHome(env.OPENCODE_USAGE_INSIGHTS_DB, home);
2553
- return defaultDbPath(env, platform);
2554
- }
2555
- function ensureRegularFile(path) {
2556
- let stats;
2557
- try {
2558
- stats = statSync(path);
2559
- } catch {
2560
- return;
2093
+ errors
2094
+ },
2095
+ turns: {
2096
+ input: {
2097
+ type: "object",
2098
+ properties: {
2099
+ sessionID: { type: "string", maxLength: 200 },
2100
+ limit: { type: "number", minimum: 1, maximum: MAX_TURNS },
2101
+ width: { type: "number", minimum: 20, maximum: 120 }
2102
+ },
2103
+ required: ["sessionID", "limit", "width"],
2104
+ additionalProperties: false
2105
+ },
2106
+ output: {
2107
+ type: "object",
2108
+ properties: {
2109
+ summary: { type: "array", items: PanelLineSchema },
2110
+ history: { type: "array", items: PanelLineSchema }
2111
+ },
2112
+ required: ["summary", "history"],
2113
+ additionalProperties: false
2114
+ },
2115
+ errors
2116
+ },
2117
+ listCost: {
2118
+ input: {
2119
+ type: "object",
2120
+ properties: { sessionID: { type: "string", maxLength: 200 } },
2121
+ required: ["sessionID"],
2122
+ additionalProperties: false
2123
+ },
2124
+ output: {
2125
+ type: "object",
2126
+ properties: { cost: { type: "number" } },
2127
+ required: ["cost"],
2128
+ additionalProperties: false
2129
+ },
2130
+ errors
2131
+ },
2132
+ filters: {
2133
+ input: NoInput,
2134
+ output: {
2135
+ type: "object",
2136
+ properties: {
2137
+ models: { type: "array", items: FilterOptionSchema },
2138
+ providers: { type: "array", items: FilterOptionSchema }
2139
+ },
2140
+ required: ["models", "providers"],
2141
+ additionalProperties: false
2142
+ },
2143
+ errors
2144
+ },
2145
+ dbInfo: {
2146
+ input: NoInput,
2147
+ output: DbInfoSchema,
2148
+ errors
2149
+ },
2150
+ prune: {
2151
+ input: {
2152
+ type: "object",
2153
+ properties: {
2154
+ days: { type: "number", minimum: 1, maximum: 3650 },
2155
+ confirm: { type: "boolean", enum: [true] }
2156
+ },
2157
+ required: ["days", "confirm"],
2158
+ additionalProperties: false
2159
+ },
2160
+ output: PruneResultSchema,
2161
+ errors
2162
+ },
2163
+ wipe: {
2164
+ input: {
2165
+ type: "object",
2166
+ properties: { confirm: { type: "boolean", enum: [true] } },
2167
+ required: ["confirm"],
2168
+ additionalProperties: false
2169
+ },
2170
+ output: WipeResultSchema,
2171
+ errors
2172
+ },
2173
+ vacuum: {
2174
+ input: {
2175
+ type: "object",
2176
+ properties: { confirm: { type: "boolean", enum: [true] } },
2177
+ required: ["confirm"],
2178
+ additionalProperties: false
2179
+ },
2180
+ output: VacuumResultSchema,
2181
+ errors
2182
+ },
2183
+ backfill: {
2184
+ input: {
2185
+ type: "object",
2186
+ properties: { confirm: { type: "boolean", enum: [true] } },
2187
+ required: ["confirm"],
2188
+ additionalProperties: false
2189
+ },
2190
+ output: BackfillResultSchema,
2191
+ errors
2192
+ }
2193
+ },
2194
+ events: {
2195
+ recorded: {
2196
+ schema: {
2197
+ type: "object",
2198
+ properties: {
2199
+ sessionID: { type: "string", maxLength: 200 },
2200
+ at: { type: "number" }
2201
+ },
2202
+ required: ["at"],
2203
+ additionalProperties: false
2204
+ }
2205
+ }
2561
2206
  }
2562
- if (!stats.isFile())
2563
- throw new Error(`not a regular file: ${path}`);
2564
- }
2565
-
2566
- // src/stats/db.ts
2567
- var SCHEMA_VERSION = 10;
2568
- var LABEL_LIMIT = 4 * TEXT_LIMIT;
2569
- var SCHEMA = `
2570
- CREATE TABLE IF NOT EXISTS meta (
2571
- key TEXT PRIMARY KEY,
2572
- value TEXT NOT NULL
2573
- );
2574
-
2575
- CREATE TABLE IF NOT EXISTS sessions (
2576
- session_id TEXT PRIMARY KEY,
2577
- parent_id TEXT,
2578
- directory TEXT,
2579
- title TEXT,
2580
- started_at INTEGER,
2581
- updated_at INTEGER
2582
- );
2583
-
2584
- CREATE TABLE IF NOT EXISTS prompts (
2585
- session_id TEXT NOT NULL,
2586
- message_id TEXT NOT NULL,
2587
- created_at INTEGER,
2588
- PRIMARY KEY (session_id, message_id)
2589
- );
2590
- CREATE INDEX IF NOT EXISTS prompts_created ON prompts(created_at);
2591
-
2592
- CREATE TABLE IF NOT EXISTS steps (
2593
- message_id TEXT PRIMARY KEY,
2594
- session_id TEXT NOT NULL,
2595
- parent_id TEXT,
2596
- provider_id TEXT,
2597
- model_id TEXT,
2598
- variant TEXT,
2599
- input_tokens INTEGER NOT NULL DEFAULT 0,
2600
- output_tokens INTEGER NOT NULL DEFAULT 0,
2601
- reasoning_tokens INTEGER NOT NULL DEFAULT 0,
2602
- cache_read INTEGER NOT NULL DEFAULT 0,
2603
- cache_write INTEGER NOT NULL DEFAULT 0,
2604
- cost REAL NOT NULL DEFAULT 0,
2605
- list_cost REAL,
2606
- created_at INTEGER,
2607
- streamed_at INTEGER,
2608
- completed_at INTEGER,
2609
- finish TEXT,
2610
- recorded_at INTEGER NOT NULL
2611
- );
2612
- CREATE INDEX IF NOT EXISTS steps_session ON steps(session_id, created_at);
2613
- CREATE INDEX IF NOT EXISTS steps_model ON steps(provider_id, model_id, variant);
2614
- CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
2615
- -- Every range filter and every ordering compares the step's own clock, which
2616
- -- falls back to the recording time for a step that was already in flight when
2617
- -- the plugin loaded. The index has to cover that expression, or every ranged
2618
- -- view is a full table scan.
2619
- CREATE INDEX IF NOT EXISTS steps_at ON steps(COALESCE(created_at, recorded_at));
2620
- CREATE INDEX IF NOT EXISTS steps_session_at ON steps(session_id, COALESCE(created_at, recorded_at));
2207
+ });
2621
2208
 
2622
- CREATE TABLE IF NOT EXISTS events (
2623
- id INTEGER PRIMARY KEY AUTOINCREMENT,
2624
- session_id TEXT NOT NULL,
2625
- kind TEXT NOT NULL,
2626
- message_id TEXT,
2627
- at INTEGER,
2628
- data TEXT
2629
- );
2630
- CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
2631
- CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
2632
- `;
2633
- var TABLES = ["sessions", "prompts", "events", "steps"];
2634
- function jsonText(value) {
2635
- if (value === undefined || value === null)
2636
- return null;
2637
- if (typeof value === "string")
2638
- return value;
2639
- try {
2640
- return JSON.stringify(value);
2641
- } catch {
2642
- return null;
2643
- }
2644
- }
2645
- var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
2646
- var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
2647
- function dropUnused(db) {
2648
- const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
2649
- const tables = new Set(objects.filter((row) => row.type === "table").map((row) => row.name));
2650
- const indexes = new Set(objects.filter((row) => row.type === "index").map((row) => row.name));
2651
- if (tables.has("http_responses"))
2652
- db.exec("DROP TABLE http_responses");
2653
- if (indexes.has("steps_upstream"))
2654
- db.exec("DROP INDEX steps_upstream");
2655
- if (indexes.has("steps_router"))
2656
- db.exec("DROP INDEX steps_router");
2657
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
2658
- for (const name of REMOVED_COLUMNS) {
2659
- if (columns.has(name))
2660
- db.exec(`ALTER TABLE steps DROP COLUMN ${name}`);
2661
- }
2662
- if (tables.has("events")) {
2663
- const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(", ");
2664
- db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
2665
- }
2666
- }
2667
- function addMissing(db) {
2668
- const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
2669
- if (columns.size > 0 && !columns.has("list_cost")) {
2670
- db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
2671
- }
2672
- }
2673
- function migrate(db) {
2674
- dropUnused(db);
2675
- addMissing(db);
2676
- }
2677
- var POSIX = process.platform !== "win32";
2678
- function hardenDirectory(path) {
2679
- if (!POSIX)
2680
- return;
2681
- try {
2682
- chmodSync(path, 448);
2683
- } catch {}
2684
- }
2685
- function hardenFiles(path) {
2686
- if (!POSIX || path === ":memory:")
2687
- return;
2688
- for (const file of [path, `${path}-wal`, `${path}-shm`]) {
2689
- try {
2690
- chmodSync(file, 384);
2691
- } catch {}
2692
- }
2693
- }
2694
- function prepareDirectory(path) {
2695
- if (path === ":memory:")
2696
- return;
2697
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
2698
- hardenDirectory(dirname(path));
2699
- }
2700
- function openStatsDb(path) {
2701
- if (path !== ":memory:")
2702
- ensureRegularFile(path);
2703
- prepareDirectory(path);
2704
- const db = new Database(path, { create: true });
2705
- db.exec("PRAGMA journal_mode = WAL");
2706
- db.exec("PRAGMA busy_timeout = 5000");
2707
- db.exec("PRAGMA synchronous = NORMAL");
2708
- db.exec(SCHEMA);
2709
- migrate(db);
2710
- db.query("INSERT INTO meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(SCHEMA_VERSION));
2711
- hardenFiles(path);
2712
- return db;
2713
- }
2714
- function openStatsDbReadOnly(path) {
2715
- ensureRegularFile(path);
2716
- const db = new Database(path, { readonly: true });
2717
- try {
2718
- db.query("SELECT 1 FROM steps LIMIT 1").get();
2719
- } catch (error) {
2720
- db.close();
2721
- throw error;
2722
- }
2723
- return db;
2724
- }
2725
- function openStatsDbWrite(path) {
2726
- if (path !== ":memory:")
2727
- ensureRegularFile(path);
2728
- prepareDirectory(path);
2729
- const db = new Database(path, { create: true });
2730
- db.exec("PRAGMA busy_timeout = 250");
2731
- db.exec("PRAGMA synchronous = NORMAL");
2732
- hardenFiles(path);
2733
- return db;
2734
- }
2735
- function recordStep(db, record) {
2736
- db.query(`INSERT INTO steps (
2737
- message_id, session_id, parent_id, provider_id, model_id, variant,
2738
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
2739
- created_at, streamed_at, completed_at, finish, recorded_at
2740
- ) VALUES (
2741
- $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
2742
- $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
2743
- $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
2744
- )
2745
- ON CONFLICT(message_id) DO UPDATE SET
2746
- session_id = excluded.session_id,
2747
- parent_id = COALESCE(excluded.parent_id, steps.parent_id),
2748
- provider_id = COALESCE(excluded.provider_id, steps.provider_id),
2749
- model_id = COALESCE(excluded.model_id, steps.model_id),
2750
- variant = COALESCE(excluded.variant, steps.variant),
2751
- input_tokens = excluded.input_tokens,
2752
- output_tokens = excluded.output_tokens,
2753
- reasoning_tokens = excluded.reasoning_tokens,
2754
- cache_read = excluded.cache_read,
2755
- cache_write = excluded.cache_write,
2756
- cost = excluded.cost,
2757
- -- A step that starts being charged loses its estimate; an estimate is
2758
- -- kept when a replayed event arrives without a price table.
2759
- list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
2760
- created_at = COALESCE(excluded.created_at, steps.created_at),
2761
- streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
2762
- completed_at = COALESCE(excluded.completed_at, steps.completed_at),
2763
- finish = COALESCE(excluded.finish, steps.finish),
2764
- recorded_at = excluded.recorded_at`).run({
2765
- $messageID: record.messageID,
2766
- $sessionID: record.sessionID,
2767
- $parentID: record.parentID ?? null,
2768
- $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
2769
- $modelID: record.modelID ?? null,
2770
- $variant: record.variant ?? null,
2771
- $input: record.input ?? 0,
2772
- $output: record.output ?? 0,
2773
- $reasoning: record.reasoning ?? 0,
2774
- $cacheRead: record.cacheRead ?? 0,
2775
- $cacheWrite: record.cacheWrite ?? 0,
2776
- $cost: record.cost ?? 0,
2777
- $listCost: (record.cost ?? 0) <= 0 && record.listCost !== undefined && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null,
2778
- $createdAt: record.createdAt ?? null,
2779
- $streamedAt: record.streamedAt ?? null,
2780
- $completedAt: record.completedAt ?? null,
2781
- $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
2782
- $recordedAt: record.recordedAt ?? Date.now()
2209
+ // src/rpc-client.ts
2210
+ function usageApi(client, location) {
2211
+ const rpc = client.rpc(UsageInsights);
2212
+ const options = (signal) => ({
2213
+ ...location !== undefined && location.directory !== undefined ? { location: { directory: location.directory } } : {},
2214
+ ...signal !== undefined ? { signal } : {}
2783
2215
  });
2784
- }
2785
- function recordPrompt(db, record) {
2786
- db.query(`INSERT INTO prompts (session_id, message_id, created_at)
2787
- VALUES ($sessionID, $messageID, $createdAt)
2788
- ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
2789
- $sessionID: record.sessionID,
2790
- $messageID: record.messageID,
2791
- $createdAt: record.createdAt ?? null
2792
- });
2793
- }
2794
- function recordEvent(db, record) {
2795
- db.query(`INSERT INTO events (session_id, kind, message_id, at, data)
2796
- VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
2797
- $sessionID: record.sessionID,
2798
- $kind: sanitizeLabel(record.kind, 64),
2799
- $messageID: record.messageID ?? null,
2800
- $at: record.at ?? Date.now(),
2801
- $data: jsonText(record.data)
2802
- });
2803
- }
2804
- function upsertSession(db, record) {
2805
- db.query(`INSERT INTO sessions (session_id, parent_id, directory, title, started_at, updated_at)
2806
- VALUES ($sessionID, $parentID, $directory, $title, $startedAt, $updatedAt)
2807
- ON CONFLICT(session_id) DO UPDATE SET
2808
- parent_id = COALESCE(excluded.parent_id, sessions.parent_id),
2809
- directory = COALESCE(excluded.directory, sessions.directory),
2810
- title = COALESCE(excluded.title, sessions.title),
2811
- started_at = COALESCE(sessions.started_at, excluded.started_at),
2812
- updated_at = COALESCE(excluded.updated_at, sessions.updated_at)`).run({
2813
- $sessionID: record.sessionID,
2814
- $parentID: record.parentID ?? null,
2815
- $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
2816
- $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
2817
- $startedAt: record.startedAt ?? null,
2818
- $updatedAt: record.updatedAt ?? null
2819
- });
2820
- }
2821
-
2822
- // src/stats/maintenance.ts
2823
- var STEP_TIME2 = "COALESCE(created_at, recorded_at)";
2824
- var DAY = 24 * 60 * 60 * 1000;
2825
- function size(path) {
2826
- try {
2827
- return statSync2(path).size;
2828
- } catch {
2829
- return 0;
2830
- }
2831
- }
2832
- function dbInfo(db, path, now = Date.now()) {
2833
- const tables = TABLES.map((table) => ({
2834
- name: table,
2835
- rows: db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n
2836
- }));
2837
- const window = db.query(`SELECT MIN(${STEP_TIME2}) AS first, MAX(${STEP_TIME2}) AS last FROM steps`).get();
2838
- const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
2839
- return {
2840
- path,
2841
- unpriced: hasListCost(db) ? db.query(`SELECT COUNT(*) AS n FROM steps
2842
- WHERE cost = 0 AND list_cost IS NULL
2843
- AND provider_id IS NOT NULL AND provider_id <> ''
2844
- AND model_id IS NOT NULL AND model_id <> ''
2845
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n : 0,
2846
- bytes: size(path),
2847
- walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
2848
- schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
2849
- tables,
2850
- firstAt: window.first ?? undefined,
2851
- lastAt: window.last ?? undefined,
2852
- removable: [30, 90, 365].map((days) => ({
2853
- days,
2854
- steps: db.query(`SELECT COUNT(*) AS n FROM steps WHERE ${STEP_TIME2} < ?`).get(now - days * DAY).n
2855
- }))
2856
- };
2857
- }
2858
- var PRUNE_BATCH = 5000;
2859
- function deleteBatched(db, table, where, cutoff) {
2860
- const statement = db.query(`DELETE FROM ${table} WHERE rowid IN (SELECT rowid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`);
2861
- let removed = 0;
2862
- for (;; ) {
2863
- const changes = statement.run(cutoff).changes;
2864
- removed += changes;
2865
- if (changes < PRUNE_BATCH)
2866
- break;
2867
- }
2868
- return removed;
2869
- }
2870
- function pruneOlderThan(db, cutoff) {
2871
2216
  return {
2872
- steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
2873
- prompts: deleteBatched(db, "prompts", "created_at IS NOT NULL AND created_at < ?", cutoff),
2874
- events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff)
2217
+ panel: (input, signal) => rpc.panel(input, options(signal)),
2218
+ turns: (input, signal) => rpc.turns(input, options(signal)),
2219
+ listCost: (input, signal) => rpc.listCost(input, options(signal)),
2220
+ filters: (signal) => rpc.filters({}, options(signal)),
2221
+ dbInfo: (signal) => rpc.dbInfo({}, options(signal)),
2222
+ prune: (input, signal) => rpc.prune(input, options(signal)),
2223
+ wipe: (input, signal) => rpc.wipe(input, options(signal)),
2224
+ vacuum: (input, signal) => rpc.vacuum(input, options(signal)),
2225
+ backfill: (input, signal) => rpc.backfill(input, options(signal)),
2226
+ onRecorded: (handler, signal) => rpc.events.on("recorded", (event) => handler(event.data), signal === undefined ? undefined : { signal })
2875
2227
  };
2876
2228
  }
2877
- function footprint(path) {
2878
- return size(path) + size(`${path}-wal`);
2879
- }
2880
- function vacuum(db, path) {
2881
- const before = footprint(path);
2882
- db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
2883
- db.exec("VACUUM");
2884
- const after = footprint(path);
2885
- return { before, after, freed: Math.max(0, before - after) };
2886
- }
2887
- function hasListCost(db) {
2888
- try {
2889
- return db.query("PRAGMA table_info(steps)").all().some((column) => column.name === "list_cost");
2890
- } catch {
2891
- return false;
2892
- }
2893
- }
2894
- var BACKFILL_BATCH = 1000;
2895
- function backfillListCost(db, price) {
2896
- if (!hasListCost(db))
2897
- return { candidates: 0, updated: 0 };
2898
- const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
2899
- WHERE cost = 0 AND list_cost IS NULL
2900
- AND provider_id IS NOT NULL AND provider_id <> ''
2901
- AND model_id IS NOT NULL AND model_id <> ''
2902
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
2903
- if (candidates === 0)
2904
- return { candidates: 0, updated: 0 };
2905
- const select = db.query(`SELECT rowid, provider_id, model_id,
2906
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
2907
- FROM steps
2908
- WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
2909
- AND provider_id IS NOT NULL AND provider_id <> ''
2910
- AND model_id IS NOT NULL AND model_id <> ''
2911
- AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
2912
- ORDER BY rowid
2913
- LIMIT ?`);
2914
- const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
2915
- let cursor = 0;
2916
- let updated = 0;
2917
- for (;; ) {
2918
- const rows = select.all(cursor, BACKFILL_BATCH);
2919
- if (rows.length === 0)
2920
- break;
2921
- db.transaction(() => {
2922
- for (const row of rows) {
2923
- const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
2924
- input: row.input_tokens ?? 0,
2925
- output: row.output_tokens ?? 0,
2926
- reasoning: row.reasoning_tokens ?? 0,
2927
- cacheRead: row.cache_read ?? 0,
2928
- cacheWrite: row.cache_write ?? 0
2929
- });
2930
- if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
2931
- continue;
2932
- if (update.run(estimate, row.rowid).changes > 0)
2933
- updated += 1;
2934
- }
2935
- })();
2936
- cursor = rows[rows.length - 1].rowid;
2937
- if (rows.length < BACKFILL_BATCH)
2938
- break;
2939
- }
2940
- return { candidates, updated };
2941
- }
2942
2229
 
2943
2230
  // src/panel.tsx
2944
2231
  function Panel(props) {
@@ -2947,71 +2234,77 @@ function Panel(props) {
2947
2234
  const [help, setHelp] = createSignal(false);
2948
2235
  const [tick, setTick] = createSignal(0);
2949
2236
  const [busy, setBusy] = createSignal(false);
2237
+ const [lines, setLines] = createSignal([]);
2238
+ const [database, setDatabase] = createSignal(undefined);
2239
+ const [loading, setLoading] = createSignal(false);
2240
+ const [error, setError] = createSignal(undefined);
2241
+ let generation = 0;
2950
2242
  let scroller;
2951
- const width = () => Math.max(60, props.input.width - 4);
2243
+ const width = () => clampPanelWidth(Math.max(60, props.input.width - 4));
2952
2244
  const view = () => sanitizeSettings(props.settings).view;
2953
2245
  const settings = () => sanitizeSettings(props.settings);
2954
- const filters = () => {
2246
+ const api = () => usageApi(props.ctx.client, props.ctx.location);
2247
+ function errorMessage(cause) {
2248
+ if (cause instanceof Error)
2249
+ return cause.message;
2250
+ if (cause !== null && typeof cause === "object" && "message" in cause)
2251
+ return String(cause.message);
2252
+ return "usage service unavailable";
2253
+ }
2254
+ const rowKey = (row) => `${row.kind}:${row.value}${row.variant !== undefined ? `#${row.variant}` : ""}`;
2255
+ const request = createMemo(() => {
2256
+ tick();
2257
+ props.deps.refresh?.();
2258
+ if (help())
2259
+ return;
2955
2260
  const current = settings();
2956
2261
  return {
2957
- ...current.modelID !== "" ? {
2958
- modelID: current.modelID
2262
+ sessionID: props.input.sessionID,
2263
+ settings: current,
2264
+ ...detail() !== undefined ? {
2265
+ detail: detail()
2959
2266
  } : {},
2960
- ...current.providerID !== "" ? {
2961
- provider: current.providerID
2962
- } : {}
2267
+ width: width(),
2268
+ busy: busy()
2963
2269
  };
2964
- };
2965
- const rowKey = (row) => `${row.kind}:${row.value}${row.variant !== undefined ? `#${row.variant}` : ""}`;
2966
- const database = createMemo(() => {
2967
- tick();
2968
- const handle = props.deps.db();
2969
- if (handle === undefined)
2970
- return;
2971
- try {
2972
- return dbInfo(handle, props.deps.dbPath(), props.deps.now());
2973
- } catch {
2270
+ });
2271
+ createEffect(() => {
2272
+ const input = request();
2273
+ const current = ++generation;
2274
+ if (input === undefined) {
2275
+ setLines(helpLines(width()));
2276
+ setDatabase(undefined);
2277
+ setError(undefined);
2278
+ setLoading(false);
2974
2279
  return;
2975
2280
  }
2281
+ setLoading(true);
2282
+ api().panel(input).then((result) => {
2283
+ if (current !== generation)
2284
+ return;
2285
+ setLines(result.lines);
2286
+ setDatabase(result.database);
2287
+ setError(undefined);
2288
+ }).catch((cause) => {
2289
+ if (current !== generation)
2290
+ return;
2291
+ setError(errorMessage(cause));
2292
+ if (lines().length === 0)
2293
+ setLines([]);
2294
+ }).finally(() => {
2295
+ if (current === generation)
2296
+ setLoading(false);
2297
+ });
2976
2298
  });
2977
2299
  const content = createMemo(() => {
2978
- tick();
2979
- props.deps.refresh?.();
2980
- const current = settings();
2981
- if (help())
2982
- return helpLines(width());
2983
- const db = props.deps.db();
2984
- if (db === undefined) {
2300
+ if (error() !== undefined && lines().length === 0) {
2985
2301
  return [{
2986
- text: `stats database is not readable at ${props.deps.dbPath()}; enable the usage-insights server plugin in opencode.json`,
2302
+ text: `usage service unavailable: ${error()}`,
2987
2303
  tone: "warning"
2988
2304
  }];
2989
2305
  }
2990
- const info = current.view === "db" ? database() : undefined;
2991
- const request = {
2992
- db,
2993
- view: current.view,
2994
- range: current.range,
2995
- filters: filters(),
2996
- granularity: current.granularity,
2997
- turnsScope: current.turnsScope,
2998
- sort: current.sort,
2999
- sortDesc: current.sortDesc,
3000
- sessionID: props.input.sessionID,
3001
- sessionStart: props.deps.sessionStart(props.input.sessionID),
3002
- now: props.deps.now(),
3003
- format: props.format,
3004
- estimates: props.format?.estimates !== false,
3005
- ...detail() !== undefined ? {
3006
- detail: detail()
3007
- } : {},
3008
- ...info !== undefined ? {
3009
- database: info
3010
- } : {},
3011
- busy: busy(),
3012
- width: width()
3013
- };
3014
- return buildPanel(request);
2306
+ const visible = (line) => props.maintenance !== false || line.row?.kind !== "prune" && line.row?.kind !== "wipe";
2307
+ return lines().filter(visible);
3015
2308
  });
3016
2309
  const header = createMemo(() => {
3017
2310
  const current = settings();
@@ -3078,6 +2371,10 @@ function Panel(props) {
3078
2371
  prune(Number.parseInt(entry.row.value, 10));
3079
2372
  return;
3080
2373
  }
2374
+ if (entry.row.kind === "wipe") {
2375
+ wipe();
2376
+ return;
2377
+ }
3081
2378
  setDetail(entry.row);
3082
2379
  setAnchor(undefined);
3083
2380
  }
@@ -3089,6 +2386,13 @@ function Panel(props) {
3089
2386
  }
3090
2387
  }
3091
2388
  async function prune(days) {
2389
+ if (props.maintenance === false) {
2390
+ props.ctx.ui.toast.show({
2391
+ message: "database maintenance is disabled",
2392
+ variant: "warning"
2393
+ });
2394
+ return;
2395
+ }
3092
2396
  if (!Number.isFinite(days))
3093
2397
  return;
3094
2398
  if (sessionRunning()) {
@@ -3110,27 +2414,75 @@ function Panel(props) {
3110
2414
  });
3111
2415
  if (confirmed !== true)
3112
2416
  return;
3113
- const cutoff = props.deps.now() - days * 24 * 60 * 60 * 1000;
3114
- const result = props.deps.withWrite?.((handle) => pruneOlderThan(handle, cutoff));
3115
- if (result === undefined) {
2417
+ try {
2418
+ const result = await api().prune({
2419
+ days,
2420
+ confirm: true
2421
+ });
2422
+ props.ctx.ui.toast.show({
2423
+ message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
2424
+ variant: "success"
2425
+ });
2426
+ } catch (cause) {
3116
2427
  props.ctx.ui.toast.show({
3117
- message: "the recorder is writing: try again in a moment",
2428
+ message: errorMessage(cause),
3118
2429
  variant: "warning"
3119
2430
  });
3120
- } else {
2431
+ }
2432
+ setAnchor(undefined);
2433
+ setTick((value) => value + 1);
2434
+ props.deps.bump?.();
2435
+ }
2436
+ async function wipe() {
2437
+ if (props.maintenance === false) {
2438
+ props.ctx.ui.toast.show({
2439
+ message: "database maintenance is disabled",
2440
+ variant: "warning"
2441
+ });
2442
+ return;
2443
+ }
2444
+ if (sessionRunning()) {
3121
2445
  props.ctx.ui.toast.show({
3122
- message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions`,
2446
+ message: "the session is running: wipe again when it is idle",
2447
+ variant: "warning"
2448
+ });
2449
+ return;
2450
+ }
2451
+ const info = database();
2452
+ const steps = info?.tables.find((table) => table.name === "steps")?.rows ?? 0;
2453
+ const sessions = info?.tables.find((table) => table.name === "sessions")?.rows ?? 0;
2454
+ const confirmed = await props.ctx.ui.dialog.confirm({
2455
+ title: "Wipe all recorded usage",
2456
+ message: `${formatCount(steps)} steps and ${formatCount(sessions)} sessions would be deleted, with their prompts, compactions and other usage. This cannot be undone.`,
2457
+ label: {
2458
+ confirm: "Wipe",
2459
+ cancel: "Keep"
2460
+ }
2461
+ });
2462
+ if (confirmed !== true)
2463
+ return;
2464
+ try {
2465
+ const result = await api().wipe({
2466
+ confirm: true
2467
+ });
2468
+ props.ctx.ui.toast.show({
2469
+ message: `wiped ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage \xB7 ${result.sessions} sessions`,
3123
2470
  variant: "success"
3124
2471
  });
2472
+ } catch (cause) {
2473
+ props.ctx.ui.toast.show({
2474
+ message: errorMessage(cause),
2475
+ variant: "warning"
2476
+ });
3125
2477
  }
3126
2478
  setAnchor(undefined);
3127
2479
  setTick((value) => value + 1);
3128
2480
  props.deps.bump?.();
3129
2481
  }
3130
2482
  async function backfillEstimates() {
3131
- if (props.format?.estimates === false) {
2483
+ if (props.maintenance === false) {
3132
2484
  props.ctx.ui.toast.show({
3133
- message: "list-price estimates are turned off",
2485
+ message: "database maintenance is disabled",
3134
2486
  variant: "warning"
3135
2487
  });
3136
2488
  return;
@@ -3151,7 +2503,7 @@ function Panel(props) {
3151
2503
  return;
3152
2504
  }
3153
2505
  const candidates = info?.unpriced ?? 0;
3154
- if (candidates === 0) {
2506
+ if (info !== undefined && candidates === 0) {
3155
2507
  props.ctx.ui.toast.show({
3156
2508
  message: "every $0 step already has a list estimate"
3157
2509
  });
@@ -3167,22 +2519,31 @@ function Panel(props) {
3167
2519
  });
3168
2520
  if (confirmed !== true)
3169
2521
  return;
3170
- const result = props.deps.backfill?.();
3171
- if (result === undefined) {
3172
- props.ctx.ui.toast.show({
3173
- message: "the price catalog is unavailable: try again in a moment",
3174
- variant: "warning"
2522
+ try {
2523
+ const result = await api().backfill({
2524
+ confirm: true
3175
2525
  });
3176
- } else {
3177
2526
  props.ctx.ui.toast.show({
3178
2527
  message: `backfilled ${formatCount(result.updated)} of ${formatCount(result.candidates)} steps`,
3179
2528
  variant: result.updated === 0 ? "warning" : "success"
3180
2529
  });
2530
+ } catch (cause) {
2531
+ props.ctx.ui.toast.show({
2532
+ message: errorMessage(cause),
2533
+ variant: "warning"
2534
+ });
3181
2535
  }
3182
2536
  setTick((value) => value + 1);
3183
2537
  props.deps.bump?.();
3184
2538
  }
3185
2539
  async function compact() {
2540
+ if (props.maintenance === false) {
2541
+ props.ctx.ui.toast.show({
2542
+ message: "database maintenance is disabled",
2543
+ variant: "warning"
2544
+ });
2545
+ return;
2546
+ }
3186
2547
  if (sessionRunning()) {
3187
2548
  props.ctx.ui.toast.show({
3188
2549
  message: "the session is running: compact again when it is idle",
@@ -3200,25 +2561,21 @@ function Panel(props) {
3200
2561
  });
3201
2562
  if (confirmed !== true)
3202
2563
  return;
3203
- const path = props.deps.dbPath();
3204
- let result;
3205
2564
  try {
3206
- result = props.deps.withWrite?.((handle) => vacuum(handle, path));
3207
- } catch {
3208
- result = undefined;
3209
- }
3210
- if (result === undefined) {
3211
- setBusy(true);
3212
- props.ctx.ui.toast.show({
3213
- message: "the recorder is writing: try again in a moment",
3214
- variant: "warning"
2565
+ const result = await api().vacuum({
2566
+ confirm: true
3215
2567
  });
3216
- } else {
3217
2568
  setBusy(false);
3218
2569
  props.ctx.ui.toast.show({
3219
2570
  message: `compacted: ${(result.freed / 1048576).toFixed(1)} MB back`,
3220
2571
  variant: "success"
3221
2572
  });
2573
+ } catch (cause) {
2574
+ setBusy(true);
2575
+ props.ctx.ui.toast.show({
2576
+ message: errorMessage(cause),
2577
+ variant: "warning"
2578
+ });
3222
2579
  }
3223
2580
  setTick((value) => value + 1);
3224
2581
  }
@@ -3229,10 +2586,16 @@ function Panel(props) {
3229
2586
  setAnchor(undefined);
3230
2587
  }
3231
2588
  async function pickFilter(kind) {
3232
- const db = props.deps.db();
3233
- if (db === undefined)
2589
+ let all;
2590
+ try {
2591
+ all = await api().filters();
2592
+ } catch (cause) {
2593
+ props.ctx.ui.toast.show({
2594
+ message: errorMessage(cause),
2595
+ variant: "warning"
2596
+ });
3234
2597
  return;
3235
- const all = filterOptions(db);
2598
+ }
3236
2599
  const list = kind === "model" ? all.models : all.providers;
3237
2600
  const current = settings();
3238
2601
  const selected = kind === "model" ? current.modelID : current.providerID;
@@ -3325,13 +2688,13 @@ function Panel(props) {
3325
2688
  const selectedBackground = () => props.ctx.theme.background.raised.high;
3326
2689
  const cursorIndex = () => cursor();
3327
2690
  return (() => {
3328
- var _el$ = _$createElement("box"), _el$2 = _$createElement("scrollbox"), _el$3 = _$createElement("text"), _el$4 = _$createElement("text");
2691
+ var _el$ = _$createElement("box"), _el$2 = _$createElement("scrollbox"), _el$5 = _$createElement("text"), _el$6 = _$createElement("text");
3329
2692
  _$insertNode(_el$, _el$2);
3330
2693
  _$setProp(_el$, "flexDirection", "column");
3331
2694
  _$setProp(_el$, "paddingLeft", 1);
3332
2695
  _$setProp(_el$, "paddingRight", 1);
3333
- _$insertNode(_el$2, _el$3);
3334
- _$insertNode(_el$2, _el$4);
2696
+ _$insertNode(_el$2, _el$5);
2697
+ _$insertNode(_el$2, _el$6);
3335
2698
  _$use((target) => {
3336
2699
  scroller = target;
3337
2700
  const focusable = target;
@@ -3348,12 +2711,12 @@ function Panel(props) {
3348
2711
  return header();
3349
2712
  },
3350
2713
  children: (line) => (() => {
3351
- var _el$5 = _$createElement("text");
3352
- _$insert(_el$5, () => line.text);
3353
- _$effect((_$p) => _$setProp(_el$5, "fg", color(line.tone), _$p));
3354
- return _el$5;
2714
+ var _el$7 = _$createElement("text");
2715
+ _$insert(_el$7, () => line.text);
2716
+ _$effect((_$p) => _$setProp(_el$7, "fg", color(line.tone), _$p));
2717
+ return _el$7;
3355
2718
  })()
3356
- }), _el$3);
2719
+ }), _el$5);
3357
2720
  _$insert(_el$2, _$createComponent(For, {
3358
2721
  get each() {
3359
2722
  return content();
@@ -3361,14 +2724,14 @@ function Panel(props) {
3361
2724
  children: (line, index) => {
3362
2725
  const selected = () => index() === selectedLineIndex(content(), cursorIndex());
3363
2726
  return (() => {
3364
- var _el$6 = _$createElement("text");
3365
- _$insert(_el$6, () => line.text);
2727
+ var _el$8 = _$createElement("text");
2728
+ _$insert(_el$8, () => line.text);
3366
2729
  _$effect((_p$) => {
3367
2730
  var _v$3 = `line-${index()}`, _v$4 = color(line.tone), _v$5 = selected() ? selectedBackground() : undefined, _v$6 = selected() ? TextAttributes.BOLD : undefined;
3368
- _v$3 !== _p$.e && (_p$.e = _$setProp(_el$6, "id", _v$3, _p$.e));
3369
- _v$4 !== _p$.t && (_p$.t = _$setProp(_el$6, "fg", _v$4, _p$.t));
3370
- _v$5 !== _p$.a && (_p$.a = _$setProp(_el$6, "bg", _v$5, _p$.a));
3371
- _v$6 !== _p$.o && (_p$.o = _$setProp(_el$6, "attributes", _v$6, _p$.o));
2731
+ _v$3 !== _p$.e && (_p$.e = _$setProp(_el$8, "id", _v$3, _p$.e));
2732
+ _v$4 !== _p$.t && (_p$.t = _$setProp(_el$8, "fg", _v$4, _p$.t));
2733
+ _v$5 !== _p$.a && (_p$.a = _$setProp(_el$8, "bg", _v$5, _p$.a));
2734
+ _v$6 !== _p$.o && (_p$.o = _$setProp(_el$8, "attributes", _v$6, _p$.o));
3372
2735
  return _p$;
3373
2736
  }, {
3374
2737
  e: undefined,
@@ -3376,15 +2739,26 @@ function Panel(props) {
3376
2739
  a: undefined,
3377
2740
  o: undefined
3378
2741
  });
3379
- return _el$6;
2742
+ return _el$8;
3380
2743
  })();
3381
2744
  }
3382
- }), _el$3);
3383
- _$insert(_el$4, () => keysFor(view()));
2745
+ }), _el$5);
2746
+ _$insert(_el$2, _$createComponent(Show, {
2747
+ get when() {
2748
+ return loading();
2749
+ },
2750
+ get children() {
2751
+ var _el$3 = _$createElement("text");
2752
+ _$insertNode(_el$3, _$createTextNode(`loading\u2026`));
2753
+ _$effect((_$p) => _$setProp(_el$3, "fg", props.ctx.theme.text.muted, _$p));
2754
+ return _el$3;
2755
+ }
2756
+ }), _el$5);
2757
+ _$insert(_el$6, () => keysFor(view()));
3384
2758
  _$effect((_p$) => {
3385
2759
  var _v$ = props.ctx.theme.text.muted, _v$2 = props.ctx.theme.text.muted;
3386
- _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, "fg", _v$, _p$.e));
3387
- _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, "fg", _v$2, _p$.t));
2760
+ _v$ !== _p$.e && (_p$.e = _$setProp(_el$5, "fg", _v$, _p$.e));
2761
+ _v$2 !== _p$.t && (_p$.t = _$setProp(_el$6, "fg", _v$2, _p$.t));
3388
2762
  return _p$;
3389
2763
  }, {
3390
2764
  e: undefined,
@@ -3431,8 +2805,13 @@ function priceTable(models) {
3431
2805
  for (const cost of model.cost) {
3432
2806
  if (cost === null || cost === undefined)
3433
2807
  continue;
3434
- const size = cost.tier?.size;
3435
- const tier = cost.tier !== undefined && typeof size === "number" && Number.isFinite(size) && size >= 0 ? { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size } : undefined;
2808
+ let tier;
2809
+ if (cost.tier !== undefined) {
2810
+ const size = cost.tier.size;
2811
+ if (typeof size !== "number" || !Number.isFinite(size))
2812
+ continue;
2813
+ tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
2814
+ }
3436
2815
  tiers.push({
3437
2816
  ...tier !== undefined ? { tier } : {},
3438
2817
  input: money(cost.input),
@@ -3475,12 +2854,15 @@ function costOf(table, ref, usage) {
3475
2854
  }
3476
2855
 
3477
2856
  // src/sidebar.tsx
3478
- import { effect as _$effect2 } from "@opentui/solid";
3479
2857
  import { insert as _$insert2 } from "@opentui/solid";
2858
+ import { effect as _$effect2 } from "@opentui/solid";
2859
+ import { createTextNode as _$createTextNode2 } from "@opentui/solid";
2860
+ import { insertNode as _$insertNode2 } from "@opentui/solid";
2861
+ import { memo as _$memo } from "@opentui/solid";
3480
2862
  import { createComponent as _$createComponent2 } from "@opentui/solid";
3481
2863
  import { setProp as _$setProp2 } from "@opentui/solid";
3482
2864
  import { createElement as _$createElement2 } from "@opentui/solid";
3483
- import { For as For2, createMemo as createMemo2 } from "solid-js";
2865
+ import { For as For2, Show as Show2, createEffect as createEffect2, createMemo as createMemo2, createSignal as createSignal2, onCleanup } from "solid-js";
3484
2866
  function TurnsSidebar(props) {
3485
2867
  const color = (tone) => {
3486
2868
  switch (tone) {
@@ -3494,30 +2876,49 @@ function TurnsSidebar(props) {
3494
2876
  return props.ctx.theme.text.base;
3495
2877
  }
3496
2878
  };
3497
- const lines = createMemo2(() => {
2879
+ const [data, setData] = createSignal2(undefined);
2880
+ const [error, setError] = createSignal2(undefined);
2881
+ const [loading, setLoading] = createSignal2(false);
2882
+ let generation = 0;
2883
+ createEffect2(() => {
3498
2884
  props.deps.refresh();
3499
- const db = props.deps.db();
3500
- if (db === undefined)
3501
- return [];
3502
- const budget = props.deps.budget ?? 34;
3503
- try {
3504
- const summary = sessionSummaryLines(overview(db, undefined, {
3505
- sessionID: props.sessionID
3506
- }), budget, props.options?.estimates !== false);
3507
- const history = sidebarLines(turns(db, {
3508
- sessionID: props.sessionID,
3509
- limit: props.deps.limit
3510
- }), {
3511
- ...props.options,
3512
- budget
3513
- });
3514
- return [...summary, {
3515
- text: "turns",
3516
- tone: "accent"
3517
- }, ...history];
3518
- } catch {
2885
+ const input = {
2886
+ sessionID: props.sessionID,
2887
+ limit: props.deps.limit,
2888
+ width: props.deps.budget ?? 34
2889
+ };
2890
+ const current = ++generation;
2891
+ const controller = new AbortController;
2892
+ onCleanup(() => controller.abort());
2893
+ setLoading(true);
2894
+ usageApi(props.ctx.client, props.ctx.location).turns(input, controller.signal).then((result) => {
2895
+ if (current !== generation)
2896
+ return;
2897
+ setData(result);
2898
+ setError(undefined);
2899
+ }).catch((cause) => {
2900
+ if (current !== generation)
2901
+ return;
2902
+ setError(cause);
2903
+ }).finally(() => {
2904
+ if (current === generation)
2905
+ setLoading(false);
2906
+ });
2907
+ });
2908
+ const lines = createMemo2(() => {
2909
+ const result = data();
2910
+ if (result === undefined) {
2911
+ if (error() !== undefined)
2912
+ return [{
2913
+ text: "usage history unavailable",
2914
+ tone: "muted"
2915
+ }];
3519
2916
  return [];
3520
2917
  }
2918
+ return [...result.summary, {
2919
+ text: "turns",
2920
+ tone: "accent"
2921
+ }, ...result.history];
3521
2922
  });
3522
2923
  return (() => {
3523
2924
  var _el$ = _$createElement2("box");
@@ -3529,12 +2930,23 @@ function TurnsSidebar(props) {
3529
2930
  return lines();
3530
2931
  },
3531
2932
  children: (line) => (() => {
2933
+ var _el$4 = _$createElement2("text");
2934
+ _$insert2(_el$4, () => line.text);
2935
+ _$effect2((_$p) => _$setProp2(_el$4, "fg", color(line.tone), _$p));
2936
+ return _el$4;
2937
+ })()
2938
+ }), null);
2939
+ _$insert2(_el$, _$createComponent2(Show2, {
2940
+ get when() {
2941
+ return _$memo(() => !!loading())() && data() !== undefined;
2942
+ },
2943
+ get children() {
3532
2944
  var _el$2 = _$createElement2("text");
3533
- _$insert2(_el$2, () => line.text);
3534
- _$effect2((_$p) => _$setProp2(_el$2, "fg", color(line.tone), _$p));
2945
+ _$insertNode2(_el$2, _$createTextNode2(`\u2026`));
2946
+ _$effect2((_$p) => _$setProp2(_el$2, "fg", props.ctx.theme.text.muted, _$p));
3535
2947
  return _el$2;
3536
- })()
3537
- }));
2948
+ }
2949
+ }), null);
3538
2950
  return _el$;
3539
2951
  })();
3540
2952
  }
@@ -3585,14 +2997,14 @@ var tui_default = Plugin.define({
3585
2997
  const patchSettings = (mutation) => {
3586
2998
  updateSettings(mutation);
3587
2999
  };
3588
- const [refresh, setRefresh] = createSignal2(0);
3589
- let database;
3590
- let databaseFailed = false;
3000
+ const [refresh, setRefresh] = createSignal3(0);
3001
+ const [listCosts, setListCosts] = createSignal3({});
3002
+ const pendingListCost = new Set;
3003
+ const dirtyListCost = new Set;
3004
+ const api = usageApi(ctx.client, ctx.location);
3591
3005
  let refreshTimer;
3592
3006
  let lastRefresh = 0;
3593
- const sessionCostCache = new Map;
3594
3007
  function bumpRefresh() {
3595
- sessionCostCache.clear();
3596
3008
  const now = Date.now();
3597
3009
  const wait = lastRefresh + REFRESH_THROTTLE_MS - now;
3598
3010
  if (wait <= 0) {
@@ -3609,62 +3021,39 @@ var tui_default = Plugin.define({
3609
3021
  }, wait);
3610
3022
  refreshTimer.unref?.();
3611
3023
  }
3612
- function db() {
3613
- if (database !== undefined)
3614
- return database;
3615
- if (databaseFailed)
3616
- return;
3617
- try {
3618
- database = openStatsDbReadOnly(resolveDbPath(options.db));
3619
- return database;
3620
- } catch {
3621
- databaseFailed = true;
3622
- return;
3623
- }
3624
- }
3625
- function sessionListCostFor(sessionID) {
3024
+ function listCostFor(sessionID) {
3626
3025
  if (!pricing)
3627
3026
  return 0;
3628
- const cached = sessionCostCache.get(sessionID);
3629
- if (cached !== undefined)
3630
- return cached;
3631
- const handle = db();
3632
- if (handle === undefined)
3633
- return 0;
3634
- try {
3635
- const value = sessionListCost(handle, sessionID);
3636
- if (sessionCostCache.size >= 512) {
3637
- const oldest = sessionCostCache.keys().next();
3638
- if (oldest.done !== true)
3639
- sessionCostCache.delete(oldest.value);
3640
- }
3641
- sessionCostCache.set(sessionID, value);
3642
- return value;
3643
- } catch {
3644
- return 0;
3645
- }
3646
- }
3647
- function withWrite(run) {
3648
- let handle;
3649
- try {
3650
- handle = openStatsDbWrite(resolveDbPath(options.db));
3651
- return run(handle);
3652
- } catch {
3653
- return;
3654
- } finally {
3655
- handle?.close();
3656
- }
3027
+ return listCosts()[sessionID] ?? 0;
3657
3028
  }
3658
- function backfill() {
3029
+ async function loadListCost(sessionID) {
3659
3030
  if (!pricing)
3660
3031
  return;
3661
- const table = priceTableFor();
3662
- if (table === undefined)
3032
+ if (pendingListCost.has(sessionID)) {
3033
+ dirtyListCost.add(sessionID);
3663
3034
  return;
3664
- return withWrite((handle) => backfillListCost(handle, (ref, tokens) => costOf(table, ref, tokens)));
3665
- }
3666
- function sessionStart(sessionID) {
3667
- return ctx.data.session.get(sessionID)?.time.created;
3035
+ }
3036
+ pendingListCost.add(sessionID);
3037
+ try {
3038
+ const result = await api.listCost({
3039
+ sessionID
3040
+ });
3041
+ setListCosts((current) => {
3042
+ const next = {
3043
+ ...current,
3044
+ [sessionID]: result.cost
3045
+ };
3046
+ const keys = Object.keys(next);
3047
+ if (keys.length > 512)
3048
+ for (const key of keys.slice(0, keys.length - 512))
3049
+ delete next[key];
3050
+ return next;
3051
+ });
3052
+ } catch {} finally {
3053
+ pendingListCost.delete(sessionID);
3054
+ if (dirtyListCost.delete(sessionID))
3055
+ loadListCost(sessionID);
3056
+ }
3668
3057
  }
3669
3058
  function sessionIdle(sessionID) {
3670
3059
  try {
@@ -3680,7 +3069,7 @@ var tui_default = Plugin.define({
3680
3069
  refresh();
3681
3070
  const messages = ctx.data.session.message.list(sessionID);
3682
3071
  const info = ctx.data.session.get(sessionID);
3683
- const session = info === undefined ? undefined : sessionTotals(info, sessionListCostFor(sessionID));
3072
+ const session = info === undefined ? undefined : sessionTotals(info, listCostFor(sessionID));
3684
3073
  return computeTurn(toTranscriptTail(messages, 2, priceFor()), session);
3685
3074
  }
3686
3075
  function toneColor(tone) {
@@ -3697,7 +3086,12 @@ var tui_default = Plugin.define({
3697
3086
  turnTotals: options.turnTotals,
3698
3087
  estimates: pricing
3699
3088
  }));
3700
- return _$createComponent3(Show, {
3089
+ createEffect3(() => {
3090
+ props.sessionID;
3091
+ refresh();
3092
+ loadListCost(props.sessionID);
3093
+ });
3094
+ return _$createComponent3(Show3, {
3701
3095
  get when() {
3702
3096
  return parts().length > 0;
3703
3097
  },
@@ -3735,24 +3129,13 @@ var tui_default = Plugin.define({
3735
3129
  input,
3736
3130
  ctx,
3737
3131
  deps: {
3738
- db,
3739
- dbPath: () => resolveDbPath(options.db),
3740
- withWrite,
3741
- backfill,
3742
- now: () => Date.now(),
3743
- sessionStart,
3744
3132
  refresh,
3745
3133
  bump: bumpRefresh
3746
3134
  },
3747
3135
  settings,
3748
3136
  update: patchSettings,
3749
- get format() {
3750
- return {
3751
- labels: options.labels,
3752
- fields: options.fields,
3753
- turnTotals: options.turnTotals,
3754
- estimates: pricing
3755
- };
3137
+ get maintenance() {
3138
+ return options.maintenance !== false;
3756
3139
  }
3757
3140
  }) : null
3758
3141
  }) : () => {};
@@ -3765,17 +3148,8 @@ var tui_default = Plugin.define({
3765
3148
  ctx,
3766
3149
  get deps() {
3767
3150
  return {
3768
- db,
3769
3151
  refresh,
3770
- limit: Math.max(1, Math.round(options.sidebarTurns ?? 5))
3771
- };
3772
- },
3773
- get options() {
3774
- return {
3775
- labels: options.labels,
3776
- fields: options.fields,
3777
- turnTotals: options.turnTotals,
3778
- estimates: pricing
3152
+ limit: clampTurnsLimit(options.sidebarTurns ?? 8)
3779
3153
  };
3780
3154
  }
3781
3155
  })
@@ -3825,7 +3199,15 @@ var tui_default = Plugin.define({
3825
3199
  };
3826
3200
  });
3827
3201
  }
3202
+ const watchRecorded = () => {
3203
+ try {
3204
+ return api.onRecorded(() => bumpRefresh());
3205
+ } catch {
3206
+ return () => {};
3207
+ }
3208
+ };
3828
3209
  const disposeEvents = [
3210
+ watchRecorded(),
3829
3211
  ctx.data.on("session.step.ended", () => bumpRefresh()),
3830
3212
  ctx.data.on("session.execution.succeeded", () => bumpRefresh()),
3831
3213
  ctx.data.on("session.execution.failed", () => bumpRefresh()),
@@ -3836,11 +3218,15 @@ var tui_default = Plugin.define({
3836
3218
  })
3837
3219
  ];
3838
3220
  __test.line = lineFor;
3839
- __test.lineText = (sessionID) => lineText(lineParts(lineFor(sessionID), {
3840
- labels: options.labels,
3841
- fields: options.fields,
3842
- estimates: pricing
3843
- }));
3221
+ __test.lineText = (sessionID) => {
3222
+ loadListCost(sessionID);
3223
+ return lineText(lineParts(lineFor(sessionID), {
3224
+ labels: options.labels,
3225
+ fields: options.fields,
3226
+ turnTotals: options.turnTotals,
3227
+ estimates: pricing
3228
+ }));
3229
+ };
3844
3230
  __test.open = open;
3845
3231
  __test.state = () => {
3846
3232
  const current = sanitizeSettings(settings);
@@ -3857,7 +3243,6 @@ var tui_default = Plugin.define({
3857
3243
  disposeLine();
3858
3244
  disposePanel();
3859
3245
  disposeSidebar();
3860
- database?.close();
3861
3246
  };
3862
3247
  }
3863
3248
  });
@@ -3866,4 +3251,4 @@ export {
3866
3251
  tui_default as default
3867
3252
  };
3868
3253
 
3869
- //# debugId=EAEFC12B046D781964756E2164756E21
3254
+ //# debugId=3E4F6620631DC12564756E2164756E21