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/tui.js CHANGED
@@ -42,7 +42,7 @@ function tokenCounts(message) {
42
42
  };
43
43
  }
44
44
  function totalize(steps) {
45
- const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, steps: steps.length };
45
+ const totals = { input: 0, cached: 0, output: 0, reasoning: 0, cacheWrite: 0, cost: 0, listCost: 0, steps: steps.length };
46
46
  for (const step of steps) {
47
47
  const counts = tokenCounts(step);
48
48
  totals.input += counts.input;
@@ -51,6 +51,7 @@ function totalize(steps) {
51
51
  totals.reasoning += counts.reasoning;
52
52
  totals.cacheWrite += counts.write;
53
53
  totals.cost += step.cost ?? 0;
54
+ totals.listCost += step.listCost ?? 0;
54
55
  }
55
56
  return totals;
56
57
  }
@@ -181,6 +182,7 @@ var DEFAULT_LABELS = {
181
182
  output: "out",
182
183
  reasoning: "reason",
183
184
  cost: "cost",
185
+ estimate: "\u2248",
184
186
  cacheExpired: "cache expired",
185
187
  providerChanged: "changed",
186
188
  modelChanged: "model changed"
@@ -239,6 +241,20 @@ function formatCost(value) {
239
241
  return `$${value.toFixed(4)}`;
240
242
  return `$${value.toFixed(2)}`;
241
243
  }
244
+ function formatMoney(charged, estimated, marker = "\u2248") {
245
+ const paid = Number.isFinite(charged) && charged > 0 ? formatCost(charged) : undefined;
246
+ const estimate = Number.isFinite(estimated) && estimated > 0 ? `${marker.trim() === "" ? "" : `${marker.trim()} `}${formatCost(estimated)}` : undefined;
247
+ if (paid !== undefined && estimate !== undefined)
248
+ return `${paid} + ${estimate}`;
249
+ return paid ?? estimate;
250
+ }
251
+ function formatSpend(charged, estimated, marker = "\u2248") {
252
+ const paid = Number.isFinite(charged) ? Math.max(0, charged) : 0;
253
+ const estimate = Number.isFinite(estimated) ? Math.max(0, estimated) : 0;
254
+ if (estimate > 0)
255
+ return `${marker.trim()}${formatCost(paid + estimate)}`;
256
+ return formatCost(paid);
257
+ }
242
258
  function displayTotals(totals) {
243
259
  const prompt = totals.input + totals.cached + totals.cacheWrite;
244
260
  return {
@@ -248,11 +264,12 @@ function displayTotals(totals) {
248
264
  output: totals.output + totals.reasoning,
249
265
  reasoning: totals.reasoning,
250
266
  cost: totals.cost,
267
+ listCost: totals.listCost,
251
268
  steps: totals.steps,
252
269
  prompt
253
270
  };
254
271
  }
255
- function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost) {
272
+ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
256
273
  const display = displayTotals(totals);
257
274
  const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
258
275
  const parts = [
@@ -262,8 +279,9 @@ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals
262
279
  ];
263
280
  if (fields.reasoning)
264
281
  parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
265
- if (fields.cost && cost > 0)
266
- parts.push(`${labels.cost} ${formatCost(cost)}`);
282
+ const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
283
+ if (money !== undefined)
284
+ parts.push(`${labels.cost} ${money}`);
267
285
  const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
268
286
  const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
269
287
  const numbers = parts.join(", ");
@@ -275,6 +293,7 @@ function formatLineSegments(stats, options) {
275
293
  const labels = { ...DEFAULT_LABELS, ...options?.labels };
276
294
  const fields = { ...DEFAULT_FIELDS, ...options?.fields };
277
295
  const turnTotals = options?.turnTotals ?? "latest";
296
+ const estimates = options?.estimates !== false;
278
297
  const segments = [];
279
298
  if (fields.clock && stats.endAt !== undefined) {
280
299
  segments.push({ text: formatClock(stats.endAt), tone: "muted" });
@@ -297,12 +316,15 @@ function formatLineSegments(stats, options) {
297
316
  if (fields.turn && stats.totals.steps > 0) {
298
317
  const totals = turnTotals === "sum" ? stats.totals : stats.latest;
299
318
  segments.push({
300
- text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost),
319
+ text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
301
320
  tone: "base"
302
321
  });
303
322
  }
304
323
  if (fields.session && stats.session) {
305
- segments.push({ text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost), tone: "muted" });
324
+ segments.push({
325
+ text: totalsText(labels.session, stats.session, labels, fields, 0, stats.session.cost, stats.session.listCost, estimates),
326
+ tone: "muted"
327
+ });
306
328
  }
307
329
  if (fields.cacheExpiry && stats.cacheExpired) {
308
330
  const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
@@ -339,7 +361,7 @@ function isToken(value, limit = 64) {
339
361
  }
340
362
 
341
363
  // src/line.ts
342
- function toTranscript(messages) {
364
+ function toTranscript(messages, price) {
343
365
  const transcript = [];
344
366
  for (const message of messages) {
345
367
  if (typeof message.id !== "string" || typeof message.type !== "string")
@@ -348,20 +370,34 @@ function toTranscript(messages) {
348
370
  transcript.push({ type: message.type, id: message.id, time: message.time });
349
371
  continue;
350
372
  }
373
+ const model = toModelRef(message.model);
374
+ let listCost = message.listCost;
375
+ if (listCost === undefined && price !== undefined && model !== undefined && (message.cost === undefined || message.cost <= 0)) {
376
+ const estimate = price({ providerID: model.providerID, modelID: model.id }, {
377
+ input: message.tokens?.input,
378
+ output: message.tokens?.output,
379
+ reasoning: message.tokens?.reasoning,
380
+ cacheRead: message.tokens?.cache?.read,
381
+ cacheWrite: message.tokens?.cache?.write
382
+ });
383
+ if (estimate !== undefined && Number.isFinite(estimate) && estimate > 0)
384
+ listCost = estimate;
385
+ }
351
386
  transcript.push({
352
387
  type: "assistant",
353
388
  id: message.id,
354
389
  time: message.time,
355
- model: toModelRef(message.model),
390
+ model,
356
391
  tokens: message.tokens,
357
392
  cost: message.cost,
393
+ ...listCost !== undefined ? { listCost } : {},
358
394
  finish: message.finish ?? undefined,
359
395
  rawFinish: message.rawFinish ?? undefined
360
396
  });
361
397
  }
362
398
  return transcript;
363
399
  }
364
- function toTranscriptTail(messages, segments = 2) {
400
+ function toTranscriptTail(messages, segments = 2, price) {
365
401
  const wanted = Math.max(2, segments);
366
402
  const tail = [];
367
403
  let collected = 0;
@@ -384,7 +420,7 @@ function toTranscriptTail(messages, segments = 2) {
384
420
  break;
385
421
  }
386
422
  tail.reverse();
387
- return toTranscript(tail);
423
+ return toTranscript(tail, price);
388
424
  }
389
425
  function toModelRef(model) {
390
426
  if (model === undefined || model.providerID === undefined || model.id === undefined)
@@ -393,7 +429,7 @@ function toModelRef(model) {
393
429
  return { providerID: model.providerID, id: model.id };
394
430
  return { providerID: model.providerID, id: model.id, variant: model.variant };
395
431
  }
396
- function sessionTotals(info) {
432
+ function sessionTotals(info, listCost = 0) {
397
433
  if (info === undefined)
398
434
  return;
399
435
  const tokens = info.tokens;
@@ -404,6 +440,7 @@ function sessionTotals(info) {
404
440
  reasoning: tokens?.reasoning ?? 0,
405
441
  cacheWrite: tokens?.cache?.write ?? 0,
406
442
  cost: info.cost ?? 0,
443
+ listCost,
407
444
  steps: 0
408
445
  };
409
446
  }
@@ -426,6 +463,13 @@ function lineText(parts) {
426
463
  // src/stats/queries.ts
427
464
  var COMPACTION_KIND = "compaction";
428
465
  var DEFAULT_TTL_HINT_MS = 10 * 60 * 1000;
466
+ function spend(usage) {
467
+ return usage.cost + usage.listCost;
468
+ }
469
+ function sessionListCost(db, sessionID) {
470
+ const row = db.query("SELECT COALESCE(SUM(list_cost), 0) AS listCost FROM steps WHERE session_id = ?").get(sessionID);
471
+ return row?.listCost ?? 0;
472
+ }
429
473
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
430
474
  var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
431
475
  function modelKey(modelID, variant) {
@@ -440,7 +484,8 @@ var USAGE_SELECT = `COUNT(*) AS steps,
440
484
  COALESCE(SUM(cache_write), 0) AS cacheWrite,
441
485
  COALESCE(SUM(output_tokens), 0) AS output,
442
486
  COALESCE(SUM(reasoning_tokens), 0) AS reasoning,
443
- COALESCE(SUM(cost), 0) AS cost`;
487
+ COALESCE(SUM(cost), 0) AS cost,
488
+ COALESCE(SUM(list_cost), 0) AS listCost`;
444
489
  function usageFrom(row) {
445
490
  return {
446
491
  steps: row.steps ?? 0,
@@ -449,7 +494,8 @@ function usageFrom(row) {
449
494
  cacheWrite: row.cacheWrite ?? 0,
450
495
  output: row.output ?? 0,
451
496
  reasoning: row.reasoning ?? 0,
452
- cost: row.cost ?? 0
497
+ cost: row.cost ?? 0,
498
+ listCost: row.listCost ?? 0
453
499
  };
454
500
  }
455
501
  function rangeWhere(range, column = STEP_TIME) {
@@ -502,7 +548,7 @@ function overview(db, range, filters) {
502
548
  FROM steps ${steps.where}`).get(...steps.params);
503
549
  const prompts = rangeWhere(range, "created_at");
504
550
  const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${prompts.where}`).get(...prompts.params);
505
- const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 });
551
+ const usage = usageFrom(row ?? { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
506
552
  return {
507
553
  ...usage,
508
554
  sessions: row?.sessions ?? 0,
@@ -544,7 +590,7 @@ function models(db, range, filters) {
544
590
  return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
545
591
  }
546
592
  function emptyUsage() {
547
- return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 };
593
+ return { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
548
594
  }
549
595
  function addUsage(target, source) {
550
596
  target.steps += source.steps;
@@ -554,6 +600,7 @@ function addUsage(target, source) {
554
600
  target.output += source.output;
555
601
  target.reasoning += source.reasoning;
556
602
  target.cost += source.cost;
603
+ target.listCost += source.listCost;
557
604
  }
558
605
  function billedTokens(usage) {
559
606
  return usage.input + usage.cached + usage.output;
@@ -598,6 +645,7 @@ function sessions(db, options) {
598
645
  COALESCE(SUM(st.output_tokens), 0) AS output,
599
646
  COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,
600
647
  COALESCE(SUM(st.cost), 0) AS cost,
648
+ COALESCE(SUM(st.list_cost), 0) AS listCost,
601
649
  MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,
602
650
  MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at
603
651
  FROM steps st
@@ -640,7 +688,8 @@ function stepUsage(row) {
640
688
  cacheWrite: row.cache_write ?? 0,
641
689
  output: row.output_tokens ?? 0,
642
690
  reasoning: row.reasoning_tokens ?? 0,
643
- cost: row.cost ?? 0
691
+ cost: row.cost ?? 0,
692
+ listCost: row.list_cost ?? 0
644
693
  };
645
694
  }
646
695
  function stepMessage(row) {
@@ -673,7 +722,7 @@ function turns(db, options) {
673
722
  params.push(floor);
674
723
  }
675
724
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
676
- input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost,
725
+ input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
677
726
  created_at, streamed_at, recorded_at, completed_at, finish
678
727
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
679
728
  ORDER BY session_id, ${STEP_TIME}`).all(...params);
@@ -979,6 +1028,7 @@ function usageBuckets(usage) {
979
1028
  output: usage.output + usage.reasoning,
980
1029
  reasoning: usage.reasoning,
981
1030
  cost: usage.cost,
1031
+ listCost: usage.listCost ?? 0,
982
1032
  hit: prompt > 0 ? usage.cached / prompt : undefined
983
1033
  };
984
1034
  }
@@ -995,7 +1045,7 @@ function viewBar(view, width = 200) {
995
1045
  }
996
1046
  function keysFor(of) {
997
1047
  if (of === "db")
998
- return "\u2191\u2193 pick a retention \xB7 enter prune (asks first) \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
1048
+ return "\u2191\u2193 pick a retention \xB7 enter prune \xB7 e backfill estimates \xB7 v vacuum \xB7 r refresh \xB7 1-9 view \xB7 ? help";
999
1049
  if (of === "periods")
1000
1050
  return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1001
1051
  if (of === "turns")
@@ -1024,6 +1074,7 @@ function helpLines(width) {
1024
1074
  { text: " a turns scope: this session \u2194 all sessions" },
1025
1075
  { text: " m p filter by model / provider (x clears)" },
1026
1076
  { text: " r re-read the database \xB7 f full screen \xB7 escape close" },
1077
+ { text: " e db: backfill list-price estimates for the $0 steps" },
1027
1078
  { text: "" },
1028
1079
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
1029
1080
  { text: " prompt everything the provider saw: cached + fresh + writes" },
@@ -1035,6 +1086,8 @@ function helpLines(width) {
1035
1086
  { text: " out everything generated: visible output + reasoning" },
1036
1087
  { text: " reasoning part of `out`" },
1037
1088
  { text: " cost money, not tokens: a turn sums every step; $0 is left out" },
1089
+ { text: " \u2248 list-price estimate for steps the host reported as $0;" },
1090
+ { text: " `$0.12 + \u2248 $3.40` keeps charged and estimated money apart" },
1038
1091
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
1039
1092
  { text: " tps out / streaming seconds, shown as p50" },
1040
1093
  { text: " switches how often a step's model or provider differs from the step" },
@@ -1050,12 +1103,12 @@ function helpLines(width) {
1050
1103
  { text: "database", tone: HEADER_TONE },
1051
1104
  { text: " the db view shows where the file lives, what it holds and how much" },
1052
1105
  { text: " of it is old: \u2191\u2193 pick a retention, enter prunes from its cutoff date," },
1053
- { text: " v gives the space back" },
1106
+ { text: " e backfills list estimates, v gives the space back" },
1054
1107
  { text: " local time \xB7 SQLite in the OpenCode state directory" }
1055
1108
  ];
1056
1109
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1057
1110
  }
1058
- function usagePairs(usage) {
1111
+ function usagePairs(usage, estimates = true) {
1059
1112
  if (usage === undefined)
1060
1113
  return [];
1061
1114
  const buckets = usageBuckets(usage);
@@ -1070,18 +1123,19 @@ function usagePairs(usage) {
1070
1123
  ];
1071
1124
  if (buckets.reasoning > 0)
1072
1125
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
1073
- pairs.push(["cost", formatCost(buckets.cost)]);
1126
+ pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
1074
1127
  if ("tps" in usage && usage.tps !== undefined)
1075
1128
  pairs.push(["tps", formatTps(usage.tps)]);
1076
1129
  return pairs;
1077
1130
  }
1078
1131
  function overviewLines(data, width) {
1079
1132
  const lines = [];
1133
+ const estimates = data.estimates !== false;
1080
1134
  lines.push({
1081
1135
  text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
1082
1136
  tone: "muted"
1083
1137
  });
1084
- lines.push(...kvGrid(buildOverviewPairs(data.usage, "all"), width));
1138
+ lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
1085
1139
  if (data.activity !== undefined && data.activity.length > 1) {
1086
1140
  const series = reduceSeries(data.activity);
1087
1141
  lines.push({ text: "", tone: "muted" });
@@ -1090,12 +1144,13 @@ function overviewLines(data, width) {
1090
1144
  if (data.session !== undefined) {
1091
1145
  lines.push({ text: "", tone: "muted" });
1092
1146
  lines.push({ text: "this session", tone: HEADER_TONE });
1093
- lines.push(...kvGrid(buildOverviewPairs(data.session, "session"), width));
1147
+ lines.push(...kvGrid(buildOverviewPairs(data.session, "session", estimates), width));
1094
1148
  if (data.subagents !== undefined && data.subagents.length > 0) {
1095
1149
  const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0);
1096
1150
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
1151
+ const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
1097
1152
  lines.push({
1098
- text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatCost(cost)} (their own sessions)`,
1153
+ text: ` subagents ${count(data.subagents.length, "session")} \xB7 ${count(steps, "step")} \xB7 ${formatSpend(cost, estimates ? listCost : 0)} (their own sessions)`,
1099
1154
  tone: "muted"
1100
1155
  });
1101
1156
  }
@@ -1107,8 +1162,8 @@ function overviewLines(data, width) {
1107
1162
  }
1108
1163
  return lines;
1109
1164
  }
1110
- function buildOverviewPairs(usage, scope) {
1111
- const pairs = usagePairs(usage);
1165
+ function buildOverviewPairs(usage, scope, estimates = true) {
1166
+ const pairs = usagePairs(usage, estimates);
1112
1167
  if (scope === "all") {
1113
1168
  pairs.push(["first", usage.firstAt === undefined ? "\u2013" : new Date(usage.firstAt).toLocaleString("en-GB")]);
1114
1169
  pairs.push(["last", usage.lastAt === undefined ? "\u2013" : new Date(usage.lastAt).toLocaleString("en-GB")]);
@@ -1142,7 +1197,7 @@ function modelColumns(width) {
1142
1197
  }
1143
1198
  return layouts[layouts.length - 1];
1144
1199
  }
1145
- function modelsLines(rows, width, extras, limit = 40) {
1200
+ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
1146
1201
  const columns = modelColumns(width);
1147
1202
  const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
1148
1203
  const aligns = ["left", "right", "right", "right"];
@@ -1178,7 +1233,7 @@ function modelsLines(rows, width, extras, limit = 40) {
1178
1233
  cells.push(formatPercent(cache?.hit ?? buckets.hit));
1179
1234
  cells.push(formatTokens(buckets.output));
1180
1235
  if (columns.cost > 0)
1181
- cells.push(formatCost(buckets.cost));
1236
+ cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
1182
1237
  if (columns.spread > 0)
1183
1238
  cells.push(providers.join(", "));
1184
1239
  lines.push({
@@ -1239,7 +1294,7 @@ function renderTable(rows, columns, width, options) {
1239
1294
  lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
1240
1295
  return lines;
1241
1296
  }
1242
- function providerSummaryLines(rows, width, limit = 40) {
1297
+ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
1243
1298
  const lines = renderTable(rows, [
1244
1299
  { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
1245
1300
  { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
@@ -1250,7 +1305,7 @@ function providerSummaryLines(rows, width, limit = 40) {
1250
1305
  { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1251
1306
  { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1252
1307
  { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1253
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatCost(row.usage.cost) }
1308
+ { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1254
1309
  ], width, {
1255
1310
  limit,
1256
1311
  empty: "no usage recorded for this range",
@@ -1259,7 +1314,7 @@ function providerSummaryLines(rows, width, limit = 40) {
1259
1314
  });
1260
1315
  return lines;
1261
1316
  }
1262
- function providerLines(rows, width, limit = 40) {
1317
+ function providerLines(rows, width, limit = 40, estimates = true) {
1263
1318
  return renderTable(rows, [
1264
1319
  { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
1265
1320
  { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
@@ -1270,7 +1325,7 @@ function providerLines(rows, width, limit = 40) {
1270
1325
  { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1271
1326
  { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1272
1327
  { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1273
- { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatCost(row.usage.cost) }
1328
+ { header: "cost", width: 9, align: "right", optional: true, cell: (row) => formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0) }
1274
1329
  ], width, {
1275
1330
  limit,
1276
1331
  empty: "no usage recorded for this range",
@@ -1358,7 +1413,7 @@ function cacheLines(data, width) {
1358
1413
  }
1359
1414
  return lines;
1360
1415
  }
1361
- function periodLines(rows, width, granularity, limit = 40) {
1416
+ function periodLines(rows, width, granularity, limit = 40, estimates = true) {
1362
1417
  const lines = [];
1363
1418
  const totals = rows.reduce((sum, row) => {
1364
1419
  sum.steps += row.usage.steps;
@@ -1369,8 +1424,9 @@ function periodLines(rows, width, granularity, limit = 40) {
1369
1424
  sum.output += row.usage.output;
1370
1425
  sum.reasoning += row.usage.reasoning;
1371
1426
  sum.cost += row.usage.cost;
1427
+ sum.listCost += row.usage.listCost;
1372
1428
  return sum;
1373
- }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 });
1429
+ }, { steps: 0, sessions: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 });
1374
1430
  const overall = usageBuckets(totals);
1375
1431
  lines.push({
1376
1432
  text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
@@ -1379,7 +1435,10 @@ function periodLines(rows, width, granularity, limit = 40) {
1379
1435
  if (rows.length > 1) {
1380
1436
  lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
1381
1437
  lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
1382
- lines.push({ text: `cost ${sparkline(rows.map((row) => Math.round(row.usage.cost * 1e4)))}`, tone: "muted" });
1438
+ lines.push({
1439
+ text: `cost ${sparkline(rows.map((row) => Math.round((estimates ? row.usage.cost + row.usage.listCost : row.usage.cost) * 1e4)))}`,
1440
+ tone: "muted"
1441
+ });
1383
1442
  }
1384
1443
  const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
1385
1444
  const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
@@ -1397,7 +1456,7 @@ function periodLines(rows, width, granularity, limit = 40) {
1397
1456
  formatTokens(buckets.cached),
1398
1457
  formatPercent(buckets.hit, 0),
1399
1458
  formatTokens(buckets.output),
1400
- formatCost(buckets.cost)
1459
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1401
1460
  ];
1402
1461
  lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
1403
1462
  }
@@ -1411,7 +1470,7 @@ function periodLines(rows, width, granularity, limit = 40) {
1411
1470
  formatTokens(overall.cached),
1412
1471
  formatPercent(overall.hit, 0),
1413
1472
  formatTokens(overall.output),
1414
- formatCost(overall.cost)
1473
+ formatSpend(overall.cost, estimates ? overall.listCost : 0)
1415
1474
  ], widths, aligns),
1416
1475
  tone: HEADER_TONE
1417
1476
  });
@@ -1419,7 +1478,7 @@ function periodLines(rows, width, granularity, limit = 40) {
1419
1478
  lines.push({ text: "no usage recorded for this range", tone: "muted" });
1420
1479
  return lines;
1421
1480
  }
1422
- function latencyLines(report, width, groups, limit = 12) {
1481
+ function latencyLines(report, width, groups, limit = 12, estimates = true) {
1423
1482
  const lines = [];
1424
1483
  lines.push({
1425
1484
  text: formatTableRow(["wall", "p50", formatMs(report.wall.p50), "p90", formatMs(report.wall.p90), "p99", formatMs(report.wall.p99), `n ${formatCount(report.wall.count)}`], [10, 4, 9, 4, 9, 4, 9, 12]),
@@ -1449,7 +1508,16 @@ function latencyLines(report, width, groups, limit = 12) {
1449
1508
  for (const row of groups.slice(0, limit)) {
1450
1509
  const thin = row.count < 5;
1451
1510
  lines.push({
1452
- text: formatTableRow([row.label, formatCount(row.count), formatMs(row.wall.p50), formatMs(row.wall.p90), formatMs(row.stream.p50), formatTps(row.tps.p50), formatTps(row.tps.p90), formatCost(row.usage.cost)], widths, aligns),
1511
+ text: formatTableRow([
1512
+ row.label,
1513
+ formatCount(row.count),
1514
+ formatMs(row.wall.p50),
1515
+ formatMs(row.wall.p90),
1516
+ formatMs(row.stream.p50),
1517
+ formatTps(row.tps.p50),
1518
+ formatTps(row.tps.p90),
1519
+ formatSpend(row.usage.cost, estimates ? row.usage.listCost : 0)
1520
+ ], widths, aligns),
1453
1521
  tone: thin ? "muted" : "base",
1454
1522
  row: { kind: "model", value: row.key }
1455
1523
  });
@@ -1460,6 +1528,7 @@ function latencyLines(report, width, groups, limit = 12) {
1460
1528
  }
1461
1529
  function sessionsLines(rows, width, options) {
1462
1530
  const limit = options?.limit ?? 20;
1531
+ const estimates = options?.estimates !== false;
1463
1532
  const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
1464
1533
  const aligns = ["left", "right", "right", "right", "right", "right", "right"];
1465
1534
  const lines = [
@@ -1481,7 +1550,7 @@ function sessionsLines(rows, width, options) {
1481
1550
  formatTokens(buckets.cached),
1482
1551
  formatPercent(buckets.hit, 0),
1483
1552
  formatTokens(buckets.output),
1484
- formatCost(buckets.cost)
1553
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1485
1554
  ], widths, aligns),
1486
1555
  tone: child ? "muted" : "base",
1487
1556
  row: { kind: "session", value: row.sessionID }
@@ -1493,7 +1562,7 @@ function sessionsLines(rows, width, options) {
1493
1562
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
1494
1563
  lines.push({ text: "", tone: "muted" });
1495
1564
  lines.push({
1496
- text: `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${formatCost(options.rollup.subagentCost)}`,
1565
+ text: `subagents ${formatCount(options.rollup.subagentSteps)} steps (${formatPercent(share > 0 ? options.rollup.subagentSteps / share : undefined)}) \xB7 ${formatSpend(options.rollup.subagentCost, estimates ? options.rollup.subagentListCost ?? 0 : 0)}`,
1497
1566
  tone: "muted"
1498
1567
  });
1499
1568
  }
@@ -1523,6 +1592,12 @@ function dbLines(data, width) {
1523
1592
  lines.push({ text: "", tone: "muted" });
1524
1593
  lines.push({ text: "clean up", tone: HEADER_TONE });
1525
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" });
1595
+ if (data.estimates !== false) {
1596
+ lines.push({
1597
+ text: truncate(data.info.schemaVersion < 10 ? " list estimates the recorder must upgrade this database first" : data.info.unpriced === 0 ? " list estimates every $0 step has a price" : ` list estimates ${formatCount(data.info.unpriced)} $0 steps without a known price \xB7 e retries`, width),
1598
+ tone: data.info.schemaVersion < 10 || data.info.unpriced > 0 ? "base" : "muted"
1599
+ });
1600
+ }
1526
1601
  const widths = [10, 13, 10];
1527
1602
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
1528
1603
  for (const option of data.info.removable) {
@@ -1583,7 +1658,7 @@ function turnsLines(rows, width, options) {
1583
1658
  lines.push({ text: "no finished turns for this range", tone: "muted" });
1584
1659
  return lines;
1585
1660
  }
1586
- function sessionSummaryLines(usage, budget = 34) {
1661
+ function sessionSummaryLines(usage, budget = 34, estimates = true) {
1587
1662
  const buckets = usageBuckets(usage);
1588
1663
  const steps = formatCount(buckets.steps);
1589
1664
  const input = formatTokens(buckets.input);
@@ -1591,7 +1666,7 @@ function sessionSummaryLines(usage, budget = 34) {
1591
1666
  const out = formatTokens(buckets.output);
1592
1667
  const hit = formatPercent(buckets.hit);
1593
1668
  const tps = formatTpsCompact(usage.tps);
1594
- const cost = formatCost(buckets.cost);
1669
+ const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
1595
1670
  const first = [
1596
1671
  ` ${steps} steps \xB7 in ${input}`,
1597
1672
  ` ${steps} steps`
@@ -1624,7 +1699,7 @@ function sidebarLines(rows, options) {
1624
1699
  const input = formatTokens(display.input);
1625
1700
  const prompt = formatTokens(display.prompt);
1626
1701
  const output = formatTokens(display.output);
1627
- const cost = formatCost(turn.totals.cost);
1702
+ const cost = options?.estimates === false ? formatCost(turn.totals.cost) : formatMoney(turn.totals.cost, turn.totals.listCost) ?? formatCost(turn.totals.cost);
1628
1703
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
1629
1704
  const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
1630
1705
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
@@ -1696,6 +1771,7 @@ var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_i
1696
1771
  model_id AS modelID, variant,
1697
1772
  COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1698
1773
  COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, COALESCE(cost, 0) AS cost,
1774
+ COALESCE(list_cost, 0) AS listCost,
1699
1775
  created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1700
1776
  var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
1701
1777
  var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
@@ -1755,7 +1831,7 @@ function pairsOf(rows) {
1755
1831
  return pairs;
1756
1832
  }
1757
1833
  function usageOf(steps) {
1758
- const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0 };
1834
+ const usage = { steps: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0, cost: 0, listCost: 0 };
1759
1835
  for (const step of steps) {
1760
1836
  usage.steps += 1;
1761
1837
  usage.input += step.input;
@@ -1764,6 +1840,7 @@ function usageOf(steps) {
1764
1840
  usage.output += step.output;
1765
1841
  usage.reasoning += step.reasoning;
1766
1842
  usage.cost += step.cost;
1843
+ usage.listCost += step.listCost;
1767
1844
  }
1768
1845
  return usage;
1769
1846
  }
@@ -2188,11 +2265,12 @@ function buildPanel(request) {
2188
2265
  }
2189
2266
  function build(request) {
2190
2267
  const { db, view, now, sessionStart, width } = request;
2268
+ const estimates = request.estimates !== false;
2191
2269
  const scoped = request.range === "session" && request.sessionID !== "";
2192
2270
  const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
2193
2271
  const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
2194
2272
  if (request.detail !== undefined)
2195
- return buildDetail(request, range, filters);
2273
+ return buildDetail(request, range, filters, estimates);
2196
2274
  switch (view) {
2197
2275
  case "overview": {
2198
2276
  const usage = overview(db, range, filters);
@@ -2205,20 +2283,21 @@ function build(request) {
2205
2283
  ...children.length > 0 ? { subagents: children } : {},
2206
2284
  range: request.range,
2207
2285
  activity: activityOf(db, range, now),
2208
- coverage: coverageOf(db, { range, filters })
2286
+ coverage: coverageOf(db, { range, filters }),
2287
+ estimates
2209
2288
  }, width);
2210
2289
  }
2211
2290
  case "models": {
2212
- const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc);
2291
+ const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
2213
2292
  const pairs = cachePairs(db, { range, filters });
2214
2293
  const switches = switchesOf(pairs);
2215
2294
  return modelsLines(rows, width, {
2216
2295
  cache: cacheByModel(pairs),
2217
2296
  switches: switchesByModel(switches.rows)
2218
- }, 40);
2297
+ }, 40, estimates);
2219
2298
  }
2220
2299
  case "providers":
2221
- return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc), width, 40);
2300
+ return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
2222
2301
  case "cache": {
2223
2302
  const pairs = cachePairs(db, { range, filters });
2224
2303
  return cacheLines({
@@ -2229,27 +2308,32 @@ function build(request) {
2229
2308
  }, width);
2230
2309
  }
2231
2310
  case "periods":
2232
- return periodLines(periodsOf(stepRows(db, { range, filters }), request.granularity), width, request.granularity, 40);
2311
+ return periodLines(periodsOf(stepRows(db, { range, filters }), request.granularity), width, request.granularity, 40, estimates);
2233
2312
  case "latency": {
2234
2313
  const timings = timingRows(db, { range, filters });
2235
2314
  const by = filters.modelID !== undefined ? "provider" : "model";
2236
- return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14);
2315
+ return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
2237
2316
  }
2238
2317
  case "sessions": {
2239
- const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc);
2318
+ const rows = sortSessions(sessions(db, { range, filters, limit: 200 }), request.sort, request.sortDesc, estimates);
2240
2319
  const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
2241
2320
  return sessionsLines(rows, width, {
2242
2321
  limit: 20,
2243
- rollup: { subagentSteps: child.reduce((sum, row) => sum + row.steps, 0), subagentCost: child.reduce((sum, row) => sum + row.cost, 0) }
2322
+ estimates,
2323
+ rollup: {
2324
+ subagentSteps: child.reduce((sum, row) => sum + row.steps, 0),
2325
+ subagentCost: child.reduce((sum, row) => sum + row.cost, 0),
2326
+ subagentListCost: child.reduce((sum, row) => sum + row.listCost, 0)
2327
+ }
2244
2328
  });
2245
2329
  }
2246
2330
  case "db":
2247
- return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now }, width);
2331
+ return request.database === undefined ? [{ text: "the database location is unavailable to this panel", tone: "warning" }] : dbLines({ info: request.database, busy: request.busy, now, estimates }, width);
2248
2332
  case "turns": {
2249
2333
  const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
2250
- const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc);
2334
+ const rows = sortTurns(turns(db, { sessionID, range, filters, limit: 300 }), request.sort, request.sortDesc, estimates);
2251
2335
  const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
2252
- return turnsLines(rows.slice(0, 60), width, { ...request.format, sessionTitles: titles });
2336
+ return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
2253
2337
  }
2254
2338
  }
2255
2339
  }
@@ -2268,7 +2352,7 @@ function rangeForRequest(key, now) {
2268
2352
  return;
2269
2353
  }
2270
2354
  }
2271
- function buildDetail(request, range, filters) {
2355
+ function buildDetail(request, range, filters, estimates) {
2272
2356
  const row = request.detail;
2273
2357
  const db = request.db;
2274
2358
  const width = request.width;
@@ -2285,16 +2369,16 @@ function buildDetail(request, range, filters) {
2285
2369
  tone: "muted"
2286
2370
  },
2287
2371
  { text: "", tone: "muted" },
2288
- ...providerLines(providerBreakdownOf(steps), width, 40),
2372
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2289
2373
  { text: "", tone: "muted" },
2290
- ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14),
2374
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
2291
2375
  { text: "", tone: "muted" },
2292
2376
  back
2293
2377
  ];
2294
2378
  }
2295
2379
  if (row.kind === "session" || row.kind === "turn") {
2296
2380
  const rows = turns(db, { sessionID: row.value, limit: 80 });
2297
- return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, request.format), { text: "", tone: "muted" }, back];
2381
+ return [head, { text: "", tone: "muted" }, ...turnsLines(rows, width, { ...request.format, estimates }), { text: "", tone: "muted" }, back];
2298
2382
  }
2299
2383
  if (row.kind === "provider") {
2300
2384
  const scoped = { ...filters, provider: row.value };
@@ -2307,9 +2391,9 @@ function buildDetail(request, range, filters) {
2307
2391
  tone: "muted"
2308
2392
  },
2309
2393
  { text: "", tone: "muted" },
2310
- ...providerLines(providerBreakdownOf(steps), width, 40),
2394
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2311
2395
  { text: "", tone: "muted" },
2312
- ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14),
2396
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
2313
2397
  { text: "", tone: "muted" },
2314
2398
  back
2315
2399
  ];
@@ -2321,7 +2405,7 @@ function buildDetail(request, range, filters) {
2321
2405
  head,
2322
2406
  { text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
2323
2407
  { text: "", tone: "muted" },
2324
- ...providerSummaryLines(providerSummaryOf(stepRows(db, { range, filters })), width, 40),
2408
+ ...providerSummaryLines(providerSummaryOf(stepRows(db, { range, filters })), width, 40, estimates),
2325
2409
  { text: "", tone: "muted" },
2326
2410
  back
2327
2411
  ];
@@ -2331,7 +2415,7 @@ function buildDetail(request, range, filters) {
2331
2415
  function percent(value) {
2332
2416
  return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
2333
2417
  }
2334
- function sortModels(rows, sort, desc) {
2418
+ function sortModels(rows, sort, desc, estimates = true) {
2335
2419
  const sign = desc ? -1 : 1;
2336
2420
  const pick = (model) => {
2337
2421
  if (sort === "cached")
@@ -2339,12 +2423,12 @@ function sortModels(rows, sort, desc) {
2339
2423
  if (sort === "out")
2340
2424
  return model.totals.output;
2341
2425
  if (sort === "cost")
2342
- return model.totals.cost;
2426
+ return estimates ? spend(model.totals) : model.totals.cost;
2343
2427
  return model.totals.steps;
2344
2428
  };
2345
2429
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2346
2430
  }
2347
- function sortProviders(rows, sort, desc) {
2431
+ function sortProviders(rows, sort, desc, estimates = true) {
2348
2432
  const sign = desc ? -1 : 1;
2349
2433
  const pick = (row) => {
2350
2434
  if (sort === "cached")
@@ -2352,7 +2436,7 @@ function sortProviders(rows, sort, desc) {
2352
2436
  if (sort === "hit")
2353
2437
  return row.cache.hit ?? -1;
2354
2438
  if (sort === "cost")
2355
- return row.usage.cost;
2439
+ return estimates ? spend(row.usage) : row.usage.cost;
2356
2440
  if (sort === "share")
2357
2441
  return row.share;
2358
2442
  if (sort === "tps")
@@ -2372,7 +2456,7 @@ function sortLatency(rows, sort, desc) {
2372
2456
  };
2373
2457
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2374
2458
  }
2375
- function sortSessions(rows, sort, desc) {
2459
+ function sortSessions(rows, sort, desc, estimates = true) {
2376
2460
  const sign = desc ? -1 : 1;
2377
2461
  const pick = (row) => {
2378
2462
  if (sort === "steps")
@@ -2380,16 +2464,16 @@ function sortSessions(rows, sort, desc) {
2380
2464
  if (sort === "cached")
2381
2465
  return row.cached;
2382
2466
  if (sort === "cost")
2383
- return row.cost;
2467
+ return estimates ? spend(row) : row.cost;
2384
2468
  return row.lastAt ?? 0;
2385
2469
  };
2386
2470
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2387
2471
  }
2388
- function sortTurns(rows, sort, desc) {
2472
+ function sortTurns(rows, sort, desc, estimates = true) {
2389
2473
  const sign = desc ? -1 : 1;
2390
2474
  const pick = (row) => {
2391
2475
  if (sort === "cost")
2392
- return row.totals.cost;
2476
+ return estimates ? spend(row.totals) : row.totals.cost;
2393
2477
  if (sort === "tokens")
2394
2478
  return row.totals.cached + row.totals.input + row.totals.output;
2395
2479
  return row.endAt ?? 0;
@@ -2480,7 +2564,7 @@ function ensureRegularFile(path) {
2480
2564
  }
2481
2565
 
2482
2566
  // src/stats/db.ts
2483
- var SCHEMA_VERSION = 9;
2567
+ var SCHEMA_VERSION = 10;
2484
2568
  var LABEL_LIMIT = 4 * TEXT_LIMIT;
2485
2569
  var SCHEMA = `
2486
2570
  CREATE TABLE IF NOT EXISTS meta (
@@ -2518,6 +2602,7 @@ CREATE TABLE IF NOT EXISTS steps (
2518
2602
  cache_read INTEGER NOT NULL DEFAULT 0,
2519
2603
  cache_write INTEGER NOT NULL DEFAULT 0,
2520
2604
  cost REAL NOT NULL DEFAULT 0,
2605
+ list_cost REAL,
2521
2606
  created_at INTEGER,
2522
2607
  streamed_at INTEGER,
2523
2608
  completed_at INTEGER,
@@ -2579,8 +2664,15 @@ function dropUnused(db) {
2579
2664
  db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
2580
2665
  }
2581
2666
  }
2667
+ function addMissing(db) {
2668
+ const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
2669
+ if (columns.size > 0 && !columns.has("list_cost")) {
2670
+ db.exec("ALTER TABLE steps ADD COLUMN list_cost REAL");
2671
+ }
2672
+ }
2582
2673
  function migrate(db) {
2583
2674
  dropUnused(db);
2675
+ addMissing(db);
2584
2676
  }
2585
2677
  var POSIX = process.platform !== "win32";
2586
2678
  function hardenDirectory(path) {
@@ -2643,11 +2735,11 @@ function openStatsDbWrite(path) {
2643
2735
  function recordStep(db, record) {
2644
2736
  db.query(`INSERT INTO steps (
2645
2737
  message_id, session_id, parent_id, provider_id, model_id, variant,
2646
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost,
2738
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
2647
2739
  created_at, streamed_at, completed_at, finish, recorded_at
2648
2740
  ) VALUES (
2649
2741
  $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
2650
- $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost,
2742
+ $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
2651
2743
  $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
2652
2744
  )
2653
2745
  ON CONFLICT(message_id) DO UPDATE SET
@@ -2662,6 +2754,9 @@ function recordStep(db, record) {
2662
2754
  cache_read = excluded.cache_read,
2663
2755
  cache_write = excluded.cache_write,
2664
2756
  cost = excluded.cost,
2757
+ -- A step that starts being charged loses its estimate; an estimate is
2758
+ -- kept when a replayed event arrives without a price table.
2759
+ list_cost = CASE WHEN excluded.cost > 0 THEN NULL ELSE COALESCE(excluded.list_cost, steps.list_cost) END,
2665
2760
  created_at = COALESCE(excluded.created_at, steps.created_at),
2666
2761
  streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
2667
2762
  completed_at = COALESCE(excluded.completed_at, steps.completed_at),
@@ -2679,6 +2774,7 @@ function recordStep(db, record) {
2679
2774
  $cacheRead: record.cacheRead ?? 0,
2680
2775
  $cacheWrite: record.cacheWrite ?? 0,
2681
2776
  $cost: record.cost ?? 0,
2777
+ $listCost: (record.cost ?? 0) <= 0 && record.listCost !== undefined && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null,
2682
2778
  $createdAt: record.createdAt ?? null,
2683
2779
  $streamedAt: record.streamedAt ?? null,
2684
2780
  $completedAt: record.completedAt ?? null,
@@ -2742,6 +2838,11 @@ function dbInfo(db, path, now = Date.now()) {
2742
2838
  const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
2743
2839
  return {
2744
2840
  path,
2841
+ unpriced: hasListCost(db) ? db.query(`SELECT COUNT(*) AS n FROM steps
2842
+ WHERE cost = 0 AND list_cost IS NULL
2843
+ AND provider_id IS NOT NULL AND provider_id <> ''
2844
+ AND model_id IS NOT NULL AND model_id <> ''
2845
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n : 0,
2745
2846
  bytes: size(path),
2746
2847
  walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
2747
2848
  schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
@@ -2783,6 +2884,61 @@ function vacuum(db, path) {
2783
2884
  const after = footprint(path);
2784
2885
  return { before, after, freed: Math.max(0, before - after) };
2785
2886
  }
2887
+ function hasListCost(db) {
2888
+ try {
2889
+ return db.query("PRAGMA table_info(steps)").all().some((column) => column.name === "list_cost");
2890
+ } catch {
2891
+ return false;
2892
+ }
2893
+ }
2894
+ var BACKFILL_BATCH = 1000;
2895
+ function backfillListCost(db, price) {
2896
+ if (!hasListCost(db))
2897
+ return { candidates: 0, updated: 0 };
2898
+ const candidates = db.query(`SELECT COUNT(*) AS n FROM steps
2899
+ WHERE cost = 0 AND list_cost IS NULL
2900
+ AND provider_id IS NOT NULL AND provider_id <> ''
2901
+ AND model_id IS NOT NULL AND model_id <> ''
2902
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0`).get().n;
2903
+ if (candidates === 0)
2904
+ return { candidates: 0, updated: 0 };
2905
+ const select = db.query(`SELECT rowid, provider_id, model_id,
2906
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write
2907
+ FROM steps
2908
+ WHERE cost = 0 AND list_cost IS NULL AND rowid > ?
2909
+ AND provider_id IS NOT NULL AND provider_id <> ''
2910
+ AND model_id IS NOT NULL AND model_id <> ''
2911
+ AND input_tokens + output_tokens + reasoning_tokens + cache_read + cache_write > 0
2912
+ ORDER BY rowid
2913
+ LIMIT ?`);
2914
+ const update = db.query("UPDATE steps SET list_cost = ? WHERE rowid = ? AND cost = 0 AND list_cost IS NULL");
2915
+ let cursor = 0;
2916
+ let updated = 0;
2917
+ for (;; ) {
2918
+ const rows = select.all(cursor, BACKFILL_BATCH);
2919
+ if (rows.length === 0)
2920
+ break;
2921
+ db.transaction(() => {
2922
+ for (const row of rows) {
2923
+ const estimate = price({ providerID: row.provider_id ?? undefined, modelID: row.model_id ?? undefined }, {
2924
+ input: row.input_tokens ?? 0,
2925
+ output: row.output_tokens ?? 0,
2926
+ reasoning: row.reasoning_tokens ?? 0,
2927
+ cacheRead: row.cache_read ?? 0,
2928
+ cacheWrite: row.cache_write ?? 0
2929
+ });
2930
+ if (estimate === undefined || !Number.isFinite(estimate) || estimate < 0)
2931
+ continue;
2932
+ if (update.run(estimate, row.rowid).changes > 0)
2933
+ updated += 1;
2934
+ }
2935
+ })();
2936
+ cursor = rows[rows.length - 1].rowid;
2937
+ if (rows.length < BACKFILL_BATCH)
2938
+ break;
2939
+ }
2940
+ return { candidates, updated };
2941
+ }
2786
2942
 
2787
2943
  // src/panel.tsx
2788
2944
  function Panel(props) {
@@ -2845,6 +3001,7 @@ function Panel(props) {
2845
3001
  sessionStart: props.deps.sessionStart(props.input.sessionID),
2846
3002
  now: props.deps.now(),
2847
3003
  format: props.format,
3004
+ estimates: props.format?.estimates !== false,
2848
3005
  ...detail() !== undefined ? {
2849
3006
  detail: detail()
2850
3007
  } : {},
@@ -2968,6 +3125,62 @@ function Panel(props) {
2968
3125
  }
2969
3126
  setAnchor(undefined);
2970
3127
  setTick((value) => value + 1);
3128
+ props.deps.bump?.();
3129
+ }
3130
+ async function backfillEstimates() {
3131
+ if (props.format?.estimates === false) {
3132
+ props.ctx.ui.toast.show({
3133
+ message: "list-price estimates are turned off",
3134
+ variant: "warning"
3135
+ });
3136
+ return;
3137
+ }
3138
+ if (sessionRunning()) {
3139
+ props.ctx.ui.toast.show({
3140
+ message: "the session is running: backfill again when it is idle",
3141
+ variant: "warning"
3142
+ });
3143
+ return;
3144
+ }
3145
+ const info = database();
3146
+ if (info !== undefined && info.schemaVersion < 10) {
3147
+ props.ctx.ui.toast.show({
3148
+ message: "the recorder must upgrade the database before estimates can be backfilled",
3149
+ variant: "warning"
3150
+ });
3151
+ return;
3152
+ }
3153
+ const candidates = info?.unpriced ?? 0;
3154
+ if (candidates === 0) {
3155
+ props.ctx.ui.toast.show({
3156
+ message: "every $0 step already has a list estimate"
3157
+ });
3158
+ return;
3159
+ }
3160
+ const confirmed = await props.ctx.ui.dialog.confirm({
3161
+ title: "Backfill list-price estimates",
3162
+ message: `${formatCount(candidates)} steps recorded at $0 have no estimate. Those with a known catalog price will be filled using today's catalog; models the catalog no longer lists stay unknown.`,
3163
+ label: {
3164
+ confirm: "Backfill",
3165
+ cancel: "Cancel"
3166
+ }
3167
+ });
3168
+ if (confirmed !== true)
3169
+ return;
3170
+ const result = props.deps.backfill?.();
3171
+ if (result === undefined) {
3172
+ props.ctx.ui.toast.show({
3173
+ message: "the price catalog is unavailable: try again in a moment",
3174
+ variant: "warning"
3175
+ });
3176
+ } else {
3177
+ props.ctx.ui.toast.show({
3178
+ message: `backfilled ${formatCount(result.updated)} of ${formatCount(result.candidates)} steps`,
3179
+ variant: result.updated === 0 ? "warning" : "success"
3180
+ });
3181
+ }
3182
+ setTick((value) => value + 1);
3183
+ props.deps.bump?.();
2971
3184
  }
2972
3185
  async function compact() {
2973
3186
  if (sessionRunning()) {
@@ -3086,7 +3299,10 @@ function Panel(props) {
3086
3299
  draft.providerID = "";
3087
3300
  });
3088
3301
  setAnchor(undefined);
3089
- }), command("usage-insights.refresh", "Refresh", "r", () => setTick((value) => value + 1)), command("usage-insights.vacuum", "Compact the database", "v", () => void compact()), command("usage-insights.help", "Help", "?", () => setHelp((open) => !open)), command("usage-insights.fullscreen", "Toggle full screen", "f", () => props.input.toggleFullscreen()), command("usage-insights.close", "Close usage panel", "escape", () => props.input.close()), ...PANEL_VIEWS.map((name, index) => command(`usage-insights.view.${name}`, `View ${name}`, String((index + 1) % 10), () => {
3302
+ }), command("usage-insights.refresh", "Refresh", "r", () => setTick((value) => value + 1)), command("usage-insights.backfill", "Backfill list-price estimates", "e", () => {
3303
+ if (view() === "db")
3304
+ backfillEstimates();
3305
+ }), command("usage-insights.vacuum", "Compact the database", "v", () => void compact()), command("usage-insights.help", "Help", "?", () => setHelp((open) => !open)), command("usage-insights.fullscreen", "Toggle full screen", "f", () => props.input.toggleFullscreen()), command("usage-insights.close", "Close usage panel", "escape", () => props.input.close()), ...PANEL_VIEWS.map((name, index) => command(`usage-insights.view.${name}`, `View ${name}`, String((index + 1) % 10), () => {
3090
3306
  setHelp(false);
3091
3307
  props.update((draft) => {
3092
3308
  draft.view = name;
@@ -3189,6 +3405,75 @@ function selectedLineIndex(lines, cursor) {
3189
3405
  return -1;
3190
3406
  }
3191
3407
 
3408
+ // src/pricing.ts
3409
+ function money(value) {
3410
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
3411
+ }
3412
+ function tokens(value) {
3413
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
3414
+ }
3415
+ function priceTable(models) {
3416
+ const table = new Map;
3417
+ if (!Array.isArray(models))
3418
+ return table;
3419
+ for (const model of models) {
3420
+ if (model === null || model === undefined)
3421
+ continue;
3422
+ const providerID = model.providerID;
3423
+ const modelID = model.modelID ?? model.id;
3424
+ if (typeof providerID !== "string" || providerID === "")
3425
+ continue;
3426
+ if (typeof modelID !== "string" || modelID === "")
3427
+ continue;
3428
+ if (!Array.isArray(model.cost) || model.cost.length === 0)
3429
+ continue;
3430
+ const tiers = [];
3431
+ for (const cost of model.cost) {
3432
+ if (cost === null || cost === undefined)
3433
+ 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;
3436
+ tiers.push({
3437
+ ...tier !== undefined ? { tier } : {},
3438
+ input: money(cost.input),
3439
+ output: money(cost.output),
3440
+ cacheRead: money(cost.cache?.read),
3441
+ cacheWrite: money(cost.cache?.write)
3442
+ });
3443
+ }
3444
+ if (tiers.length > 0)
3445
+ table.set(`${providerID}/${modelID}`, { tiers });
3446
+ }
3447
+ return table;
3448
+ }
3449
+ function priceOf(table, ref) {
3450
+ if (ref.providerID === undefined || ref.providerID === "")
3451
+ return;
3452
+ if (ref.modelID === undefined || ref.modelID === "")
3453
+ return;
3454
+ return table.get(`${ref.providerID}/${ref.modelID}`);
3455
+ }
3456
+ function costOf(table, ref, usage) {
3457
+ const price = priceOf(table, ref);
3458
+ if (price === undefined)
3459
+ return;
3460
+ const input = tokens(usage.input);
3461
+ const output = tokens(usage.output);
3462
+ const reasoning = tokens(usage.reasoning);
3463
+ const cacheRead = tokens(usage.cacheRead);
3464
+ const cacheWrite = tokens(usage.cacheWrite);
3465
+ const prompt = input + cacheRead + cacheWrite;
3466
+ 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);
3467
+ if (selected === undefined)
3468
+ return;
3469
+ if (selected.input === 0 && selected.output === 0 && selected.cacheRead === 0 && selected.cacheWrite === 0)
3470
+ return 0;
3471
+ const billed = input * selected.input + (output + reasoning) * selected.output + cacheRead * selected.cacheRead + cacheWrite * selected.cacheWrite;
3472
+ if (!Number.isFinite(billed) || billed <= 0)
3473
+ return;
3474
+ return billed / 1e6;
3475
+ }
3476
+
3192
3477
  // src/sidebar.tsx
3193
3478
  import { effect as _$effect2 } from "@opentui/solid";
3194
3479
  import { insert as _$insert2 } from "@opentui/solid";
@@ -3218,7 +3503,7 @@ function TurnsSidebar(props) {
3218
3503
  try {
3219
3504
  const summary = sessionSummaryLines(overview(db, undefined, {
3220
3505
  sessionID: props.sessionID
3221
- }), budget);
3506
+ }), budget, props.options?.estimates !== false);
3222
3507
  const history = sidebarLines(turns(db, {
3223
3508
  sessionID: props.sessionID,
3224
3509
  limit: props.deps.limit
@@ -3269,6 +3554,31 @@ var tui_default = Plugin.define({
3269
3554
  if (options.enabled === false)
3270
3555
  return;
3271
3556
  const panelEnabled = options.panel !== false;
3557
+ const pricing = options.pricing !== "off";
3558
+ const PRICE_TTL_MS = 5 * 60 * 1000;
3559
+ let priceCache;
3560
+ function priceTableFor() {
3561
+ if (!pricing)
3562
+ return;
3563
+ const now = Date.now();
3564
+ if (priceCache !== undefined && now - priceCache.at < PRICE_TTL_MS)
3565
+ return priceCache.table;
3566
+ try {
3567
+ const models = ctx.data.location?.model?.list(ctx.location);
3568
+ if (models !== undefined && models.length > 0) {
3569
+ priceCache = {
3570
+ table: priceTable(models),
3571
+ at: now
3572
+ };
3573
+ return priceCache.table;
3574
+ }
3575
+ } catch {}
3576
+ return priceCache?.table;
3577
+ }
3578
+ function priceFor() {
3579
+ const table = priceTableFor();
3580
+ return table === undefined ? undefined : (ref, tokens) => costOf(table, ref, tokens);
3581
+ }
3272
3582
  const [settings, updateSettings] = ctx.storage.store("panel", {
3273
3583
  initial: DEFAULT_SETTINGS
3274
3584
  });
@@ -3280,7 +3590,9 @@ var tui_default = Plugin.define({
3280
3590
  let databaseFailed = false;
3281
3591
  let refreshTimer;
3282
3592
  let lastRefresh = 0;
3593
+ const sessionCostCache = new Map;
3283
3594
  function bumpRefresh() {
3595
+ sessionCostCache.clear();
3284
3596
  const now = Date.now();
3285
3597
  const wait = lastRefresh + REFRESH_THROTTLE_MS - now;
3286
3598
  if (wait <= 0) {
@@ -3310,6 +3622,28 @@ var tui_default = Plugin.define({
3310
3622
  return;
3311
3623
  }
3312
3624
  }
3625
+ function sessionListCostFor(sessionID) {
3626
+ if (!pricing)
3627
+ return 0;
3628
+ const cached = sessionCostCache.get(sessionID);
3629
+ if (cached !== undefined)
3630
+ return cached;
3631
+ const handle = db();
3632
+ if (handle === undefined)
3633
+ return 0;
3634
+ try {
3635
+ const value = sessionListCost(handle, sessionID);
3636
+ if (sessionCostCache.size >= 512) {
3637
+ const oldest = sessionCostCache.keys().next();
3638
+ if (oldest.done !== true)
3639
+ sessionCostCache.delete(oldest.value);
3640
+ }
3641
+ sessionCostCache.set(sessionID, value);
3642
+ return value;
3643
+ } catch {
3644
+ return 0;
3645
+ }
3646
+ }
3313
3647
  function withWrite(run) {
3314
3648
  let handle;
3315
3649
  try {
@@ -3321,6 +3655,14 @@ var tui_default = Plugin.define({
3321
3655
  handle?.close();
3322
3656
  }
3323
3657
  }
3658
+ function backfill() {
3659
+ if (!pricing)
3660
+ return;
3661
+ const table = priceTableFor();
3662
+ if (table === undefined)
3663
+ return;
3664
+ return withWrite((handle) => backfillListCost(handle, (ref, tokens) => costOf(table, ref, tokens)));
3665
+ }
3324
3666
  function sessionStart(sessionID) {
3325
3667
  return ctx.data.session.get(sessionID)?.time.created;
3326
3668
  }
@@ -3334,9 +3676,12 @@ var tui_default = Plugin.define({
3334
3676
  function lineFor(sessionID) {
3335
3677
  if (!sessionIdle(sessionID))
3336
3678
  return;
3679
+ if (pricing)
3680
+ refresh();
3337
3681
  const messages = ctx.data.session.message.list(sessionID);
3338
3682
  const info = ctx.data.session.get(sessionID);
3339
- return computeTurn(toTranscriptTail(messages, 2), sessionTotals(info));
3683
+ const session = info === undefined ? undefined : sessionTotals(info, sessionListCostFor(sessionID));
3684
+ return computeTurn(toTranscriptTail(messages, 2, priceFor()), session);
3340
3685
  }
3341
3686
  function toneColor(tone) {
3342
3687
  if (tone === "warning")
@@ -3349,7 +3694,8 @@ var tui_default = Plugin.define({
3349
3694
  const parts = createMemo3(() => lineParts(lineFor(props.sessionID), {
3350
3695
  labels: options.labels,
3351
3696
  fields: options.fields,
3352
- turnTotals: options.turnTotals
3697
+ turnTotals: options.turnTotals,
3698
+ estimates: pricing
3353
3699
  }));
3354
3700
  return _$createComponent3(Show, {
3355
3701
  get when() {
@@ -3392,9 +3738,11 @@ var tui_default = Plugin.define({
3392
3738
  db,
3393
3739
  dbPath: () => resolveDbPath(options.db),
3394
3740
  withWrite,
3741
+ backfill,
3395
3742
  now: () => Date.now(),
3396
3743
  sessionStart,
3397
- refresh
3744
+ refresh,
3745
+ bump: bumpRefresh
3398
3746
  },
3399
3747
  settings,
3400
3748
  update: patchSettings,
@@ -3402,7 +3750,8 @@ var tui_default = Plugin.define({
3402
3750
  return {
3403
3751
  labels: options.labels,
3404
3752
  fields: options.fields,
3405
- turnTotals: options.turnTotals
3753
+ turnTotals: options.turnTotals,
3754
+ estimates: pricing
3406
3755
  };
3407
3756
  }
3408
3757
  }) : null
@@ -3425,7 +3774,8 @@ var tui_default = Plugin.define({
3425
3774
  return {
3426
3775
  labels: options.labels,
3427
3776
  fields: options.fields,
3428
- turnTotals: options.turnTotals
3777
+ turnTotals: options.turnTotals,
3778
+ estimates: pricing
3429
3779
  };
3430
3780
  }
3431
3781
  })
@@ -3480,12 +3830,16 @@ var tui_default = Plugin.define({
3480
3830
  ctx.data.on("session.execution.succeeded", () => bumpRefresh()),
3481
3831
  ctx.data.on("session.execution.failed", () => bumpRefresh()),
3482
3832
  ctx.data.on("session.execution.interrupted", () => bumpRefresh()),
3483
- ctx.data.on("session.compaction.ended", () => bumpRefresh())
3833
+ ctx.data.on("session.compaction.ended", () => bumpRefresh()),
3834
+ ctx.data.on("model.updated", () => {
3835
+ priceCache = undefined;
3836
+ })
3484
3837
  ];
3485
3838
  __test.line = lineFor;
3486
3839
  __test.lineText = (sessionID) => lineText(lineParts(lineFor(sessionID), {
3487
3840
  labels: options.labels,
3488
- fields: options.fields
3841
+ fields: options.fields,
3842
+ estimates: pricing
3489
3843
  }));
3490
3844
  __test.open = open;
3491
3845
  __test.state = () => {
@@ -3512,4 +3866,4 @@ export {
3512
3866
  tui_default as default
3513
3867
  };
3514
3868
 
3515
- //# debugId=6DDD20AEAE1B401D64756E2164756E21
3869
+ //# debugId=EAEFC12B046D781964756E2164756E21