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/index.js CHANGED
@@ -28,8 +28,13 @@ function priceTable(models) {
28
28
  for (const cost of model.cost) {
29
29
  if (cost === null || cost === undefined)
30
30
  continue;
31
- const size = cost.tier?.size;
32
- const tier = cost.tier !== undefined && typeof size === "number" && Number.isFinite(size) && size >= 0 ? { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size } : undefined;
31
+ let tier;
32
+ if (cost.tier !== undefined) {
33
+ const size = cost.tier.size;
34
+ if (typeof size !== "number" || !Number.isFinite(size))
35
+ continue;
36
+ tier = { ...cost.tier.type !== undefined ? { type: cost.tier.type } : {}, size };
37
+ }
33
38
  tiers.push({
34
39
  ...tier !== undefined ? { tier } : {},
35
40
  input: money(cost.input),
@@ -141,7 +146,7 @@ function isToken(value, limit = 64) {
141
146
  }
142
147
 
143
148
  // src/stats/db.ts
144
- var SCHEMA_VERSION = 10;
149
+ var SCHEMA_VERSION = 11;
145
150
  var LABEL_LIMIT = 4 * TEXT_LIMIT;
146
151
  var SCHEMA = `
147
152
  CREATE TABLE IF NOT EXISTS meta (
@@ -206,8 +211,28 @@ CREATE TABLE IF NOT EXISTS events (
206
211
  );
207
212
  CREATE INDEX IF NOT EXISTS events_session ON events(session_id, at);
208
213
  CREATE INDEX IF NOT EXISTS events_kind ON events(kind, at);
214
+
215
+ -- Usage the host reports with no assistant step of its own: the compaction
216
+ -- summarisation and the session-title generation. The host publishes it as
217
+ -- session.usage.recorded with a source other than generate, and includes it in
218
+ -- the session's own cost/token totals. Primary key is the host event ID, so a
219
+ -- replayed event never counts twice.
220
+ CREATE TABLE IF NOT EXISTS usage (
221
+ id TEXT PRIMARY KEY,
222
+ session_id TEXT NOT NULL,
223
+ source TEXT NOT NULL,
224
+ at INTEGER,
225
+ cost REAL NOT NULL DEFAULT 0,
226
+ input_tokens INTEGER NOT NULL DEFAULT 0,
227
+ output_tokens INTEGER NOT NULL DEFAULT 0,
228
+ reasoning_tokens INTEGER NOT NULL DEFAULT 0,
229
+ cache_read INTEGER NOT NULL DEFAULT 0,
230
+ cache_write INTEGER NOT NULL DEFAULT 0
231
+ );
232
+ CREATE INDEX IF NOT EXISTS usage_session_at ON usage(session_id, at);
233
+ CREATE INDEX IF NOT EXISTS usage_at ON usage(at);
209
234
  `;
210
- var TABLES = ["sessions", "prompts", "events", "steps"];
235
+ var TABLES = ["sessions", "prompts", "events", "steps", "usage"];
211
236
  function jsonText(value) {
212
237
  if (value === undefined || value === null)
213
238
  return null;
@@ -219,6 +244,15 @@ function jsonText(value) {
219
244
  return null;
220
245
  }
221
246
  }
247
+ function finite(value) {
248
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
249
+ }
250
+ function tokenCount(value) {
251
+ return Math.max(0, Math.floor(finite(value)));
252
+ }
253
+ function timestamp(value) {
254
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
255
+ }
222
256
  var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
223
257
  var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
224
258
  function dropUnused(db) {
@@ -247,9 +281,56 @@ function addMissing(db) {
247
281
  db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
248
282
  }
249
283
  }
284
+ function dedupeEvents(db) {
285
+ const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
286
+ if (table === null)
287
+ return;
288
+ db.exec(`DELETE FROM events
289
+ WHERE kind = 'compaction' AND message_id IS NULL
290
+ AND rowid NOT IN (
291
+ SELECT MIN(rowid) FROM events
292
+ WHERE kind = 'compaction' AND message_id IS NULL
293
+ GROUP BY session_id, at, data
294
+ )`);
295
+ db.exec(`DELETE FROM events
296
+ WHERE message_id IS NOT NULL
297
+ AND rowid NOT IN (
298
+ SELECT MIN(rowid) FROM events
299
+ WHERE message_id IS NOT NULL
300
+ GROUP BY kind, message_id
301
+ )`);
302
+ }
303
+ function addEventKey(db) {
304
+ const table = db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get();
305
+ if (table === null)
306
+ return;
307
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS events_kind_message ON events(kind, message_id) WHERE message_id IS NOT NULL");
308
+ }
309
+ function backfillCompactionUsage(db) {
310
+ const tables = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
311
+ if (!tables.has("events") || !tables.has("usage"))
312
+ return;
313
+ db.exec(`INSERT OR IGNORE INTO usage (
314
+ id, session_id, source, at, cost,
315
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
316
+ )
317
+ SELECT 'compaction:' || rowid, session_id, 'compaction', at,
318
+ MAX(0, COALESCE(CAST(json_extract(data, '$.cost') AS REAL), 0)),
319
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.input'), 0) AS INTEGER)),
320
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.output'), 0) AS INTEGER)),
321
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS INTEGER)),
322
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS INTEGER)),
323
+ MAX(0, CAST(COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS INTEGER))
324
+ FROM events
325
+ WHERE kind = 'compaction' AND message_id IS NULL AND at IS NOT NULL AND data IS NOT NULL
326
+ AND json_valid(data)`);
327
+ }
250
328
  function migrate(db) {
251
329
  dropUnused(db);
252
330
  addMissing(db);
331
+ dedupeEvents(db);
332
+ backfillCompactionUsage(db);
333
+ addEventKey(db);
253
334
  }
254
335
  var POSIX = process.platform !== "win32";
255
336
  function hardenDirectory(path) {
@@ -310,6 +391,8 @@ function openStatsDbWrite(path) {
310
391
  return db;
311
392
  }
312
393
  function recordStep(db, record) {
394
+ const cost = Math.max(0, finite(record.cost));
395
+ const listCost = cost <= 0 && typeof record.listCost === "number" && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null;
313
396
  db.query(`INSERT INTO steps (
314
397
  message_id, session_id, parent_id, provider_id, model_id, variant,
315
398
  input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
@@ -345,18 +428,40 @@ function recordStep(db, record) {
345
428
  $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
346
429
  $modelID: record.modelID ?? null,
347
430
  $variant: record.variant ?? null,
348
- $input: record.input ?? 0,
349
- $output: record.output ?? 0,
350
- $reasoning: record.reasoning ?? 0,
351
- $cacheRead: record.cacheRead ?? 0,
352
- $cacheWrite: record.cacheWrite ?? 0,
353
- $cost: record.cost ?? 0,
354
- $listCost: (record.cost ?? 0) <= 0 && record.listCost !== undefined && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null,
355
- $createdAt: record.createdAt ?? null,
356
- $streamedAt: record.streamedAt ?? null,
357
- $completedAt: record.completedAt ?? null,
431
+ $input: tokenCount(record.input),
432
+ $output: tokenCount(record.output),
433
+ $reasoning: tokenCount(record.reasoning),
434
+ $cacheRead: tokenCount(record.cacheRead),
435
+ $cacheWrite: tokenCount(record.cacheWrite),
436
+ $cost: cost,
437
+ $listCost: listCost,
438
+ $createdAt: timestamp(record.createdAt),
439
+ $streamedAt: timestamp(record.streamedAt),
440
+ $completedAt: timestamp(record.completedAt),
358
441
  $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
359
- $recordedAt: record.recordedAt ?? Date.now()
442
+ $recordedAt: timestamp(record.recordedAt) ?? Date.now()
443
+ });
444
+ }
445
+ function recordUsage(db, record) {
446
+ if (typeof record.id !== "string" || record.id === "")
447
+ return;
448
+ if (typeof record.sessionID !== "string" || record.sessionID === "")
449
+ return;
450
+ db.query(`INSERT INTO usage (
451
+ id, session_id, source, at, cost, input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
452
+ ) VALUES (
453
+ $id, $sessionID, $source, $at, $cost, $input, $output, $reasoning, $cacheRead, $cacheWrite
454
+ ) ON CONFLICT(id) DO NOTHING`).run({
455
+ $id: record.id,
456
+ $sessionID: record.sessionID,
457
+ $source: sanitizeLabel(record.source, 64),
458
+ $at: timestamp(record.at) ?? Date.now(),
459
+ $cost: Math.max(0, finite(record.cost)),
460
+ $input: tokenCount(record.input),
461
+ $output: tokenCount(record.output),
462
+ $reasoning: tokenCount(record.reasoning),
463
+ $cacheRead: tokenCount(record.cacheRead),
464
+ $cacheWrite: tokenCount(record.cacheWrite)
360
465
  });
361
466
  }
362
467
  function recordPrompt(db, record) {
@@ -365,16 +470,16 @@ function recordPrompt(db, record) {
365
470
  ON CONFLICT(session_id, message_id) DO UPDATE SET created_at = COALESCE(excluded.created_at, prompts.created_at)`).run({
366
471
  $sessionID: record.sessionID,
367
472
  $messageID: record.messageID,
368
- $createdAt: record.createdAt ?? null
473
+ $createdAt: timestamp(record.createdAt)
369
474
  });
370
475
  }
371
476
  function recordEvent(db, record) {
372
- db.query(`INSERT INTO events (session_id, kind, message_id, at, data)
477
+ db.query(`INSERT OR IGNORE INTO events (session_id, kind, message_id, at, data)
373
478
  VALUES ($sessionID, $kind, $messageID, $at, $data)`).run({
374
479
  $sessionID: record.sessionID,
375
480
  $kind: sanitizeLabel(record.kind, 64),
376
481
  $messageID: record.messageID ?? null,
377
- $at: record.at ?? Date.now(),
482
+ $at: timestamp(record.at) ?? Date.now(),
378
483
  $data: jsonText(record.data)
379
484
  });
380
485
  }
@@ -391,8 +496,8 @@ function upsertSession(db, record) {
391
496
  $parentID: record.parentID ?? null,
392
497
  $directory: record.directory === undefined ? null : sanitizeLabel(record.directory, LABEL_LIMIT),
393
498
  $title: record.title === undefined ? null : sanitizeLabel(record.title, LABEL_LIMIT),
394
- $startedAt: record.startedAt ?? null,
395
- $updatedAt: record.updatedAt ?? null
499
+ $startedAt: timestamp(record.startedAt),
500
+ $updatedAt: timestamp(record.updatedAt)
396
501
  });
397
502
  }
398
503
 
@@ -420,14 +525,23 @@ function transcriptTail(messages, count) {
420
525
  segments.unshift({ assistants: current, prompt: undefined });
421
526
  return segments;
422
527
  }
528
+ function countOf(value) {
529
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
530
+ }
531
+ function amountOf(value) {
532
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
533
+ }
534
+ function stampOf(value) {
535
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
536
+ }
423
537
  function tokenCounts(message) {
424
538
  const tokens = message.tokens;
425
539
  return {
426
- input: tokens?.input ?? 0,
427
- output: tokens?.output ?? 0,
428
- reasoning: tokens?.reasoning ?? 0,
429
- read: tokens?.cache?.read ?? 0,
430
- write: tokens?.cache?.write ?? 0
540
+ input: countOf(tokens?.input),
541
+ output: countOf(tokens?.output),
542
+ reasoning: countOf(tokens?.reasoning),
543
+ read: countOf(tokens?.cache?.read),
544
+ write: countOf(tokens?.cache?.write)
431
545
  };
432
546
  }
433
547
  function totalize(steps) {
@@ -439,8 +553,8 @@ function totalize(steps) {
439
553
  totals.output += counts.output;
440
554
  totals.reasoning += counts.reasoning;
441
555
  totals.cacheWrite += counts.write;
442
- totals.cost += step.cost ?? 0;
443
- totals.listCost += step.listCost ?? 0;
556
+ totals.cost += amountOf(step.cost);
557
+ totals.listCost += amountOf(step.listCost);
444
558
  }
445
559
  return totals;
446
560
  }
@@ -450,16 +564,16 @@ function identityKey(model) {
450
564
  return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
451
565
  }
452
566
  function cacheRead(message) {
453
- return message?.tokens?.cache?.read ?? 0;
567
+ return countOf(message?.tokens?.cache?.read);
454
568
  }
455
569
  function stepCreated(message) {
456
- return message?.time?.created;
570
+ return stampOf(message?.time?.created);
457
571
  }
458
572
  function stepEnd(message) {
459
573
  const time = message?.time;
460
574
  if (!time)
461
575
  return;
462
- return time.completed ?? time.streamed ?? time.created;
576
+ return stampOf(time.completed) ?? stampOf(time.streamed) ?? stampOf(time.created);
463
577
  }
464
578
  function cacheDrop(reference, current, scope = "provider") {
465
579
  if (!reference)
@@ -486,9 +600,9 @@ function stepGap(reference, current) {
486
600
  return Math.max(0, started - ended);
487
601
  }
488
602
  function tokensPerSecond(produced, from, to) {
489
- if (from === undefined || to === undefined || to <= from)
603
+ if (from === undefined || to === undefined || !Number.isFinite(from) || !Number.isFinite(to) || to <= from)
490
604
  return;
491
- if (produced <= 0)
605
+ if (!Number.isFinite(produced) || produced <= 0)
492
606
  return;
493
607
  return produced / (to - from) * 1000;
494
608
  }
@@ -532,7 +646,7 @@ function computeTurn(messages, session) {
532
646
  return {
533
647
  endAt: stepEnd(lastStep),
534
648
  startAt: stepCreated(settled[0] ?? lastStep),
535
- promptAt: last.prompt?.time?.created,
649
+ promptAt: stampOf(last.prompt?.time?.created),
536
650
  promptGapMs: promptGap(last.prompt, previous?.prompt),
537
651
  providerID: provider,
538
652
  modelID: lastStep.model?.id,
@@ -549,8 +663,8 @@ function computeTurn(messages, session) {
549
663
  };
550
664
  }
551
665
  function promptGap(current, previous) {
552
- const now = current?.time?.created;
553
- const before = previous?.time?.created;
666
+ const now = stampOf(current?.time?.created);
667
+ const before = stampOf(previous?.time?.created);
554
668
  if (now === undefined || before === undefined)
555
669
  return;
556
670
  return Math.max(0, now - before);
@@ -588,11 +702,15 @@ var DEFAULT_FIELDS = {
588
702
  cacheExpiry: true
589
703
  };
590
704
  function formatClock(ms) {
705
+ if (!Number.isFinite(ms))
706
+ return "--:--";
591
707
  const date = new Date(ms);
592
708
  const pad = (value) => String(value).padStart(2, "0");
593
709
  return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
594
710
  }
595
711
  function formatDuration(ms) {
712
+ if (!Number.isFinite(ms))
713
+ return "\u2013";
596
714
  const totalSeconds = Math.max(0, Math.floor(ms / 1000));
597
715
  const seconds = totalSeconds % 60;
598
716
  const minutes = Math.floor(totalSeconds / 60) % 60;
@@ -607,7 +725,7 @@ function formatDuration(ms) {
607
725
  return `${seconds}s`;
608
726
  }
609
727
  function formatTokens(value) {
610
- const n = Math.max(0, Math.round(value));
728
+ const n = Number.isFinite(value) ? Math.max(0, Math.round(value)) : 0;
611
729
  if (n < 1000)
612
730
  return String(n);
613
731
  if (n < 999500) {
@@ -624,8 +742,10 @@ function trimZeros(value) {
624
742
  return value.includes(".") ? value.replace(/0+$/, "").replace(/\.$/, "") : value;
625
743
  }
626
744
  function formatCost(value) {
627
- if (value <= 0)
745
+ if (!Number.isFinite(value) || value <= 0)
628
746
  return "$0";
747
+ if (value < 0.00005)
748
+ return "<$0.0001";
629
749
  if (value < 1)
630
750
  return `$${value.toFixed(4)}`;
631
751
  return `$${value.toFixed(2)}`;
@@ -735,6 +855,66 @@ function sessionListCost(db, sessionID) {
735
855
  const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
736
856
  return row?.listCost ?? 0;
737
857
  }
858
+ var EMPTY_OTHER = { entries: 0, cost: 0 };
859
+ function hasUsageTable(db) {
860
+ try {
861
+ return db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'usage'").get() !== null;
862
+ } catch {
863
+ return false;
864
+ }
865
+ }
866
+ function otherWhere(range, filters) {
867
+ if (filters?.modelID !== undefined && filters.modelID !== "")
868
+ return;
869
+ if (filters?.modelKey !== undefined && filters.modelKey !== "")
870
+ return;
871
+ if (filters?.provider !== undefined && filters.provider !== "")
872
+ return;
873
+ const span = rangeWhere(range, "at");
874
+ const clauses = span.where === "" ? [] : [span.where.slice("WHERE ".length)];
875
+ const params = [...span.params];
876
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
877
+ clauses.push("session_id = ?");
878
+ params.push(filters.sessionID);
879
+ }
880
+ return { where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "", params };
881
+ }
882
+ function otherUsage(db, range, filters) {
883
+ const filter = otherWhere(range, filters);
884
+ if (filter === undefined || !hasUsageTable(db))
885
+ return { ...EMPTY_OTHER };
886
+ try {
887
+ const row = db.query(`SELECT COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost FROM usage ${filter.where}`).get(...filter.params);
888
+ return { entries: row?.entries ?? 0, cost: row?.cost ?? 0 };
889
+ } catch {
890
+ return { ...EMPTY_OTHER };
891
+ }
892
+ }
893
+ function otherUsageBySession(db, range, filters) {
894
+ const out = new Map;
895
+ const filter = otherWhere(range, filters);
896
+ if (filter === undefined || !hasUsageTable(db))
897
+ return out;
898
+ try {
899
+ const rows = db.query(`SELECT session_id AS sessionID, COUNT(*) AS entries, COALESCE(SUM(cost), 0) AS cost
900
+ FROM usage ${filter.where}
901
+ GROUP BY session_id`).all(...filter.params);
902
+ for (const row of rows)
903
+ out.set(row.sessionID, { entries: row.entries ?? 0, cost: row.cost ?? 0 });
904
+ } catch {}
905
+ return out;
906
+ }
907
+ function otherUsageRows(db, range, filters) {
908
+ const filter = otherWhere(range, filters);
909
+ if (filter === undefined || !hasUsageTable(db))
910
+ return [];
911
+ const where = filter.where === "" ? "WHERE at IS NOT NULL" : `${filter.where} AND at IS NOT NULL`;
912
+ try {
913
+ return db.query(`SELECT session_id AS sessionID, at, cost FROM usage ${where} ORDER BY at`).all(...filter.params);
914
+ } catch {
915
+ return [];
916
+ }
917
+ }
738
918
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
739
919
  var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
740
920
  function modelKey(modelID, variant) {
@@ -812,12 +992,22 @@ function overview(db, range, filters) {
812
992
  COALESCE(SUM(CASE WHEN streamed_at > created_at THEN streamed_at - created_at ELSE 0 END), 0) AS window
813
993
  FROM steps ${steps.where}`).get(...steps.params);
814
994
  const prompts = rangeWhere(range, "created_at");
815
- const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${prompts.where}`).get(...prompts.params);
995
+ const promptClauses = prompts.where === "" ? [] : [prompts.where.slice("WHERE ".length)];
996
+ const promptParams = [...prompts.params];
997
+ if (filters?.sessionID !== undefined && filters.sessionID !== "") {
998
+ promptClauses.push("session_id = ?");
999
+ promptParams.push(filters.sessionID);
1000
+ }
1001
+ const promptWhere = promptClauses.length > 0 ? `WHERE ${promptClauses.join(" AND ")}` : "";
1002
+ const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${promptWhere}`).get(...promptParams);
816
1003
  const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
1004
+ const other = otherUsage(db, range, filters);
817
1005
  return {
818
1006
  ...usage,
1007
+ cost: usage.cost + other.cost,
819
1008
  sessions: row?.sessions ?? 0,
820
1009
  prompts: promptRow?.prompts ?? 0,
1010
+ otherCost: other.cost,
821
1011
  firstAt: row?.firstAt ?? undefined,
822
1012
  lastAt: row?.lastAt ?? undefined,
823
1013
  cacheHitRatio: cacheHitRatio(usage),
@@ -868,7 +1058,7 @@ function addUsage(target, source) {
868
1058
  target.listCost += source.listCost;
869
1059
  }
870
1060
  function billedTokens(usage) {
871
- return usage.input + usage.cached + usage.output;
1061
+ return usage.input + usage.cached + usage.cacheWrite + usage.output + usage.reasoning;
872
1062
  }
873
1063
  function percentile(values, p) {
874
1064
  if (values.length === 0)
@@ -894,6 +1084,17 @@ function sessions(db, options) {
894
1084
  const limit = options?.limit ?? 20;
895
1085
  const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
896
1086
  const params = [...filter.params];
1087
+ const promptRange = [];
1088
+ const promptParams = [];
1089
+ if (range?.from !== undefined) {
1090
+ promptRange.push("p.created_at >= ?");
1091
+ promptParams.push(range.from);
1092
+ }
1093
+ if (range?.to !== undefined) {
1094
+ promptRange.push("p.created_at < ?");
1095
+ promptParams.push(range.to);
1096
+ }
1097
+ const promptClause = promptRange.length > 0 ? ` AND ${promptRange.join(" AND ")}` : "";
897
1098
  if (options?.sessionIDs !== undefined) {
898
1099
  const ids = options.sessionIDs.slice(0, 500);
899
1100
  clauses.push(`st.session_id IN (${ids.map(() => "?").join(", ")})`);
@@ -902,7 +1103,7 @@ function sessions(db, options) {
902
1103
  const rows = db.query(`SELECT st.session_id, s.title, s.directory, s.parent_id,
903
1104
  GROUP_CONCAT(DISTINCT st.provider_id) AS providers,
904
1105
  GROUP_CONCAT(DISTINCT st.model_id) AS models,
905
- (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id) AS prompts,
1106
+ (SELECT COUNT(*) FROM prompts p WHERE p.session_id = st.session_id${promptClause}) AS prompts,
906
1107
  COUNT(*) AS steps,
907
1108
  COALESCE(SUM(st.input_tokens), 0) AS input,
908
1109
  COALESCE(SUM(st.cache_read), 0) AS cached,
@@ -918,11 +1119,14 @@ function sessions(db, options) {
918
1119
  ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
919
1120
  GROUP BY st.session_id
920
1121
  ORDER BY last_at DESC
921
- LIMIT ?`).all(...params, limit);
1122
+ LIMIT ?`).all(...promptParams, ...params, limit);
1123
+ const other = otherUsageBySession(db, range, options?.filters);
922
1124
  return rows.map((row) => {
923
1125
  const usage = usageFrom(row);
1126
+ const extra = other.get(row.session_id)?.cost ?? 0;
924
1127
  return {
925
1128
  ...usage,
1129
+ cost: usage.cost + extra,
926
1130
  sessionID: row.session_id,
927
1131
  parentID: row.parent_id ?? undefined,
928
1132
  title: row.title ?? undefined,
@@ -930,6 +1134,7 @@ function sessions(db, options) {
930
1134
  providers: row.providers ? row.providers.split(",").filter(Boolean) : [],
931
1135
  models: row.models ? row.models.split(",").filter(Boolean) : [],
932
1136
  prompts: row.prompts ?? 0,
1137
+ otherCost: extra,
933
1138
  firstAt: row.first_at ?? undefined,
934
1139
  lastAt: row.last_at ?? undefined,
935
1140
  cacheHitRatio: cacheHitRatio(usage)
@@ -973,118 +1178,131 @@ function stepMessage(row) {
973
1178
  };
974
1179
  }
975
1180
  function turns(db, options) {
976
- const limit = options?.limit ?? 50;
1181
+ const requested = options?.limit ?? 50;
1182
+ const limit = Number.isFinite(requested) ? Math.max(0, Math.floor(requested)) : 50;
977
1183
  const filter = buildWhere(options?.range, options?.filters);
978
- const clauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
979
- const params = [...filter.params];
1184
+ const baseClauses = filter.where === "" ? [] : [filter.where.slice("WHERE ".length)];
1185
+ const baseParams = [...filter.params];
980
1186
  if (options?.sessionID !== undefined) {
981
- clauses.push("session_id = ?");
982
- params.push(options.sessionID);
983
- }
984
- const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, limit + 1);
985
- if (floor !== undefined) {
986
- clauses.push(`${STEP_TIME} >= ?`);
987
- params.push(floor);
1187
+ baseClauses.push("session_id = ?");
1188
+ baseParams.push(options.sessionID);
988
1189
  }
989
- const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
990
- input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
991
- created_at, streamed_at, recorded_at, completed_at, finish
992
- FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
993
- ORDER BY session_id, ${STEP_TIME}`).all(...params);
994
- const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
995
- const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
996
- const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
997
- const promptsBySession = new Map;
998
- for (const row of promptRows) {
999
- if (row.created_at === null)
1000
- continue;
1001
- const list = promptsBySession.get(row.session_id) ?? [];
1002
- list.push(row.created_at);
1003
- promptsBySession.set(row.session_id, list);
1004
- }
1005
- const result = [];
1006
- let sessionID;
1007
- let bucket = [];
1008
- let promptIndex = -2;
1009
- let promptAt;
1010
- let previousPromptAt;
1011
- function close() {
1012
- const last = bucket[bucket.length - 1];
1013
- if (last === undefined || !turnFinished(last.finish)) {
1014
- bucket = [];
1015
- return;
1016
- }
1017
- const totals = emptyUsage();
1018
- for (const row of bucket)
1019
- addUsage(totals, stepUsage(row));
1020
- const drops = [];
1021
- let reference;
1022
- for (const row of bucket) {
1023
- const message = stepMessage(row);
1024
- const drop = cacheDrop(reference, message);
1025
- if (drop !== undefined) {
1026
- drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
1027
- }
1028
- reference = message;
1190
+ function read(promptCount) {
1191
+ const clauses = [...baseClauses];
1192
+ const params = [...baseParams];
1193
+ const floor = options?.sessionID === undefined ? undefined : promptFloor(db, options.sessionID, promptCount);
1194
+ if (floor !== undefined) {
1195
+ clauses.push(`${STEP_TIME} >= ?`);
1196
+ params.push(floor);
1029
1197
  }
1030
- const providerID = last.provider_id ?? undefined;
1031
- const modelID = last.model_id ?? undefined;
1032
- const variant = last.variant ?? undefined;
1033
- let produced = 0;
1034
- let window = 0;
1035
- for (const row of bucket) {
1036
- if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
1198
+ const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
1199
+ input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
1200
+ created_at, streamed_at, recorded_at, completed_at, finish
1201
+ FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
1202
+ ORDER BY session_id, ${STEP_TIME}, message_id`).all(...params);
1203
+ const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
1204
+ const promptParams = options?.sessionID === undefined ? [] : floor === undefined ? [options.sessionID] : [options.sessionID, floor];
1205
+ const promptRows = db.query(`SELECT session_id, created_at FROM prompts ${promptClause} ORDER BY session_id, created_at`).all(...promptParams);
1206
+ const promptsBySession = new Map;
1207
+ for (const row of promptRows) {
1208
+ if (row.created_at === null)
1037
1209
  continue;
1038
- produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
1039
- window += row.streamed_at - row.created_at;
1210
+ const list = promptsBySession.get(row.session_id) ?? [];
1211
+ list.push(row.created_at);
1212
+ promptsBySession.set(row.session_id, list);
1040
1213
  }
1041
- const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
1042
- result.push({
1043
- sessionID: last.session_id,
1044
- promptAt,
1045
- endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
1046
- promptGapMs: promptAt !== undefined && previousPromptAt !== undefined ? Math.max(0, promptAt - previousPromptAt) : undefined,
1047
- providerID,
1048
- modelID,
1049
- variant,
1050
- providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
1051
- modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
1052
- steps: bucket.length,
1053
- latest: stepUsage(last),
1054
- totals,
1055
- drops,
1056
- finish: last.finish ?? undefined,
1057
- tps: tokensPerSecond(produced, 0, window)
1058
- });
1059
- bucket = [];
1060
- }
1061
- for (const row of steps) {
1062
- if (row.session_id !== sessionID) {
1063
- close();
1064
- sessionID = row.session_id;
1065
- promptIndex = -2;
1066
- promptAt = undefined;
1067
- previousPromptAt = undefined;
1068
- }
1069
- const time = row.created_at ?? row.recorded_at;
1070
- const prompts = promptsBySession.get(row.session_id) ?? [];
1071
- let index = -1;
1072
- for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
1073
- if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
1074
- index = candidate;
1075
- break;
1214
+ const result = [];
1215
+ let sessionID;
1216
+ let bucket = [];
1217
+ let promptIndex = -2;
1218
+ let promptAt;
1219
+ function close() {
1220
+ const last = bucket[bucket.length - 1];
1221
+ if (last === undefined || !turnFinished(last.finish)) {
1222
+ bucket = [];
1223
+ return;
1224
+ }
1225
+ const totals = emptyUsage();
1226
+ for (const row of bucket)
1227
+ addUsage(totals, stepUsage(row));
1228
+ const drops = [];
1229
+ let reference;
1230
+ for (const row of bucket) {
1231
+ const message = stepMessage(row);
1232
+ const drop = cacheDrop(reference, message);
1233
+ if (drop !== undefined) {
1234
+ drops.push({ messageID: row.message_id, tokens: drop, gapMs: stepGap(reference, message) });
1235
+ }
1236
+ reference = message;
1237
+ }
1238
+ const providerID = last.provider_id ?? undefined;
1239
+ const modelID = last.model_id ?? undefined;
1240
+ const variant = last.variant ?? undefined;
1241
+ let produced = 0;
1242
+ let window = 0;
1243
+ for (const row of bucket) {
1244
+ if (row.created_at === null || row.streamed_at === null || row.streamed_at <= row.created_at)
1245
+ continue;
1246
+ produced += (row.output_tokens ?? 0) + (row.reasoning_tokens ?? 0);
1247
+ window += row.streamed_at - row.created_at;
1076
1248
  }
1249
+ const previous = result.length > 0 && result[result.length - 1].sessionID === last.session_id ? result[result.length - 1] : undefined;
1250
+ result.push({
1251
+ sessionID: last.session_id,
1252
+ promptAt,
1253
+ endAt: last.completed_at ?? last.created_at ?? last.recorded_at,
1254
+ promptGapMs: promptAt !== undefined && previous?.promptAt !== undefined ? Math.max(0, promptAt - previous.promptAt) : undefined,
1255
+ providerID,
1256
+ modelID,
1257
+ variant,
1258
+ providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
1259
+ modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
1260
+ steps: bucket.length,
1261
+ latest: stepUsage(last),
1262
+ totals,
1263
+ drops,
1264
+ finish: last.finish ?? undefined,
1265
+ tps: tokensPerSecond(produced, 0, window)
1266
+ });
1267
+ bucket = [];
1077
1268
  }
1078
- if (index !== promptIndex) {
1079
- close();
1080
- promptIndex = index;
1081
- promptAt = index >= 0 ? prompts[index] : undefined;
1082
- previousPromptAt = index >= 1 ? prompts[index - 1] : undefined;
1269
+ for (const row of steps) {
1270
+ if (row.session_id !== sessionID) {
1271
+ close();
1272
+ sessionID = row.session_id;
1273
+ promptIndex = -2;
1274
+ promptAt = undefined;
1275
+ }
1276
+ const time = row.created_at ?? row.recorded_at;
1277
+ const prompts = promptsBySession.get(row.session_id) ?? [];
1278
+ let index = -1;
1279
+ for (let candidate = prompts.length - 1;candidate >= 0; candidate -= 1) {
1280
+ if ((prompts[candidate] ?? Number.POSITIVE_INFINITY) <= time) {
1281
+ index = candidate;
1282
+ break;
1283
+ }
1284
+ }
1285
+ if (index !== promptIndex) {
1286
+ close();
1287
+ promptIndex = index;
1288
+ promptAt = index >= 0 ? prompts[index] : undefined;
1289
+ }
1290
+ bucket.push(row);
1083
1291
  }
1084
- bucket.push(row);
1292
+ close();
1293
+ const reachedRangeStart = options?.range?.from !== undefined && floor !== undefined && floor <= options.range.from;
1294
+ return { rows: result.reverse(), complete: floor === undefined || reachedRangeStart };
1295
+ }
1296
+ let promptCount = Math.max(1, limit + 1);
1297
+ for (;; ) {
1298
+ const { rows, complete } = read(promptCount);
1299
+ if (rows.length >= limit || complete)
1300
+ return rows.slice(0, limit);
1301
+ const next = promptCount * 2 + 1;
1302
+ if (!Number.isFinite(next) || next <= promptCount)
1303
+ return rows.slice(0, limit);
1304
+ promptCount = next;
1085
1305
  }
1086
- close();
1087
- return result.reverse().slice(0, limit);
1088
1306
  }
1089
1307
  function promptFloor(db, sessionID, count) {
1090
1308
  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);
@@ -1278,12 +1496,35 @@ function createRecorder(db, options) {
1278
1496
  recordPendingStep(data.assistantMessageID, data, data.finish ?? "error", at);
1279
1497
  return;
1280
1498
  }
1499
+ case "session.usage.recorded": {
1500
+ if (sessionID === undefined)
1501
+ return;
1502
+ const source = typeof data.source === "string" ? data.source : undefined;
1503
+ if (source === undefined || source === "generate")
1504
+ return;
1505
+ const id = typeof event.id === "string" && event.id !== "" ? event.id : `${sessionID}:${source}:${at}:${data.cost ?? 0}`;
1506
+ write(() => recordUsage(db, {
1507
+ id,
1508
+ sessionID,
1509
+ source,
1510
+ at,
1511
+ cost: data.cost,
1512
+ input: data.tokens?.input,
1513
+ output: data.tokens?.output,
1514
+ reasoning: data.tokens?.reasoning,
1515
+ cacheRead: data.tokens?.cache?.read,
1516
+ cacheWrite: data.tokens?.cache?.write
1517
+ }));
1518
+ return;
1519
+ }
1281
1520
  case "session.compaction.ended": {
1282
1521
  if (sessionID === undefined)
1283
1522
  return;
1523
+ const messageID = typeof event.id === "string" && event.id !== "" ? event.id : `compaction:${sessionID}:${at}`;
1284
1524
  write(() => recordEvent(db, {
1285
1525
  sessionID,
1286
1526
  kind: COMPACTION_KIND,
1527
+ messageID,
1287
1528
  at,
1288
1529
  data: { reason: data.reason, model: data.model, tokens: data.tokens, cost: data.cost }
1289
1530
  }));
@@ -1387,4 +1628,4 @@ export {
1387
1628
  src_default as default
1388
1629
  };
1389
1630
 
1390
- //# debugId=453796543F95785064756E2164756E21
1631
+ //# debugId=54D17612579BB39464756E2164756E21