opencode-usage-insights 0.1.2 → 0.1.3

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
@@ -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)}`;
@@ -429,18 +444,24 @@ function toModelRef(model) {
429
444
  return { providerID: model.providerID, id: model.id };
430
445
  return { providerID: model.providerID, id: model.id, variant: model.variant };
431
446
  }
447
+ function countOf2(value) {
448
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
449
+ }
450
+ function amountOf2(value) {
451
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
452
+ }
432
453
  function sessionTotals(info, listCost = 0) {
433
454
  if (info === undefined)
434
455
  return;
435
456
  const tokens = info.tokens;
436
457
  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,
458
+ input: countOf2(tokens?.input),
459
+ cached: countOf2(tokens?.cache?.read),
460
+ output: countOf2(tokens?.output),
461
+ reasoning: countOf2(tokens?.reasoning),
462
+ cacheWrite: countOf2(tokens?.cache?.write),
463
+ cost: amountOf2(info.cost),
464
+ listCost: amountOf2(listCost),
444
465
  steps: 0
445
466
  };
446
467
  }
@@ -470,6 +491,66 @@ function sessionListCost(db, sessionID) {
470
491
  const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
471
492
  return row?.listCost ?? 0;
472
493
  }
494
+ var EMPTY_OTHER = { entries: 0, cost: 0 };
495
+ function hasUsageTable(db) {
496
+ try {
497
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'").get() !== null;
498
+ } catch {
499
+ return false;
500
+ }
501
+ }
502
+ function otherWhere(range, filters) {
503
+ if (filters?.modelID !== undefined && filters.modelID !== "")
504
+ return;
505
+ if (filters?.modelKey !== undefined && filters.modelKey !== "")
506
+ return;
507
+ if (filters?.provider !== undefined && filters.provider !== "")
508
+ return;
509
+ const span = rangeWhere(range, "at");
510
+ const clauses = span.where === "" ? [] : [span.where.slice("WHERE ".length)];
511
+ const params = [...span.params];
512
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
513
+ clauses.push("session_id = ?");
514
+ params.push(filters.sessionID);
515
+ }
516
+ return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
517
+ }
518
+ function otherUsage(db, range, filters) {
519
+ const filter = otherWhere(range, filters);
520
+ if (filter === undefined || !hasUsageTable(db))
521
+ return { ...EMPTY_OTHER };
522
+ try {
523
+ const row = db.query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`).get(...filter.params);
524
+ return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 };
525
+ } catch {
526
+ return { ...EMPTY_OTHER };
527
+ }
528
+ }
529
+ function otherUsageBySession(db, range, filters) {
530
+ const out = new Map;
531
+ const filter = otherWhere(range, filters);
532
+ if (filter === undefined || !hasUsageTable(db))
533
+ return out;
534
+ try {
535
+ const rows = db.query(`SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost
536
+ FROM usage ${filter.where}
537
+ GROUP BY session_id`).all(...filter.params);
538
+ for (const row of rows)
539
+ out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 });
540
+ } catch {}
541
+ return out;
542
+ }
543
+ function otherUsageRows(db, range, filters) {
544
+ const filter = otherWhere(range, filters);
545
+ if (filter === undefined || !hasUsageTable(db))
546
+ return [];
547
+ const where = filter.where === "" ? "WHERE at IS NOT NULL" : `${filter.where} AND at IS NOT NULL`;
548
+ try {
549
+ return db.query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`).all(...filter.params);
550
+ } catch {
551
+ return [];
552
+ }
553
+ }
473
554
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
474
555
  var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
475
556
  function modelKey(modelID, variant) {
@@ -547,12 +628,22 @@ function overview(db, range, filters) {
547
628
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
548
629
  FROM steps ${steps.where}`).get(...steps.params);
549
630
  const prompts = rangeWhere(range, "created_at");
550
- const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${prompts.where}`).get(...prompts.params);
631
+ const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
632
+ const promptParams = [...prompts.params];
633
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
634
+ promptClauses.push("session_id = ?");
635
+ promptParams.push(filters.sessionID);
636
+ }
637
+ const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
638
+ const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
551
639
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
640
+ const other = otherUsage(db, range, filters);
552
641
  return {
553
642
  ...usage,
643
+ cost: usage.cost + other.cost,
554
644
  sessions: row?.sessions ?? 0,
555
645
  prompts: promptRow?.prompts ?? 0,
646
+ otherCost: other.cost,
556
647
  firstAt: row?.firstAt ?? undefined,
557
648
  lastAt: row?.lastAt ?? undefined,
558
649
  cacheHitRatio: cacheHitRatio(usage),
@@ -603,7 +694,7 @@ function addUsage(target, source) {
603
694
  target.listCost += source.listCost;
604
695
  }
605
696
  function billedTokens(usage) {
606
- return usage.input + usage.cached + usage.output;
697
+ return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning;
607
698
  }
608
699
  function percentile(values, p) {
609
700
  if (values.length === 0)
@@ -629,6 +720,17 @@ function sessions(db, options) {
629
720
  const limit = options?.limit ?? 20;
630
721
  const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
631
722
  const params = [...filter.params];
723
+ const promptRange = [];
724
+ const promptParams = [];
725
+ if (range?.from !== undefined) {
726
+ promptRange.push("p.created_at >= ?");
727
+ promptParams.push(range.from);
728
+ }
729
+ if (range?.to !== undefined) {
730
+ promptRange.push("p.created_at < ?");
731
+ promptParams.push(range.to);
732
+ }
733
+ const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(" AND ")}` : "";
632
734
  if (options?.sessionIDs !== undefined) {
633
735
  const ids = options.sessionIDs.slice(0, 500);
634
736
  clauses.push(`st.session_id IN (${ids.map(() => "?").join(", ")})`);
@@ -637,7 +739,7 @@ function sessions(db, options) {
637
739
  const rows = db.query(`SELECT st.session_id, s.title, s.directory, s.parent_id,
638
740
  GROUP_CONCAT(DISTINCT st.provider_id) AS providers,
639
741
  GROUP_CONCAT(DISTINCT st.model_id) AS models,
640
- (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id) AS prompts,
742
+ (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,
641
743
  COUNT(*) AS steps,
642
744
  COALESCE(SUM(st.input_tokens), 0) AS input,
643
745
  COALESCE(SUM(st.cache_read), 0) AS cached,
@@ -653,11 +755,14 @@ function sessions(db, options) {
653
755
  ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
654
756
  GROUP BY st.session_id
655
757
  ORDER BY last_at DESC
656
- LIMIT ?`).all(...params, limit);
758
+ LIMIT ?`).all(...promptParams, ...params, limit);
759
+ const other = otherUsageBySession(db, range, options?.filters);
657
760
  return rows.map((row) => {
658
761
  const usage = usageFrom(row);
762
+ const extra = other.get(row.session_id)?.cost ?? 0;
659
763
  return {
660
764
  ...usage,
765
+ cost: usage.cost + extra,
661
766
  sessionID: row.session_id,
662
767
  parentID: row.parent_id ?? undefined,
663
768
  title: row.title ?? undefined,
@@ -665,6 +770,7 @@ function sessions(db, options) {
665
770
  providers: row.providers ? row.providers.split(",").filter(Boolean) : [],
666
771
  models: row.models ? row.models.split(",").filter(Boolean) : [],
667
772
  prompts: row.prompts ?? 0,
773
+ otherCost: extra,
668
774
  firstAt: row.first_at ?? undefined,
669
775
  lastAt: row.last_at ?? undefined,
670
776
  cacheHitRatio: cacheHitRatio(usage)
@@ -708,118 +814,131 @@ function stepMessage(row) {
708
814
  };
709
815
  }
710
816
  function turns(db, options) {
711
- const limit = options?.limit ?? 50;
817
+ const requested = options?.limit ?? 50;
818
+ const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50;
712
819
  const filter = buildWhere(options?.range, options?.filters);
713
- const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
714
- const params = [...filter.params];
820
+ const baseClauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
821
+ const baseParams = [...filter.params];
715
822
  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)) {
749
- bucket = [];
750
- return;
823
+ baseClauses.push("session_id = ?");
824
+ baseParams.push(options.sessionID);
825
+ }
826
+ function read(promptCount) {
827
+ const clauses = [...baseClauses];
828
+ const params = [...baseParams];
829
+ const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount);
830
+ if (floor !== undefined) {
831
+ clauses.push(`${STEP_TIME} >= ?`);
832
+ params.push(floor);
751
833
  }
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) });
762
- }
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)
834
+ const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
835
+ input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
836
+ created_at, streamed_at, recorded_at, completed_at, finish
837
+ FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
838
+ ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
839
+ const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
840
+ const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
841
+ const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
842
+ const promptsBySession = new Map;
843
+ for (const row of promptRows) {
844
+ if (row.created_at === null)
772
845
  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;
846
+ const list = promptsBySession.get(row.session_id) ?? [];
847
+ list.push(row.created_at);
848
+ promptsBySession.set(row.session_id, list);
849
+ }
850
+ const result = [];
851
+ let sessionID;
852
+ let bucket = [];
853
+ let promptIndex = -2;
854
+ let promptAt;
855
+ function close() {
856
+ const last = bucket[bucket.length - 1];
857
+ if (last === undefined || !turnFinished(last.finish)) {
858
+ bucket = [];
859
+ return;
860
+ }
861
+ const totals = emptyUsage();
862
+ for (const row of bucket)
863
+ addUsage(totals, stepUsage(row));
864
+ const drops = [];
865
+ let reference;
866
+ for (const row of bucket) {
867
+ const message = stepMessage(row);
868
+ const drop = cacheDrop(reference, message);
869
+ if (drop !== undefined) {
870
+ drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
871
+ }
872
+ reference = message;
873
+ }
874
+ const providerID = last.provider_id ?? undefined;
875
+ const modelID = last.model_id ?? undefined;
876
+ const variant = last.variant ?? undefined;
877
+ let produced = 0;
878
+ let window = 0;
879
+ for (const row of bucket) {
880
+ if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
881
+ continue;
882
+ produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
883
+ window += row.streamed_at - row.created_at;
811
884
  }
885
+ const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
886
+ result.push({
887
+ sessionID: last.session_id,
888
+ promptAt,
889
+ endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
890
+ promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
891
+ providerID,
892
+ modelID,
893
+ variant,
894
+ providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
895
+ modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
896
+ steps: bucket.length,
897
+ latest: stepUsage(last),
898
+ totals,
899
+ drops,
900
+ finish: last.finish ?? undefined,
901
+ tps: tokensPerSecond(produced, 0, window)
902
+ });
903
+ bucket = [];
812
904
  }
813
- if (index !== promptIndex) {
814
- close();
815
- promptIndex = index;
816
- promptAt = index >= 0 ? prompts[index] : undefined;
817
- previousPromptAt = index >= 1 ? prompts[index - 1] : undefined;
905
+ for (const row of steps) {
906
+ if (row.session_id !== sessionID) {
907
+ close();
908
+ sessionID = row.session_id;
909
+ promptIndex = -2;
910
+ promptAt = undefined;
911
+ }
912
+ const time = row.created_at ?? row.recorded_at;
913
+ const prompts = promptsBySession.get(row.session_id) ?? [];
914
+ let index = -1;
915
+ for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
916
+ if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
917
+ index = candidate;
918
+ break;
919
+ }
920
+ }
921
+ if (index !== promptIndex) {
922
+ close();
923
+ promptIndex = index;
924
+ promptAt = index >= 0 ? prompts[index] : undefined;
925
+ }
926
+ bucket.push(row);
818
927
  }
819
- bucket.push(row);
928
+ close();
929
+ const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
930
+ return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
931
+ }
932
+ let promptCount = Math.max(1, limit + 1);
933
+ for (;; ) {
934
+ const { rows, complete } = read(promptCount);
935
+ if (rows.length >= limit || complete)
936
+ return rows.slice(0, limit);
937
+ const next = promptCount * 2 + 1;
938
+ if (!Number.isFinite(next) || next <= promptCount)
939
+ return rows.slice(0, limit);
940
+ promptCount = next;
820
941
  }
821
- close();
822
- return result.reverse().slice(0, limit);
823
942
  }
824
943
  function promptFloor(db, sessionID, count) {
825
944
  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);
@@ -892,38 +1011,44 @@ function sanitizeSettings(raw) {
892
1011
  };
893
1012
  }
894
1013
  function formatPercent(value, digits = 1) {
895
- return value === undefined ? "\u2013" : `${(value * 100).toFixed(digits)}%`;
1014
+ if (value === undefined || !Number.isFinite(value))
1015
+ return "\u2013";
1016
+ return `${(value * 100).toFixed(digits)}%`;
896
1017
  }
897
1018
  function formatCount(value) {
898
- return Math.round(value).toLocaleString("en-US");
1019
+ return Number.isFinite(value) ? Math.round(value).toLocaleString("en-US") : "\u2013";
899
1020
  }
900
1021
  function formatMs(value) {
901
- if (value === undefined)
1022
+ if (value === undefined || !Number.isFinite(value))
902
1023
  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);
1024
+ const ms = Math.max(0, value);
1025
+ if (ms < 1000)
1026
+ return `${Math.round(ms)}ms`;
1027
+ if (ms < 60000)
1028
+ return `${(ms / 1000).toFixed(1)}s`;
1029
+ return formatDuration(ms);
908
1030
  }
909
1031
  function formatTps(value) {
910
- return value === undefined ? "\u2013" : `${value.toFixed(1)}/s`;
1032
+ if (value === undefined || !Number.isFinite(value) || value < 0)
1033
+ return "\u2013";
1034
+ return `${value.toFixed(1)}/s`;
911
1035
  }
912
1036
  function formatTpsCompact(value) {
913
- if (value === undefined)
1037
+ if (value === undefined || !Number.isFinite(value) || value < 0)
914
1038
  return "\u2013";
915
1039
  return value >= 10 ? `${Math.round(value)}/s` : `${value.toFixed(1)}/s`;
916
1040
  }
917
1041
  function formatGap(value) {
918
- if (value === undefined)
1042
+ if (value === undefined || !Number.isFinite(value))
919
1043
  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`;
1044
+ const gap = Math.max(0, value);
1045
+ if (gap < 60000)
1046
+ return `${Math.round(gap / 1000)}s`;
1047
+ if (gap < 3600000)
1048
+ return `${Math.round(gap / 60000)}m`;
1049
+ if (gap < 86400000)
1050
+ return `${(gap / 3600000).toFixed(1)}h`;
1051
+ return `${(gap / 86400000).toFixed(1)}d`;
927
1052
  }
928
1053
  function truncate(value, width) {
929
1054
  if (width <= 1)
@@ -1086,6 +1211,8 @@ function helpLines(width) {
1086
1211
  { text: " out everything generated: visible output + reasoning" },
1087
1212
  { text: " reasoning part of `out`" },
1088
1213
  { text: " cost money, not tokens: a turn sums every step; $0 is left out" },
1214
+ { text: " other compaction/title usage: money with no assistant step;" },
1215
+ { text: " overview, periods and sessions include it; model rows do not" },
1089
1216
  { text: " \u2248 list-price estimate for steps the host reported as $0;" },
1090
1217
  { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
1091
1218
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
@@ -1124,6 +1251,9 @@ function usagePairs(usage, estimates = true) {
1124
1251
  if (buckets.reasoning > 0)
1125
1252
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
1126
1253
  pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
1254
+ const other = usage.otherCost ?? 0;
1255
+ if (other > 0)
1256
+ pairs.push(["other", `${formatCost(other)} comp/title`]);
1127
1257
  if ("tps" in usage && usage.tps !== undefined)
1128
1258
  pairs.push(["tps", formatTps(usage.tps)]);
1129
1259
  return pairs;
@@ -1413,7 +1543,7 @@ function cacheLines(data, width) {
1413
1543
  }
1414
1544
  return lines;
1415
1545
  }
1416
- function periodLines(rows, width, granularity, limit = 40, estimates = true) {
1546
+ function periodLines(rows, width, granularity, limit = 40, estimates = true, totalSessions) {
1417
1547
  const lines = [];
1418
1548
  const totals = rows.reduce((sum, row) => {
1419
1549
  sum.steps += row.usage.steps;
@@ -1465,7 +1595,7 @@ function periodLines(rows, width, granularity, limit = 40, estimates = true) {
1465
1595
  text: formatTableRow([
1466
1596
  "total",
1467
1597
  formatCount(totals.steps),
1468
- ...withSessions ? [formatCount(totals.sessions)] : [],
1598
+ ...withSessions ? [formatCount(totalSessions ?? totals.sessions)] : [],
1469
1599
  formatTokens(overall.prompt),
1470
1600
  formatTokens(overall.cached),
1471
1601
  formatPercent(overall.hit, 0),
@@ -1555,7 +1685,11 @@ function sessionsLines(rows, width, options) {
1555
1685
  tone: child ? "muted" : "base",
1556
1686
  row: { kind: "session", value: row.sessionID }
1557
1687
  });
1558
- const details = [row.directory ?? "", row.models.length > 1 ? count(row.models.length, "model") : ""].filter((part) => part !== "").join(" \xB7 ");
1688
+ const details = [
1689
+ row.directory ?? "",
1690
+ row.models.length > 1 ? count(row.models.length, "model") : "",
1691
+ (row.otherCost ?? 0) > 0 ? `other ${formatCost(row.otherCost)}` : ""
1692
+ ].filter((part) => part !== "").join(" \xB7 ");
1559
1693
  lines.push({ text: truncate(`${" ".repeat(child ? 2 : 0)} ${details}`, width), tone: "muted" });
1560
1694
  }
1561
1695
  if (options?.rollup !== undefined && options.rollup.subagentSteps > 0) {
@@ -1591,7 +1725,7 @@ function dbLines(data, width) {
1591
1725
  });
1592
1726
  lines.push({ text: "", tone: "muted" });
1593
1727
  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" });
1728
+ lines.push({ text: truncate(" \u2191\u2193 pick a retention \xB7 enter prunes the steps and their other usage (asks first) \xB7 v gives the space back", width), tone: "muted" });
1595
1729
  if (data.estimates !== false) {
1596
1730
  lines.push({
1597
1731
  text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price \xB7 e retries`, width),
@@ -1872,7 +2006,7 @@ function groupedRows(db, options) {
1872
2006
  return normalize(rows, STEP_OPTIONAL);
1873
2007
  }
1874
2008
  function timingOf(step) {
1875
- const wall = step.createdAt !== undefined && step.completedAt !== undefined ? step.completedAt - step.createdAt : undefined;
2009
+ const wall = step.createdAt !== undefined && step.completedAt !== undefined ? Math.max(0, step.completedAt - step.createdAt) : undefined;
1876
2010
  const stream = step.createdAt !== undefined && step.streamedAt !== undefined && step.streamedAt > step.createdAt ? step.streamedAt - step.createdAt : undefined;
1877
2011
  return { wall, stream, tps: tokensPerSecond(step.output + step.reasoning, step.createdAt, step.streamedAt) };
1878
2012
  }
@@ -2139,7 +2273,14 @@ function groupValues(steps) {
2139
2273
  }
2140
2274
  function providerOf(steps, models) {
2141
2275
  const values = groupValues(steps);
2142
- const times = steps.map((step) => step.at);
2276
+ let firstAt;
2277
+ let lastAt;
2278
+ for (const step of steps) {
2279
+ if (firstAt === undefined || step.at < firstAt)
2280
+ firstAt = step.at;
2281
+ if (lastAt === undefined || step.at > lastAt)
2282
+ lastAt = step.at;
2283
+ }
2143
2284
  return {
2144
2285
  provider: steps[0].providerID,
2145
2286
  models: models.split("\x00"),
@@ -2148,8 +2289,8 @@ function providerOf(steps, models) {
2148
2289
  cache: values.cache,
2149
2290
  tps: values.tps,
2150
2291
  wall: values.wall,
2151
- firstAt: times.length > 0 ? Math.min(...times) : undefined,
2152
- lastAt: times.length > 0 ? Math.max(...times) : undefined
2292
+ firstAt,
2293
+ lastAt
2153
2294
  };
2154
2295
  }
2155
2296
  var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => modelLabel(key.slice(0, key.indexOf("#")), key.slice(key.indexOf("#") + 1) || undefined)).join("\x00");
@@ -2185,6 +2326,14 @@ function isoWeek(date) {
2185
2326
  const week = 1 + Math.round((thursday.getTime() - firstThursday.getTime()) / (7 * 24 * 60 * 60 * 1000));
2186
2327
  return { year: thursday.getFullYear(), week, monday };
2187
2328
  }
2329
+ function periodEnd(at, granularity) {
2330
+ const date = new Date(at);
2331
+ if (granularity === "month")
2332
+ return new Date(date.getFullYear(), date.getMonth() + 1, 1).getTime();
2333
+ if (granularity === "week")
2334
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7).getTime();
2335
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
2336
+ }
2188
2337
  function periodStart(at, granularity) {
2189
2338
  const date = new Date(at);
2190
2339
  const pad = (value) => String(value).padStart(2, "0");
@@ -2200,11 +2349,11 @@ function periodStart(at, granularity) {
2200
2349
  const key = `${start.getFullYear()}-${pad(start.getMonth() + 1)}-${pad(start.getDate())}`;
2201
2350
  return { key, label: key, start: start.getTime() };
2202
2351
  }
2203
- function periodsOf(rows, granularity) {
2204
- const out = [];
2352
+ function periodsOf(rows, granularity, otherRows = []) {
2353
+ const byKey = new Map;
2205
2354
  for (const [key, steps] of groupBy(rows, (step) => periodStart(step.at, granularity).key)) {
2206
2355
  const period = periodStart(steps[0].at, granularity);
2207
- out.push({
2356
+ byKey.set(key, {
2208
2357
  key,
2209
2358
  label: period.label,
2210
2359
  at: period.start,
@@ -2214,7 +2363,27 @@ function periodsOf(rows, granularity) {
2214
2363
  cache: cacheStatsOfSteps(steps)
2215
2364
  });
2216
2365
  }
2217
- return out.sort((left, right) => left.at - right.at);
2366
+ for (const [key, group] of groupBy(otherRows, (row) => periodStart(row.at, granularity).key)) {
2367
+ const cost = group.reduce((sum, row) => sum + row.cost, 0);
2368
+ const existing = byKey.get(key);
2369
+ if (existing !== undefined) {
2370
+ existing.usage.cost += cost;
2371
+ existing.otherCost = (existing.otherCost ?? 0) + cost;
2372
+ continue;
2373
+ }
2374
+ const period = periodStart(group[0].at, granularity);
2375
+ byKey.set(key, {
2376
+ key,
2377
+ label: period.label,
2378
+ at: period.start,
2379
+ steps: 0,
2380
+ sessions: new Set(group.map((row) => row.sessionID)).size,
2381
+ usage: { ...usageOf([]), cost },
2382
+ cache: cacheStatsOfSteps([]),
2383
+ otherCost: cost
2384
+ });
2385
+ }
2386
+ return [...byKey.values()].sort((left, right) => left.at - right.at);
2218
2387
  }
2219
2388
 
2220
2389
  // src/panel-build.ts
@@ -2282,7 +2451,7 @@ function build(request) {
2282
2451
  session: sessionUsage,
2283
2452
  ...children.length > 0 ? { subagents: children } : {},
2284
2453
  range: request.range,
2285
- activity: activityOf(db, range, now),
2454
+ activity: activityOf(db, range, filters, now),
2286
2455
  coverage: coverageOf(db, { range, filters }),
2287
2456
  estimates
2288
2457
  }, width);
@@ -2307,8 +2476,11 @@ function build(request) {
2307
2476
  models: topCacheModels(pairs)
2308
2477
  }, width);
2309
2478
  }
2310
- case "periods":
2311
- return periodLines(periodsOf(stepRows(db, { range, filters }), request.granularity), width, request.granularity, 40, estimates);
2479
+ case "periods": {
2480
+ const rows = periodsOf(stepRows(db, { range, filters }), request.granularity, otherUsageRows(db, range, filters));
2481
+ const sessions = overview(db, range, filters).sessions;
2482
+ return periodLines(rows, width, request.granularity, 40, estimates, sessions);
2483
+ }
2312
2484
  case "latency": {
2313
2485
  const timings = timingRows(db, { range, filters });
2314
2486
  const by = filters.modelID !== undefined ? "provider" : "model";
@@ -2401,11 +2573,14 @@ function buildDetail(request, range, filters, estimates) {
2401
2573
  if (row.kind === "period") {
2402
2574
  const periods = periodsOf(stepRows(db, { range, filters }), request.granularity);
2403
2575
  const period = periods.find((entry) => entry.key === row.value);
2576
+ const from = period === undefined ? 0 : Math.max(period.at, range?.from ?? period.at);
2577
+ const to = period === undefined ? 0 : Math.min(periodEnd(period.at, request.granularity), range?.to ?? Number.POSITIVE_INFINITY);
2578
+ const steps = period === undefined ? [] : stepRows(db, { range: { from, to }, filters });
2404
2579
  return [
2405
2580
  head,
2406
2581
  { text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
2407
2582
  { text: "", tone: "muted" },
2408
- ...providerSummaryLines(providerSummaryOf(stepRows(db, { range, filters })), width, 40, estimates),
2583
+ ...providerSummaryLines(providerSummaryOf(steps), width, 40, estimates),
2409
2584
  { text: "", tone: "muted" },
2410
2585
  back
2411
2586
  ];
@@ -2416,12 +2591,16 @@ function percent(value) {
2416
2591
  return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
2417
2592
  }
2418
2593
  function sortModels(rows, sort, desc, estimates = true) {
2419
- const sign = desc ? -1 : 1;
2594
+ const sign = desc ? 1 : -1;
2420
2595
  const pick = (model) => {
2421
2596
  if (sort === "cached")
2422
2597
  return model.totals.cached;
2598
+ if (sort === "hit") {
2599
+ const prompt = model.totals.input + model.totals.cached + model.totals.cacheWrite;
2600
+ return prompt > 0 ? model.totals.cached / prompt : -1;
2601
+ }
2423
2602
  if (sort === "out")
2424
- return model.totals.output;
2603
+ return model.totals.output + model.totals.reasoning;
2425
2604
  if (sort === "cost")
2426
2605
  return estimates ? spend(model.totals) : model.totals.cost;
2427
2606
  return model.totals.steps;
@@ -2429,7 +2608,7 @@ function sortModels(rows, sort, desc, estimates = true) {
2429
2608
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2430
2609
  }
2431
2610
  function sortProviders(rows, sort, desc, estimates = true) {
2432
- const sign = desc ? -1 : 1;
2611
+ const sign = desc ? 1 : -1;
2433
2612
  const pick = (row) => {
2434
2613
  if (sort === "cached")
2435
2614
  return row.cache.cached;
@@ -2446,7 +2625,7 @@ function sortProviders(rows, sort, desc, estimates = true) {
2446
2625
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2447
2626
  }
2448
2627
  function sortLatency(rows, sort, desc) {
2449
- const sign = desc ? -1 : 1;
2628
+ const sign = desc ? 1 : -1;
2450
2629
  const pick = (row) => {
2451
2630
  if (sort === "tps")
2452
2631
  return row.tps.p50 ?? -1;
@@ -2457,7 +2636,7 @@ function sortLatency(rows, sort, desc) {
2457
2636
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2458
2637
  }
2459
2638
  function sortSessions(rows, sort, desc, estimates = true) {
2460
- const sign = desc ? -1 : 1;
2639
+ const sign = desc ? 1 : -1;
2461
2640
  const pick = (row) => {
2462
2641
  if (sort === "steps")
2463
2642
  return row.steps;
@@ -2470,12 +2649,12 @@ function sortSessions(rows, sort, desc, estimates = true) {
2470
2649
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2471
2650
  }
2472
2651
  function sortTurns(rows, sort, desc, estimates = true) {
2473
- const sign = desc ? -1 : 1;
2652
+ const sign = desc ? 1 : -1;
2474
2653
  const pick = (row) => {
2475
2654
  if (sort === "cost")
2476
2655
  return estimates ? spend(row.totals) : row.totals.cost;
2477
2656
  if (sort === "tokens")
2478
- return row.totals.cached + row.totals.input + row.totals.output;
2657
+ return row.totals.cached + row.totals.input + row.totals.cacheWrite + row.totals.output + row.totals.reasoning;
2479
2658
  return row.endAt ?? 0;
2480
2659
  };
2481
2660
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
@@ -2493,17 +2672,17 @@ function switchesByModel(rows) {
2493
2672
  function topCacheModels(pairs) {
2494
2673
  return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
2495
2674
  }
2496
- function activityOf(db, range, now) {
2497
- const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps`).get();
2675
+ function activityOf(db, range, filters, now) {
2676
+ const filter = buildWhere(range, filters, STEP_TIME);
2677
+ const earliest = db.query(`SELECT MIN(${STEP_TIME}) AS at FROM steps ${filter.where}`).get(...filter.params);
2498
2678
  const from = range?.from ?? earliest?.at ?? 0;
2499
2679
  const to = range?.to ?? now;
2500
2680
  const span = Math.max(1, to - from);
2501
2681
  const ladder = [3600000, 3 * 3600000, 6 * 3600000, 12 * 3600000, 86400000, 3 * 86400000, 7 * 86400000, 30 * 86400000];
2502
2682
  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);
2683
+ const rows = db.query(`SELECT CAST(${STEP_TIME} / ? AS INTEGER) AS bucket, COUNT(*) AS steps
2684
+ FROM steps ${filter.where}
2685
+ GROUP BY bucket ORDER BY bucket`).all(bucket, ...filter.params);
2507
2686
  if (rows.length === 0)
2508
2687
  return [];
2509
2688
  const first = Math.floor(from / bucket);
@@ -2564,7 +2743,7 @@ function ensureRegularFile(path) {
2564
2743
  }
2565
2744
 
2566
2745
  // src/stats/db.ts
2567
- var SCHEMA_VERSION = 10;
2746
+ var SCHEMA_VERSION = 11;
2568
2747
  var LABEL_LIMIT = 4 * TEXT_LIMIT;
2569
2748
  var SCHEMA = `
2570
2749
  CREATE TABLE IF NOT EXISTS meta (
@@ -2629,8 +2808,28 @@ CREATE TABLE IF NOT EXISTS events (
2629
2808
  );
2630
2809
  CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
2631
2810
  CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
2811
+
2812
+ -- Usage the host reports with no assistant step of its own: the compaction
2813
+ -- summarisation and the session-title generation. The host publishes it as
2814
+ -- session.usage.recorded with a source other than generate, and includes it in
2815
+ -- the session's own cost/token totals. Primary key is the host event ID, so a
2816
+ -- replayed event never counts twice.
2817
+ CREATE TABLE IF NOT EXISTS usage (
2818
+ id TEXT PRIMARY KEY,
2819
+ session_id TEXT NOT NULL,
2820
+ source TEXT NOT NULL,
2821
+ at INTEGER,
2822
+ cost REAL NOT NULL DEFAULT 0,
2823
+ input_tokens INTEGER NOT NULL DEFAULT 0,
2824
+ output_tokens INTEGER NOT NULL DEFAULT 0,
2825
+ reasoning_tokens INTEGER NOT NULL DEFAULT 0,
2826
+ cache_read INTEGER NOT NULL DEFAULT 0,
2827
+ cache_write INTEGER NOT NULL DEFAULT 0
2828
+ );
2829
+ CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
2830
+ CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
2632
2831
  `;
2633
- var TABLES = ["sessions", "prompts", "events", "steps"];
2832
+ var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
2634
2833
  function jsonText(value) {
2635
2834
  if (value === undefined || value === null)
2636
2835
  return null;
@@ -2642,6 +2841,15 @@ function jsonText(value) {
2642
2841
  return null;
2643
2842
  }
2644
2843
  }
2844
+ function finite(value) {
2845
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
2846
+ }
2847
+ function tokenCount(value) {
2848
+ return Math.max(0, Math.floor(finite(value)));
2849
+ }
2850
+ function timestamp(value) {
2851
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2852
+ }
2645
2853
  var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
2646
2854
  var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
2647
2855
  function dropUnused(db) {
@@ -2670,9 +2878,56 @@ function addMissing(db) {
2670
2878
  db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
2671
2879
  }
2672
2880
  }
2881
+ function dedupeEvents(db) {
2882
+ const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
2883
+ if (table === null)
2884
+ return;
2885
+ db.exec(`DELETE FROM events
2886
+ WHERE kind = 'compaction' AND message_id IS NULL
2887
+ AND rowid NOT IN (
2888
+ SELECT MIN(rowid) FROM events
2889
+ WHERE kind = 'compaction' AND message_id IS NULL
2890
+ GROUP BY session_id, at, data
2891
+ )`);
2892
+ db.exec(`DELETE FROM events
2893
+ WHERE message_id IS NOT NULL
2894
+ AND rowid NOT IN (
2895
+ SELECT MIN(rowid) FROM events
2896
+ WHERE message_id IS NOT NULL
2897
+ GROUP BY kind, message_id
2898
+ )`);
2899
+ }
2900
+ function addEventKey(db) {
2901
+ const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
2902
+ if (table === null)
2903
+ return;
2904
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
2905
+ }
2906
+ function backfillCompactionUsage(db) {
2907
+ const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
2908
+ if (!tables.has("events") || !tables.has("usage"))
2909
+ return;
2910
+ db.exec(`INSERT OR IGNORE INTO usage (
2911
+ id, session_id, source, at, cost,
2912
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
2913
+ )
2914
+ SELECT 'compaction:' || rowid, session_id, 'compaction', at,
2915
+ MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
2916
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
2917
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
2918
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
2919
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
2920
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
2921
+ FROM events
2922
+ WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
2923
+ AND json_valid(data)`);
2924
+ }
2673
2925
  function migrate(db) {
2674
2926
  dropUnused(db);
2675
2927
  addMissing(db);
2928
+ dedupeEvents(db);
2929
+ backfillCompactionUsage(db);
2930
+ addEventKey(db);
2676
2931
  }
2677
2932
  var POSIX = process.platform !== "win32";
2678
2933
  function hardenDirectory(path) {
@@ -2733,6 +2988,8 @@ function openStatsDbWrite(path) {
2733
2988
  return db;
2734
2989
  }
2735
2990
  function recordStep(db, record) {
2991
+ const cost = Math.max(0, finite(record.cost));
2992
+ const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
2736
2993
  db.query(`INSERT INTO steps (
2737
2994
  message_id, session_id, parent_id, provider_id, model_id, variant,
2738
2995
  input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
@@ -2768,18 +3025,40 @@ function recordStep(db, record) {
2768
3025
  $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
2769
3026
  $modelID: record.modelID ?? null,
2770
3027
  $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,
3028
+ $input: tokenCount(record.input),
3029
+ $output: tokenCount(record.output),
3030
+ $reasoning: tokenCount(record.reasoning),
3031
+ $cacheRead: tokenCount(record.cacheRead),
3032
+ $cacheWrite: tokenCount(record.cacheWrite),
3033
+ $cost: cost,
3034
+ $listCost: listCost,
3035
+ $createdAt: timestamp(record.createdAt),
3036
+ $streamedAt: timestamp(record.streamedAt),
3037
+ $completedAt: timestamp(record.completedAt),
2781
3038
  $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
2782
- $recordedAt: record.recordedAt ?? Date.now()
3039
+ $recordedAt: timestamp(record.recordedAt) ?? Date.now()
3040
+ });
3041
+ }
3042
+ function recordUsage(db, record) {
3043
+ if (typeof record.id !== "string" || record.id === "")
3044
+ return;
3045
+ if (typeof record.sessionID !== "string" || record.sessionID === "")
3046
+ return;
3047
+ db.query(`INSERT INTO usage (
3048
+ id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
3049
+ ) VALUES (
3050
+ $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
3051
+ ) ON CONFLICT(id) DO NOTHING`).run({
3052
+ $id: record.id,
3053
+ $sessionID: record.sessionID,
3054
+ $source: sanitizeLabel(record.source, 64),
3055
+ $at: timestamp(record.at) ?? Date.now(),
3056
+ $cost: Math.max(0, finite(record.cost)),
3057
+ $input: tokenCount(record.input),
3058
+ $output: tokenCount(record.output),
3059
+ $reasoning: tokenCount(record.reasoning),
3060
+ $cacheRead: tokenCount(record.cacheRead),
3061
+ $cacheWrite: tokenCount(record.cacheWrite)
2783
3062
  });
2784
3063
  }
2785
3064
  function recordPrompt(db, record) {
@@ -2788,16 +3067,16 @@ function recordPrompt(db, record) {
2788
3067
  ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
2789
3068
  $sessionID: record.sessionID,
2790
3069
  $messageID: record.messageID,
2791
- $createdAt: record.createdAt ?? null
3070
+ $createdAt: timestamp(record.createdAt)
2792
3071
  });
2793
3072
  }
2794
3073
  function recordEvent(db, record) {
2795
- db.query(`INSERT INTO events (session_id, kind, message_id, at, data)
3074
+ db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
2796
3075
  VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
2797
3076
  $sessionID: record.sessionID,
2798
3077
  $kind: sanitizeLabel(record.kind, 64),
2799
3078
  $messageID: record.messageID ?? null,
2800
- $at: record.at ?? Date.now(),
3079
+ $at: timestamp(record.at) ?? Date.now(),
2801
3080
  $data: jsonText(record.data)
2802
3081
  });
2803
3082
  }
@@ -2814,8 +3093,8 @@ function upsertSession(db, record) {
2814
3093
  $parentID: record.parentID ?? null,
2815
3094
  $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
2816
3095
  $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
2817
- $startedAt: record.startedAt ?? null,
2818
- $updatedAt: record.updatedAt ?? null
3096
+ $startedAt: timestamp(record.startedAt),
3097
+ $updatedAt: timestamp(record.updatedAt)
2819
3098
  });
2820
3099
  }
2821
3100
 
@@ -2829,10 +3108,17 @@ function size(path) {
2829
3108
  return 0;
2830
3109
  }
2831
3110
  }
3111
+ function hasTable(db, name) {
3112
+ try {
3113
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name) !== null;
3114
+ } catch {
3115
+ return false;
3116
+ }
3117
+ }
2832
3118
  function dbInfo(db, path, now = Date.now()) {
2833
3119
  const tables = TABLES.map((table) => ({
2834
3120
  name: table,
2835
- rows: db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n
3121
+ rows: hasTable(db, table) ? db.query(`SELECT COUNT(*) AS n FROM ${table}`).get().n : 0
2836
3122
  }));
2837
3123
  const window = db.query(`SELECT MIN(${STEP_TIME2}) AS first, MAX(${STEP_TIME2}) AS last FROM steps`).get();
2838
3124
  const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
@@ -2871,7 +3157,8 @@ function pruneOlderThan(db, cutoff) {
2871
3157
  return {
2872
3158
  steps: deleteBatched(db, "steps", `${STEP_TIME2} < ?`, cutoff),
2873
3159
  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)
3160
+ events: deleteBatched(db, "events", "at IS NOT NULL AND at < ?", cutoff),
3161
+ usage: hasTable(db, "usage") ? deleteBatched(db, "usage", "at IS NOT NULL AND at < ?", cutoff) : 0
2875
3162
  };
2876
3163
  }
2877
3164
  function footprint(path) {
@@ -3119,7 +3406,7 @@ function Panel(props) {
3119
3406
  });
3120
3407
  } else {
3121
3408
  props.ctx.ui.toast.show({
3122
- message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions`,
3409
+ message: `pruned ${result.steps} steps \xB7 ${result.prompts} prompts \xB7 ${result.events} compactions \xB7 ${result.usage} other usage`,
3123
3410
  variant: "success"
3124
3411
  });
3125
3412
  }
@@ -3431,8 +3718,13 @@ function priceTable(models) {
3431
3718
  for (const cost of model.cost) {
3432
3719
  if (cost === null || cost === undefined)
3433
3720
  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;
3721
+ let tier;
3722
+ if (cost.tier !== undefined) {
3723
+ const size = cost.tier.size;
3724
+ if (typeof size !== "number" || !Number.isFinite(size))
3725
+ continue;
3726
+ tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
3727
+ }
3436
3728
  tiers.push({
3437
3729
  ...tier !== undefined ? { tier } : {},
3438
3730
  input: money(cost.input),
@@ -3767,7 +4059,7 @@ var tui_default = Plugin.define({
3767
4059
  return {
3768
4060
  db,
3769
4061
  refresh,
3770
- limit: Math.max(1, Math.round(options.sidebarTurns ?? 5))
4062
+ limit: Math.max(1, Math.round(options.sidebarTurns ?? 8))
3771
4063
  };
3772
4064
  },
3773
4065
  get options() {
@@ -3866,4 +4158,4 @@ export {
3866
4158
  tui_default as default
3867
4159
  };
3868
4160
 
3869
- //# debugId=EAEFC12B046D781964756E2164756E21
4161
+ //# debugId=A1CD43DA40AD35A864756E2164756E21