opencode-usage-insights 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,6 +2,75 @@
2
2
  // src/index.ts
3
3
  import { Plugin } from "@opencode/plugin";
4
4
 
5
+ // src/pricing.ts
6
+ function money(value) {
7
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
8
+ }
9
+ function tokens(value) {
10
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
11
+ }
12
+ function priceTable(models) {
13
+ const table = new Map;
14
+ if (!Array.isArray(models))
15
+ return table;
16
+ for (const model of models) {
17
+ if (model === null || model === undefined)
18
+ continue;
19
+ const providerID = model.providerID;
20
+ const modelID = model.modelID ?? model.id;
21
+ if (typeof providerID !== "string" || providerID === "")
22
+ continue;
23
+ if (typeof modelID !== "string" || modelID === "")
24
+ continue;
25
+ if (!Array.isArray(model.cost) || model.cost.length === 0)
26
+ continue;
27
+ const tiers = [];
28
+ for (const cost of model.cost) {
29
+ if (cost === null || cost === undefined)
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;
33
+ tiers.push({
34
+ ...tier !== undefined ? { tier } : {},
35
+ input: money(cost.input),
36
+ output: money(cost.output),
37
+ cacheRead: money(cost.cache?.read),
38
+ cacheWrite: money(cost.cache?.write)
39
+ });
40
+ }
41
+ if (tiers.length > 0)
42
+ table.set(`${providerID}/${modelID}`, { tiers });
43
+ }
44
+ return table;
45
+ }
46
+ function priceOf(table, ref) {
47
+ if (ref.providerID === undefined || ref.providerID === "")
48
+ return;
49
+ if (ref.modelID === undefined || ref.modelID === "")
50
+ return;
51
+ return table.get(`${ref.providerID}/${ref.modelID}`);
52
+ }
53
+ function costOf(table, ref, usage) {
54
+ const price = priceOf(table, ref);
55
+ if (price === undefined)
56
+ return;
57
+ const input = tokens(usage.input);
58
+ const output = tokens(usage.output);
59
+ const reasoning = tokens(usage.reasoning);
60
+ const cacheRead = tokens(usage.cacheRead);
61
+ const cacheWrite = tokens(usage.cacheWrite);
62
+ const prompt = input + cacheRead + cacheWrite;
63
+ const selected = price.tiers.filter((tier) => tier.tier?.type === "context" && prompt > tier.tier.size).sort((left, right) => (right.tier?.size ?? 0) - (left.tier?.size ?? 0))[0] ?? price.tiers.find((tier) => tier.tier === undefined);
64
+ if (selected === undefined)
65
+ return;
66
+ if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
67
+ return 0;
68
+ const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
69
+ if (!Number.isFinite(billed) || billed <= 0)
70
+ return;
71
+ return billed / 1e6;
72
+ }
73
+
5
74
  // src/stats/db.ts
6
75
  import { Database } from "bun:sqlite";
7
76
  import { chmodSync, mkdirSync } from "fs";
@@ -72,7 +141,7 @@ function isToken(value, limit = 64) {
72
141
  }
73
142
 
74
143
  // src/stats/db.ts
75
- var SCHEMA_VERSION = 9;
144
+ var SCHEMA_VERSION = 10;
76
145
  var LABEL_LIMIT = 4 * TEXT_LIMIT;
77
146
  var SCHEMA = `
78
147
  CREATE TABLE IF NOT EXISTS meta (
@@ -110,6 +179,7 @@ CREATE TABLE IF NOT EXISTS steps (
110
179
  cache_read INTEGER NOT NULL DEFAULT 0,
111
180
  cache_write INTEGER NOT NULL DEFAULT 0,
112
181
  cost REAL NOT NULL DEFAULT 0,
182
+ list_cost REAL,
113
183
  created_at INTEGER,
114
184
  streamed_at INTEGER,
115
185
  completed_at INTEGER,
@@ -171,8 +241,15 @@ function dropUnused(db) {
171
241
  db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
172
242
  }
173
243
  }
244
+ function addMissing(db) {
245
+ const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
246
+ if (columns.size > 0 && !columns.has("list_cost")) {
247
+ db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
248
+ }
249
+ }
174
250
  function migrate(db) {
175
251
  dropUnused(db);
252
+ addMissing(db);
176
253
  }
177
254
  var POSIX = process.platform !== "win32";
178
255
  function hardenDirectory(path) {
@@ -235,11 +312,11 @@ function openStatsDbWrite(path) {
235
312
  function recordStep(db, record) {
236
313
  db.query(`INSERT INTO steps (
237
314
  message_id, session_id, parent_id, provider_id, model_id, variant,
238
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost,
315
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
239
316
  created_at, streamed_at, completed_at, finish, recorded_at
240
317
  ) VALUES (
241
318
  $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
242
- $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost,
319
+ $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
243
320
  $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
244
321
  )
245
322
  ON CONFLICT(message_id) DO UPDATE SET
@@ -254,6 +331,9 @@ function recordStep(db, record) {
254
331
  cache_read = excluded.cache_read,
255
332
  cache_write = excluded.cache_write,
256
333
  cost = excluded.cost,
334
+ -- A step that starts being charged loses its estimate; an estimate is
335
+ -- kept when a replayed event arrives without a price table.
336
+ list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
257
337
  created_at = COALESCE(excluded.created_at, steps.created_at),
258
338
  streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
259
339
  completed_at = COALESCE(excluded.completed_at, steps.completed_at),
@@ -271,6 +351,7 @@ function recordStep(db, record) {
271
351
  $cacheRead: record.cacheRead ?? 0,
272
352
  $cacheWrite: record.cacheWrite ?? 0,
273
353
  $cost: record.cost ?? 0,
354
+ $listCost: (record.cost ?? 0) <= 0 && record.listCost !== undefined && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null,
274
355
  $createdAt: record.createdAt ?? null,
275
356
  $streamedAt: record.streamedAt ?? null,
276
357
  $completedAt: record.completedAt ?? null,
@@ -350,7 +431,7 @@ function tokenCounts(message) {
350
431
  };
351
432
  }
352
433
  function totalize(steps) {
353
- const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, steps: steps.length };
434
+ const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
354
435
  for (const step of steps) {
355
436
  const counts = tokenCounts(step);
356
437
  totals.input += counts.input;
@@ -359,6 +440,7 @@ function totalize(steps) {
359
440
  totals.reasoning += counts.reasoning;
360
441
  totals.cacheWrite += counts.write;
361
442
  totals.cost += step.cost ?? 0;
443
+ totals.listCost += step.listCost ?? 0;
362
444
  }
363
445
  return totals;
364
446
  }
@@ -489,6 +571,7 @@ var DEFAULT_LABELS = {
489
571
  output: "out",
490
572
  reasoning: "reason",
491
573
  cost: "cost",
574
+ estimate: "\u2248",
492
575
  cacheExpired: "cache expired",
493
576
  providerChanged: "changed",
494
577
  modelChanged: "model changed"
@@ -547,6 +630,20 @@ function formatCost(value) {
547
630
  return `$${value.toFixed(4)}`;
548
631
  return `$${value.toFixed(2)}`;
549
632
  }
633
+ function formatMoney(charged, estimated, marker = "\u2248") {
634
+ const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
635
+ const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
636
+ if (paid !== undefined && estimate !== undefined)
637
+ return `${paid} + ${estimate}`;
638
+ return paid ?? estimate;
639
+ }
640
+ function formatSpend(charged, estimated, marker = "\u2248") {
641
+ const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
642
+ const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
643
+ if (estimate > 0)
644
+ return `${marker.trim()}${formatCost(paid + estimate)}`;
645
+ return formatCost(paid);
646
+ }
550
647
  function displayTotals(totals) {
551
648
  const prompt = totals.input + totals.cached + totals.cacheWrite;
552
649
  return {
@@ -556,11 +653,12 @@ function displayTotals(totals) {
556
653
  output: totals.output + totals.reasoning,
557
654
  reasoning: totals.reasoning,
558
655
  cost: totals.cost,
656
+ listCost: totals.listCost,
559
657
  steps: totals.steps,
560
658
  prompt
561
659
  };
562
660
  }
563
- function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost) {
661
+ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
564
662
  const display = displayTotals(totals);
565
663
  const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
566
664
  const parts = [
@@ -570,8 +668,9 @@ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals
570
668
  ];
571
669
  if (fields.reasoning)
572
670
  parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
573
- if (fields.cost && cost > 0)
574
- parts.push(`${labels.cost} ${formatCost(cost)}`);
671
+ const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
672
+ if (money !== undefined)
673
+ parts.push(`${labels.cost} ${money}`);
575
674
  const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
576
675
  const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
577
676
  const numbers = parts.join(", ");
@@ -583,6 +682,7 @@ function formatLineSegments(stats, options) {
583
682
  const labels = { ...DEFAULT_LABELS, ...options?.labels };
584
683
  const fields = { ...DEFAULT_FIELDS, ...options?.fields };
585
684
  const turnTotals = options?.turnTotals ?? "latest";
685
+ const estimates = options?.estimates !== false;
586
686
  const segments = [];
587
687
  if (fields.clock && stats.endAt !== undefined) {
588
688
  segments.push({ text: formatClock(stats.endAt), tone: "muted" });
@@ -605,12 +705,15 @@ function formatLineSegments(stats, options) {
605
705
  if (fields.turn && stats.totals.steps > 0) {
606
706
  const totals = turnTotals === "sum" ? stats.totals : stats.latest;
607
707
  segments.push({
608
- text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost),
708
+ text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
609
709
  tone: "base"
610
710
  });
611
711
  }
612
712
  if (fields.session && stats.session) {
613
- segments.push({ text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost), tone: "muted" });
713
+ segments.push({
714
+ text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
715
+ tone: "muted"
716
+ });
614
717
  }
615
718
  if (fields.cacheExpiry && stats.cacheExpired) {
616
719
  const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
@@ -625,6 +728,13 @@ function formatLine(stats, options) {
625
728
  // src/stats/queries.ts
626
729
  var COMPACTION_KIND = "compaction";
627
730
  var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
731
+ function spend(usage) {
732
+ return usage.cost + usage.listCost;
733
+ }
734
+ function sessionListCost(db, sessionID) {
735
+ const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
736
+ return row?.listCost ?? 0;
737
+ }
628
738
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
629
739
  var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
630
740
  function modelKey(modelID, variant) {
@@ -639,7 +749,8 @@ var USAGE_SELECT = `COUNT(*) AS steps,
639
749
  COALESCE(SUM(cache_write), 0) AS cacheWrite,
640
750
  COALESCE(SUM(output_tokens), 0) AS output,
641
751
  COALESCE(SUM(reasoning_tokens), 0) AS reasoning,
642
- COALESCE(SUM(cost), 0) AS cost`;
752
+ COALESCE(SUM(cost), 0) AS cost,
753
+ COALESCE(SUM(list_cost), 0) AS listCost`;
643
754
  function usageFrom(row) {
644
755
  return {
645
756
  steps: row.steps ?? 0,
@@ -648,7 +759,8 @@ function usageFrom(row) {
648
759
  cacheWrite: row.cacheWrite ?? 0,
649
760
  output: row.output ?? 0,
650
761
  reasoning: row.reasoning ?? 0,
651
- cost: row.cost ?? 0
762
+ cost: row.cost ?? 0,
763
+ listCost: row.listCost ?? 0
652
764
  };
653
765
  }
654
766
  function rangeWhere(range, column = STEP_TIME) {
@@ -701,7 +813,7 @@ function overview(db, range, filters) {
701
813
  FROM steps ${steps.where}`).get(...steps.params);
702
814
  const prompts = rangeWhere(range, "created_at");
703
815
  const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${prompts.where}`).get(...prompts.params);
704
- const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 });
816
+ const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
705
817
  return {
706
818
  ...usage,
707
819
  sessions: row?.sessions ?? 0,
@@ -743,7 +855,7 @@ function models(db, range, filters) {
743
855
  return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
744
856
  }
745
857
  function emptyUsage() {
746
- return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 };
858
+ return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
747
859
  }
748
860
  function addUsage(target, source) {
749
861
  target.steps += source.steps;
@@ -753,6 +865,7 @@ function addUsage(target, source) {
753
865
  target.output += source.output;
754
866
  target.reasoning += source.reasoning;
755
867
  target.cost += source.cost;
868
+ target.listCost += source.listCost;
756
869
  }
757
870
  function billedTokens(usage) {
758
871
  return usage.input + usage.cached + usage.output;
@@ -797,6 +910,7 @@ function sessions(db, options) {
797
910
  COALESCE(SUM(st.output_tokens), 0) AS output,
798
911
  COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,
799
912
  COALESCE(SUM(st.cost), 0) AS cost,
913
+ COALESCE(SUM(st.list_cost), 0) AS listCost,
800
914
  MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,
801
915
  MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at
802
916
  FROM steps st
@@ -839,7 +953,8 @@ function stepUsage(row) {
839
953
  cacheWrite: row.cache_write ?? 0,
840
954
  output: row.output_tokens ?? 0,
841
955
  reasoning: row.reasoning_tokens ?? 0,
842
- cost: row.cost ?? 0
956
+ cost: row.cost ?? 0,
957
+ listCost: row.list_cost ?? 0
843
958
  };
844
959
  }
845
960
  function stepMessage(row) {
@@ -872,7 +987,7 @@ function turns(db, options) {
872
987
  params.push(floor);
873
988
  }
874
989
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
875
- input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost,
990
+ input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
876
991
  created_at, streamed_at, recorded_at, completed_at, finish
877
992
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
878
993
  ORDER BY session_id, ${STEP_TIME}`).all(...params);
@@ -1048,6 +1163,14 @@ function createRecorder(db, options) {
1048
1163
  const info = pending.get(messageID);
1049
1164
  pending.delete(messageID);
1050
1165
  const model = info?.model ?? lastModel.get(sessionID);
1166
+ const charged = data.cost;
1167
+ const estimate = charged !== undefined && charged > 0 ? undefined : options?.price?.({ providerID: model?.providerID, modelID: model?.id }, {
1168
+ input: data.tokens?.input,
1169
+ output: data.tokens?.output,
1170
+ reasoning: data.tokens?.reasoning,
1171
+ cacheRead: data.tokens?.cache?.read,
1172
+ cacheWrite: data.tokens?.cache?.write
1173
+ });
1051
1174
  write(() => recordStep(db, {
1052
1175
  messageID,
1053
1176
  sessionID,
@@ -1060,6 +1183,7 @@ function createRecorder(db, options) {
1060
1183
  cacheRead: data.tokens?.cache?.read,
1061
1184
  cacheWrite: data.tokens?.cache?.write,
1062
1185
  cost: data.cost,
1186
+ listCost: estimate !== undefined && Number.isFinite(estimate) && estimate >= 0 ? estimate : undefined,
1063
1187
  createdAt: info?.started,
1064
1188
  streamedAt: info?.streamed,
1065
1189
  completedAt: at,
@@ -1183,6 +1307,40 @@ function createRecorder(db, options) {
1183
1307
  }
1184
1308
 
1185
1309
  // src/index.ts
1310
+ var PRICE_TTL_MS = 5 * 60 * 1000;
1311
+ var PRICE_RETRY_MS = 30 * 1000;
1312
+ function createPriceSource(ctx) {
1313
+ let table;
1314
+ let refreshing = false;
1315
+ let lastAttempt = 0;
1316
+ function refresh(force = false) {
1317
+ if (refreshing)
1318
+ return;
1319
+ const now = Date.now();
1320
+ const wait = table === undefined ? PRICE_RETRY_MS : PRICE_TTL_MS;
1321
+ if (!force && now - lastAttempt < wait)
1322
+ return;
1323
+ lastAttempt = now;
1324
+ refreshing = true;
1325
+ (async () => {
1326
+ try {
1327
+ const payload = await ctx.model.list();
1328
+ const models = Array.isArray(payload) ? payload : payload?.data;
1329
+ if (Array.isArray(models) && models.length > 0)
1330
+ table = priceTable(models);
1331
+ } catch {} finally {
1332
+ refreshing = false;
1333
+ }
1334
+ })();
1335
+ }
1336
+ return {
1337
+ price: (ref, tokens) => {
1338
+ refresh();
1339
+ return table === undefined ? undefined : costOf(table, ref, tokens);
1340
+ },
1341
+ refresh
1342
+ };
1343
+ }
1186
1344
  function tryOpen(path) {
1187
1345
  try {
1188
1346
  return openStatsDb(path);
@@ -1202,12 +1360,17 @@ var src_default = Plugin.define({
1202
1360
  try {
1203
1361
  db.exec("PRAGMA busy_timeout = 1000");
1204
1362
  } catch {}
1205
- const recorder = createRecorder(db);
1363
+ const pricing = options.pricing !== "off";
1364
+ const source = pricing ? createPriceSource(ctx) : undefined;
1365
+ source?.refresh(true);
1366
+ const recorder = createRecorder(db, source === undefined ? undefined : { price: source.price });
1206
1367
  const abort = new AbortController;
1207
1368
  const stream = (async () => {
1208
1369
  try {
1209
1370
  for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
1210
1371
  try {
1372
+ if (event.type === "model.updated")
1373
+ source?.refresh(true);
1211
1374
  recorder.handleEvent(event);
1212
1375
  } catch {}
1213
1376
  }
@@ -1224,4 +1387,4 @@ export {
1224
1387
  src_default as default
1225
1388
  };
1226
1389
 
1227
- //# debugId=CB2A8AAFDC0E182864756E2164756E21
1390
+ //# debugId=453796543F95785064756E2164756E21