opencode-usage-insights 0.1.0 → 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,10 +51,11 @@ 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
  }
57
- function affinityKey(model) {
58
+ function identityKey(model) {
58
59
  if (!model)
59
60
  return;
60
61
  return `${model.providerID}/${model.id}${model.variant ? `#${model.variant}` : ""}`;
@@ -71,14 +72,16 @@ function stepEnd(message) {
71
72
  return;
72
73
  return time.completed ?? time.streamed ?? time.created;
73
74
  }
74
- function cacheDrop(reference, current) {
75
+ function cacheDrop(reference, current, scope = "provider") {
75
76
  if (!reference)
76
77
  return;
77
78
  const before = reference.model;
78
79
  const after = current.model;
79
80
  if (!before || !after)
80
81
  return;
81
- if (before.providerID !== after.providerID || before.id !== after.id || (before.variant ?? "") !== (after.variant ?? "")) {
82
+ if (scope === "provider" && before.providerID !== after.providerID)
83
+ return;
84
+ if (before.id !== after.id || (before.variant ?? "") !== (after.variant ?? "")) {
82
85
  return;
83
86
  }
84
87
  const drop = cacheRead(reference) - cacheRead(current);
@@ -135,8 +138,8 @@ function computeTurn(messages, session) {
135
138
  }
136
139
  const provider = lastStep.model?.providerID;
137
140
  const previousProvider = previousStep?.model?.providerID;
138
- const key = affinityKey(lastStep.model);
139
- const previousKey = affinityKey(previousStep?.model);
141
+ const key = identityKey(lastStep.model);
142
+ const previousKey = identityKey(previousStep?.model);
140
143
  return {
141
144
  endAt: stepEnd(lastStep),
142
145
  startAt: stepCreated(settled[0] ?? lastStep),
@@ -145,9 +148,6 @@ function computeTurn(messages, session) {
145
148
  providerID: provider,
146
149
  modelID: lastStep.model?.id,
147
150
  variant: lastStep.model?.variant,
148
- router: undefined,
149
- identityChanged: false,
150
- affinityKey: key,
151
151
  providerChanged: previousProvider !== undefined && provider !== undefined && previousProvider !== provider,
152
152
  modelChanged: previousKey !== undefined && key !== undefined && previousKey !== key && previousProvider === provider,
153
153
  totals: totalize(settled),
@@ -156,8 +156,7 @@ function computeTurn(messages, session) {
156
156
  drops,
157
157
  cacheDropTokens: drops.reduce((sum, drop) => sum + drop.tokens, 0),
158
158
  cacheExpired: drops.length > 0,
159
- steps: settled.length,
160
- stepIDs: settled.map((step) => step.id)
159
+ steps: settled.length
161
160
  };
162
161
  }
163
162
  function promptGap(current, previous) {
@@ -183,6 +182,7 @@ var DEFAULT_LABELS = {
183
182
  output: "out",
184
183
  reasoning: "reason",
185
184
  cost: "cost",
185
+ estimate: "\u2248",
186
186
  cacheExpired: "cache expired",
187
187
  providerChanged: "changed",
188
188
  modelChanged: "model changed"
@@ -195,7 +195,7 @@ var DEFAULT_FIELDS = {
195
195
  turn: true,
196
196
  session: true,
197
197
  reasoning: false,
198
- cost: false,
198
+ cost: true,
199
199
  cacheExpiry: true
200
200
  };
201
201
  function formatClock(ms) {
@@ -241,6 +241,20 @@ function formatCost(value) {
241
241
  return `$${value.toFixed(4)}`;
242
242
  return `$${value.toFixed(2)}`;
243
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
+ }
244
258
  function displayTotals(totals) {
245
259
  const prompt = totals.input + totals.cached + totals.cacheWrite;
246
260
  return {
@@ -250,11 +264,12 @@ function displayTotals(totals) {
250
264
  output: totals.output + totals.reasoning,
251
265
  reasoning: totals.reasoning,
252
266
  cost: totals.cost,
267
+ listCost: totals.listCost,
253
268
  steps: totals.steps,
254
269
  prompt
255
270
  };
256
271
  }
257
- function totalsText(prefix, totals, labels, fields, stepCount = 0) {
272
+ function totalsText(prefix, totals, labels, fields, stepCount = 0, cost = totals.cost, listCost = totals.listCost, estimates = true) {
258
273
  const display = displayTotals(totals);
259
274
  const input = display.prompt === display.input ? `${labels.input} ${formatTokens(display.input)}` : `${labels.input} ${formatTokens(display.input)} (${formatTokens(display.prompt)})`;
260
275
  const parts = [
@@ -264,8 +279,9 @@ function totalsText(prefix, totals, labels, fields, stepCount = 0) {
264
279
  ];
265
280
  if (fields.reasoning)
266
281
  parts.push(`${labels.reasoning} ${formatTokens(display.reasoning)}`);
267
- if (fields.cost)
268
- parts.push(`${labels.cost} ${formatCost(display.cost)}`);
282
+ const money = fields.cost ? formatMoney(cost, estimates ? listCost : 0, labels.estimate) : undefined;
283
+ if (money !== undefined)
284
+ parts.push(`${labels.cost} ${money}`);
269
285
  const steps = stepCount > 1 ? `${stepCount} ${stepCount === 1 ? labels.step : labels.steps}` : "";
270
286
  const head = [prefix, steps].filter((piece) => piece !== "").join(" ");
271
287
  const numbers = parts.join(", ");
@@ -277,7 +293,7 @@ function formatLineSegments(stats, options) {
277
293
  const labels = { ...DEFAULT_LABELS, ...options?.labels };
278
294
  const fields = { ...DEFAULT_FIELDS, ...options?.fields };
279
295
  const turnTotals = options?.turnTotals ?? "latest";
280
- const identity = options?.identity ?? "endpoint";
296
+ const estimates = options?.estimates !== false;
281
297
  const segments = [];
282
298
  if (fields.clock && stats.endAt !== undefined) {
283
299
  segments.push({ text: formatClock(stats.endAt), tone: "muted" });
@@ -285,11 +301,7 @@ function formatLineSegments(stats, options) {
285
301
  if (fields.delta && stats.promptGapMs !== undefined) {
286
302
  segments.push({ text: `${labels.delta} ${formatDuration(stats.promptGapMs)}`, tone: "muted" });
287
303
  }
288
- if (identity === "endpoint" && stats.router !== undefined) {
289
- segments.push({ text: stats.router, tone: stats.identityChanged ? "warning" : "base" });
290
- if (stats.identityChanged)
291
- segments.push({ text: labels.providerChanged, tone: "warning" });
292
- } else if (stats.providerID !== undefined) {
304
+ if (stats.providerID !== undefined) {
293
305
  let text = stats.providerID;
294
306
  if (fields.model && stats.modelID !== undefined)
295
307
  text += `/${stats.modelID}`;
@@ -303,10 +315,16 @@ function formatLineSegments(stats, options) {
303
315
  }
304
316
  if (fields.turn && stats.totals.steps > 0) {
305
317
  const totals = turnTotals === "sum" ? stats.totals : stats.latest;
306
- segments.push({ text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps), tone: "base" });
318
+ segments.push({
319
+ text: totalsText(labels.turn, totals, labels, fields, turnTotals === "sum" ? stats.totals.steps : stats.steps, stats.totals.cost, stats.totals.listCost, estimates),
320
+ tone: "base"
321
+ });
307
322
  }
308
323
  if (fields.session && stats.session) {
309
- segments.push({ text: totalsText(labels.session, stats.session, labels, fields), 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
+ });
310
328
  }
311
329
  if (fields.cacheExpiry && stats.cacheExpired) {
312
330
  const count = stats.drops.length > 1 ? `\xD7${stats.drops.length}` : "";
@@ -341,13 +359,9 @@ var TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
341
359
  function isToken(value, limit = 64) {
342
360
  return value.length > 0 && value.length <= limit && TOKEN.test(value);
343
361
  }
344
- function normalizeToken(value, limit = 64) {
345
- const trimmed = value.trim().toLowerCase();
346
- return isToken(trimmed, limit) ? trimmed : undefined;
347
- }
348
362
 
349
363
  // src/line.ts
350
- function toTranscript(messages) {
364
+ function toTranscript(messages, price) {
351
365
  const transcript = [];
352
366
  for (const message of messages) {
353
367
  if (typeof message.id !== "string" || typeof message.type !== "string")
@@ -356,20 +370,34 @@ function toTranscript(messages) {
356
370
  transcript.push({ type: message.type, id: message.id, time: message.time });
357
371
  continue;
358
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
+ }
359
386
  transcript.push({
360
387
  type: "assistant",
361
388
  id: message.id,
362
389
  time: message.time,
363
- model: toModelRef(message.model),
390
+ model,
364
391
  tokens: message.tokens,
365
392
  cost: message.cost,
393
+ ...listCost !== undefined ? { listCost } : {},
366
394
  finish: message.finish ?? undefined,
367
395
  rawFinish: message.rawFinish ?? undefined
368
396
  });
369
397
  }
370
398
  return transcript;
371
399
  }
372
- function toTranscriptTail(messages, segments = 2) {
400
+ function toTranscriptTail(messages, segments = 2, price) {
373
401
  const wanted = Math.max(2, segments);
374
402
  const tail = [];
375
403
  let collected = 0;
@@ -392,7 +420,7 @@ function toTranscriptTail(messages, segments = 2) {
392
420
  break;
393
421
  }
394
422
  tail.reverse();
395
- return toTranscript(tail);
423
+ return toTranscript(tail, price);
396
424
  }
397
425
  function toModelRef(model) {
398
426
  if (model === undefined || model.providerID === undefined || model.id === undefined)
@@ -401,7 +429,7 @@ function toModelRef(model) {
401
429
  return { providerID: model.providerID, id: model.id };
402
430
  return { providerID: model.providerID, id: model.id, variant: model.variant };
403
431
  }
404
- function sessionTotals(info) {
432
+ function sessionTotals(info, listCost = 0) {
405
433
  if (info === undefined)
406
434
  return;
407
435
  const tokens = info.tokens;
@@ -412,6 +440,7 @@ function sessionTotals(info) {
412
440
  reasoning: tokens?.reasoning ?? 0,
413
441
  cacheWrite: tokens?.cache?.write ?? 0,
414
442
  cost: info.cost ?? 0,
443
+ listCost,
415
444
  steps: 0
416
445
  };
417
446
  }
@@ -434,6 +463,13 @@ function lineText(parts) {
434
463
  // src/stats/queries.ts
435
464
  var COMPACTION_KIND = "compaction";
436
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
+ }
437
473
  var STEP_TIME = "COALESCE(created_at, recorded_at)";
438
474
  var MODEL_KEY_SQL = "COALESCE(model_id, '(unknown)') || '#' || COALESCE(variant, '')";
439
475
  function modelKey(modelID, variant) {
@@ -448,7 +484,8 @@ var USAGE_SELECT = `COUNT(*) AS steps,
448
484
  COALESCE(SUM(cache_write), 0) AS cacheWrite,
449
485
  COALESCE(SUM(output_tokens), 0) AS output,
450
486
  COALESCE(SUM(reasoning_tokens), 0) AS reasoning,
451
- COALESCE(SUM(cost), 0) AS cost`;
487
+ COALESCE(SUM(cost), 0) AS cost,
488
+ COALESCE(SUM(list_cost), 0) AS listCost`;
452
489
  function usageFrom(row) {
453
490
  return {
454
491
  steps: row.steps ?? 0,
@@ -457,7 +494,8 @@ function usageFrom(row) {
457
494
  cacheWrite: row.cacheWrite ?? 0,
458
495
  output: row.output ?? 0,
459
496
  reasoning: row.reasoning ?? 0,
460
- cost: row.cost ?? 0
497
+ cost: row.cost ?? 0,
498
+ listCost: row.listCost ?? 0
461
499
  };
462
500
  }
463
501
  function rangeWhere(range, column = STEP_TIME) {
@@ -485,9 +523,9 @@ function buildWhere(range, filters, column = STEP_TIME) {
485
523
  clauses.push(`${MODEL_KEY_SQL} = ?`);
486
524
  params.push(filters.modelKey);
487
525
  }
488
- if (filters?.router !== undefined && filters.router !== "") {
489
- clauses.push("router = ?");
490
- params.push(filters.router);
526
+ if (filters?.provider !== undefined && filters.provider !== "") {
527
+ clauses.push("provider_id = ?");
528
+ params.push(filters.provider);
491
529
  }
492
530
  if (filters?.sessionID !== undefined && filters.sessionID !== "") {
493
531
  clauses.push("session_id = ?");
@@ -510,7 +548,7 @@ function overview(db, range, filters) {
510
548
  FROM steps ${steps.where}`).get(...steps.params);
511
549
  const prompts = rangeWhere(range, "created_at");
512
550
  const promptRow = db.query(`SELECT COUNT(*) AS prompts FROM prompts ${prompts.where}`).get(...prompts.params);
513
- 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 });
514
552
  return {
515
553
  ...usage,
516
554
  sessions: row?.sessions ?? 0,
@@ -524,37 +562,35 @@ function overview(db, range, filters) {
524
562
  function models(db, range, filters) {
525
563
  const filter = buildWhere(range, filters);
526
564
  const rows = db.query(`SELECT provider_id, model_id, variant,
527
- GROUP_CONCAT(DISTINCT router) AS router_list,
528
565
  ${USAGE_SELECT},
529
566
  MIN(${STEP_TIME}) AS first_at,
530
567
  MAX(COALESCE(completed_at, recorded_at)) AS last_at
531
568
  FROM steps ${filter.where}
532
569
  GROUP BY provider_id, model_id, variant
533
570
  ORDER BY steps DESC, cached DESC`).all(...filter.params);
534
- const models2 = new Map;
571
+ const models = new Map;
535
572
  for (const row of rows) {
536
573
  const modelID = row.model_id ?? "(unknown)";
537
574
  const variant = row.variant ?? undefined;
538
575
  const key = `${modelID}#${variant ?? ""}`;
539
- let model = models2.get(key);
576
+ let model = models.get(key);
540
577
  if (!model) {
541
578
  model = { modelID, variant, providers: [], totals: emptyUsage() };
542
- models2.set(key, model);
579
+ models.set(key, model);
543
580
  }
544
581
  const usage = usageFrom(row);
545
582
  model.providers.push({
546
583
  ...usage,
547
584
  providerID: row.provider_id ?? "(unknown)",
548
- routers: row.router_list ? row.router_list.split(",").filter(Boolean) : [],
549
585
  firstAt: row.first_at ?? undefined,
550
586
  lastAt: row.last_at ?? undefined
551
587
  });
552
588
  addUsage(model.totals, usage);
553
589
  }
554
- return [...models2.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
590
+ return [...models.values()].sort((a, b) => billedTokens(b.totals) - billedTokens(a.totals));
555
591
  }
556
592
  function emptyUsage() {
557
- 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 };
558
594
  }
559
595
  function addUsage(target, source) {
560
596
  target.steps += source.steps;
@@ -564,6 +600,7 @@ function addUsage(target, source) {
564
600
  target.output += source.output;
565
601
  target.reasoning += source.reasoning;
566
602
  target.cost += source.cost;
603
+ target.listCost += source.listCost;
567
604
  }
568
605
  function billedTokens(usage) {
569
606
  return usage.input + usage.cached + usage.output;
@@ -608,6 +645,7 @@ function sessions(db, options) {
608
645
  COALESCE(SUM(st.output_tokens), 0) AS output,
609
646
  COALESCE(SUM(st.reasoning_tokens), 0) AS reasoning,
610
647
  COALESCE(SUM(st.cost), 0) AS cost,
648
+ COALESCE(SUM(st.list_cost), 0) AS listCost,
611
649
  MIN(COALESCE(st.created_at, st.recorded_at)) AS first_at,
612
650
  MAX(COALESCE(st.completed_at, st.created_at, st.recorded_at)) AS last_at
613
651
  FROM steps st
@@ -650,7 +688,8 @@ function stepUsage(row) {
650
688
  cacheWrite: row.cache_write ?? 0,
651
689
  output: row.output_tokens ?? 0,
652
690
  reasoning: row.reasoning_tokens ?? 0,
653
- cost: row.cost ?? 0
691
+ cost: row.cost ?? 0,
692
+ listCost: row.list_cost ?? 0
654
693
  };
655
694
  }
656
695
  function stepMessage(row) {
@@ -683,8 +722,8 @@ function turns(db, options) {
683
722
  params.push(floor);
684
723
  }
685
724
  const steps = db.query(`SELECT message_id, session_id, provider_id, model_id, variant,
686
- input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost,
687
- created_at, streamed_at, recorded_at, completed_at, finish, router
725
+ input_tokens, cache_read, cache_write, output_tokens, reasoning_tokens, cost, list_cost,
726
+ created_at, streamed_at, recorded_at, completed_at, finish
688
727
  FROM steps ${clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : ""}
689
728
  ORDER BY session_id, ${STEP_TIME}`).all(...params);
690
729
  const promptClause = options?.sessionID === undefined ? "" : `WHERE session_id = ?${floor === undefined ? "" : " AND created_at >= ?"}`;
@@ -723,18 +762,9 @@ function turns(db, options) {
723
762
  }
724
763
  reference = message;
725
764
  }
726
- const lastWith = (pick) => {
727
- for (let index = bucket.length - 1;index >= 0; index -= 1) {
728
- const value = pick(bucket[index]);
729
- if (value !== null)
730
- return value;
731
- }
732
- return;
733
- };
734
765
  const providerID = last.provider_id ?? undefined;
735
766
  const modelID = last.model_id ?? undefined;
736
767
  const variant = last.variant ?? undefined;
737
- const router = lastWith((row) => row.router);
738
768
  let produced = 0;
739
769
  let window = 0;
740
770
  for (const row of bucket) {
@@ -752,8 +782,6 @@ function turns(db, options) {
752
782
  providerID,
753
783
  modelID,
754
784
  variant,
755
- router,
756
- routerChanged: previous?.router !== undefined && router !== undefined && previous.router !== router,
757
785
  providerChanged: previous?.providerID !== undefined && providerID !== undefined && previous.providerID !== providerID,
758
786
  modelChanged: previous !== undefined && previous.providerID === providerID && `${previous.modelID ?? ""}#${previous.variant ?? ""}` !== `${modelID ?? ""}#${variant ?? ""}`,
759
787
  steps: bucket.length,
@@ -797,31 +825,14 @@ function promptFloor(db, sessionID, count) {
797
825
  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);
798
826
  return rows.length === count ? rows[count - 1].created_at : undefined;
799
827
  }
800
- function routerBefore(db, sessionID, at) {
801
- if (at === undefined)
802
- return;
803
- const row = db.query(`SELECT router FROM steps
804
- WHERE session_id = $sessionID AND router IS NOT NULL AND COALESCE(created_at, recorded_at) < $at
805
- ORDER BY COALESCE(created_at, recorded_at) DESC LIMIT 1`).get({ $sessionID: sessionID, $at: at });
806
- return row?.router ?? undefined;
807
- }
808
- function routerForSteps(db, sessionID, messageIDs) {
809
- if (messageIDs.length === 0)
810
- return;
811
- const placeholders = messageIDs.map(() => "?").join(", ");
812
- const row = db.query(`SELECT router FROM steps
813
- WHERE session_id = ? AND message_id IN (${placeholders}) AND router IS NOT NULL
814
- ORDER BY recorded_at DESC LIMIT 1`).get(sessionID, ...messageIDs);
815
- return row?.router ?? undefined;
816
- }
817
828
  function filterOptions(db) {
818
829
  const pick = (column) => db.query(`SELECT ${column} AS value, COUNT(*) AS steps FROM steps WHERE ${column} IS NOT NULL GROUP BY ${column} ORDER BY steps DESC`).all().map((row) => ({ value: row.value, steps: row.steps }));
819
- return { models: pick("model_id"), endpoints: pick("router") };
830
+ return { models: pick("model_id"), providers: pick("provider_id") };
820
831
  }
821
832
 
822
833
  // src/panel-data.ts
823
834
  var PANEL_NAME = "usage-insights";
824
- var PANEL_VIEWS = ["overview", "models", "endpoints", "affinity", "cache", "periods", "latency", "sessions", "turns", "db"];
835
+ var PANEL_VIEWS = ["overview", "models", "providers", "cache", "periods", "latency", "sessions", "turns", "db"];
825
836
  var RANGE_KEYS = ["session", "today", "7d", "30d", "all"];
826
837
  var GRANULARITIES = ["day", "week", "month"];
827
838
  function parseArgs(input) {
@@ -830,9 +841,8 @@ function parseArgs(input) {
830
841
  const value = token.trim().toLowerCase();
831
842
  if (value === "")
832
843
  continue;
833
- const view = value === "providers" ? "endpoints" : value;
834
- if (PANEL_VIEWS.includes(view))
835
- parsed.view = view;
844
+ if (PANEL_VIEWS.includes(value))
845
+ parsed.view = value;
836
846
  else if (RANGE_KEYS.includes(value))
837
847
  parsed.range = value;
838
848
  }
@@ -866,7 +876,7 @@ var DEFAULT_SETTINGS = {
866
876
  granularity: "day",
867
877
  turnsScope: "session",
868
878
  modelID: "",
869
- routerID: ""
879
+ providerID: ""
870
880
  };
871
881
  function sanitizeSettings(raw) {
872
882
  const settings = { ...DEFAULT_SETTINGS, ...raw ?? {} };
@@ -878,7 +888,7 @@ function sanitizeSettings(raw) {
878
888
  granularity: GRANULARITIES.includes(settings.granularity) ? settings.granularity : DEFAULT_SETTINGS.granularity,
879
889
  turnsScope: settings.turnsScope === "all" ? "all" : "session",
880
890
  modelID: typeof settings.modelID === "string" ? settings.modelID : "",
881
- routerID: typeof settings.routerID === "string" ? settings.routerID : ""
891
+ providerID: typeof settings.providerID === "string" ? settings.providerID : ""
882
892
  };
883
893
  }
884
894
  function formatPercent(value, digits = 1) {
@@ -1018,6 +1028,7 @@ function usageBuckets(usage) {
1018
1028
  output: usage.output + usage.reasoning,
1019
1029
  reasoning: usage.reasoning,
1020
1030
  cost: usage.cost,
1031
+ listCost: usage.listCost ?? 0,
1021
1032
  hit: prompt > 0 ? usage.cached / prompt : undefined
1022
1033
  };
1023
1034
  }
@@ -1030,23 +1041,23 @@ function viewBar(view, width = 200) {
1030
1041
  if (text.length <= width)
1031
1042
  return { text, tone: "muted" };
1032
1043
  }
1033
- return { text: `[${String((PANEL_VIEWS.indexOf(view) + 1) % 10)} ${view}] \xB7 0-9 or [ ] to switch`, tone: "muted" };
1044
+ return { text: `[${PANEL_VIEWS.indexOf(view) + 1} ${view}] \xB7 1-9 or [ ] to switch`, tone: "muted" };
1034
1045
  }
1035
1046
  function keysFor(of) {
1036
1047
  if (of === "db")
1037
- return "\u2191\u2193 pick a retention \xB7 enter prune (asks first) \xB7 v vacuum \xB7 r refresh \xB7 0-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";
1038
1049
  if (of === "periods")
1039
- return "\u2191\u2193 move \xB7 enter drill \xB7 b bucket \xB7 t range \xB7 m/e filter \xB7 x clear \xB7 0-9 view \xB7 ? help";
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";
1040
1051
  if (of === "turns")
1041
- return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 1-9 view \xB7 ? help";
1042
- return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/e filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1052
+ return "\u2191\u2193 move \xB7 a scope \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1053
+ return "\u2191\u2193 move \xB7 enter drill \xB7 s sort \xB7 t range \xB7 m/p filter \xB7 x clear \xB7 1-9 view \xB7 ? help";
1043
1054
  }
1044
1055
  function filterSummary(filters) {
1045
1056
  const parts = [];
1046
1057
  if (filters.modelID !== undefined && filters.modelID !== "")
1047
1058
  parts.push(`model=${filters.modelID}`);
1048
- if (filters.routerID !== undefined && filters.routerID !== "")
1049
- parts.push(`endpoint=${filters.routerID}`);
1059
+ if (filters.providerID !== undefined && filters.providerID !== "")
1060
+ parts.push(`provider=${filters.providerID}`);
1050
1061
  return parts.length > 0 ? parts.join(" \xB7 ") : undefined;
1051
1062
  }
1052
1063
  function granularityLabel(granularity) {
@@ -1056,13 +1067,14 @@ function helpLines(width) {
1056
1067
  const lines = [
1057
1068
  { text: "keys", tone: HEADER_TONE },
1058
1069
  { text: " \u2191 \u2193 j k move the cursor \xB7 enter drills in \xB7 backspace goes back" },
1059
- { text: " 0-9 [ ] choose a view \xB7 cycle views (0 is db)" },
1070
+ { text: " 1-9 [ ] choose a view \xB7 cycle views (9 is db)" },
1060
1071
  { text: " t shift+t previous / next range" },
1061
1072
  { text: " s shift+s cycle sort column \xB7 reverse" },
1062
1073
  { text: " b periods bucket: day \u2192 week \u2192 month" },
1063
1074
  { text: " a turns scope: this session \u2194 all sessions" },
1064
- { text: " m e filter by model / endpoint, who served it (x clears)" },
1075
+ { text: " m p filter by model / provider (x clears)" },
1065
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" },
1066
1078
  { text: "" },
1067
1079
  { text: "numbers \xB7 the same buckets as the live line", tone: HEADER_TONE },
1068
1080
  { text: " prompt everything the provider saw: cached + fresh + writes" },
@@ -1073,28 +1085,30 @@ function helpLines(width) {
1073
1085
  { text: " hit p50 median of the per-step hit: spots a split pattern" },
1074
1086
  { text: " out everything generated: visible output + reasoning" },
1075
1087
  { text: " reasoning part of `out`" },
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" },
1076
1091
  { text: " wall request \u2192 completed step \xB7 stream request \u2192 last chunk" },
1077
1092
  { text: " tps out / streaming seconds, shown as p50" },
1078
- { text: " changed the step's model or endpoint differs from the step" },
1079
- { text: " before it in the same session (affinity view)" },
1093
+ { text: " switches how often a step's model or provider differs from the step" },
1094
+ { text: " before it in the same session (the models view's detail), with" },
1095
+ { text: " the cache a provider switch cost" },
1080
1096
  { text: "" },
1081
- { text: "evidence", tone: HEADER_TONE },
1082
- { text: " endpoint where the request was actually sent: the endpoint that ran" },
1083
- { text: " the inference in practice, and the only identity the panel" },
1084
- { text: " shows. The endpoint is the inference provider." },
1085
- { text: " recorded the OpenCode provider is kept in the database as evidence," },
1086
- { text: " not surfaced: it says where a request came from, not who" },
1087
- { text: " ran it" },
1097
+ { text: "identity", tone: HEADER_TONE },
1098
+ { text: " provider the provider the model ran through, as OpenCode is configured" },
1099
+ { text: " (opencode, opencode-go, deepseek, \u2026). A gateway may re-route" },
1100
+ { text: " a request, but the upstream that ran the inference is not" },
1101
+ { text: " observable, so the provider is the identity every view shows." },
1088
1102
  { text: "" },
1089
1103
  { text: "database", tone: HEADER_TONE },
1090
1104
  { text: " the db view shows where the file lives, what it holds and how much" },
1091
1105
  { text: " of it is old: \u2191\u2193 pick a retention, enter prunes from its cutoff date," },
1092
- { text: " v gives the space back" },
1106
+ { text: " e backfills list estimates, v gives the space back" },
1093
1107
  { text: " local time \xB7 SQLite in the OpenCode state directory" }
1094
1108
  ];
1095
1109
  return lines.map((line) => ({ ...line, text: truncate(line.text, width) }));
1096
1110
  }
1097
- function usagePairs(usage) {
1111
+ function usagePairs(usage, estimates = true) {
1098
1112
  if (usage === undefined)
1099
1113
  return [];
1100
1114
  const buckets = usageBuckets(usage);
@@ -1109,18 +1123,19 @@ function usagePairs(usage) {
1109
1123
  ];
1110
1124
  if (buckets.reasoning > 0)
1111
1125
  pairs.push(["reasoning", formatTokens(buckets.reasoning)]);
1112
- pairs.push(["cost", formatCost(buckets.cost)]);
1126
+ pairs.push(["cost", (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost)]);
1113
1127
  if ("tps" in usage && usage.tps !== undefined)
1114
1128
  pairs.push(["tps", formatTps(usage.tps)]);
1115
1129
  return pairs;
1116
1130
  }
1117
1131
  function overviewLines(data, width) {
1118
1132
  const lines = [];
1133
+ const estimates = data.estimates !== false;
1119
1134
  lines.push({
1120
1135
  text: `${rangeLabel(data.range)} \xB7 ${count(data.usage.steps, "step")} \xB7 ${count(data.usage.sessions, "session")} \xB7 ${count(data.usage.prompts, "prompt")}`,
1121
1136
  tone: "muted"
1122
1137
  });
1123
- lines.push(...kvGrid(buildOverviewPairs(data.usage, "all"), width));
1138
+ lines.push(...kvGrid(buildOverviewPairs(data.usage, "all", estimates), width));
1124
1139
  if (data.activity !== undefined && data.activity.length > 1) {
1125
1140
  const series = reduceSeries(data.activity);
1126
1141
  lines.push({ text: "", tone: "muted" });
@@ -1129,12 +1144,13 @@ function overviewLines(data, width) {
1129
1144
  if (data.session !== undefined) {
1130
1145
  lines.push({ text: "", tone: "muted" });
1131
1146
  lines.push({ text: "this session", tone: HEADER_TONE });
1132
- lines.push(...kvGrid(buildOverviewPairs(data.session, "session"), width));
1147
+ lines.push(...kvGrid(buildOverviewPairs(data.session, "session", estimates), width));
1133
1148
  if (data.subagents !== undefined && data.subagents.length > 0) {
1134
1149
  const steps = data.subagents.reduce((sum, row) => sum + row.steps, 0);
1135
1150
  const cost = data.subagents.reduce((sum, row) => sum + row.cost, 0);
1151
+ const listCost = data.subagents.reduce((sum, row) => sum + row.listCost, 0);
1136
1152
  lines.push({
1137
- 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)`,
1138
1154
  tone: "muted"
1139
1155
  });
1140
1156
  }
@@ -1146,8 +1162,8 @@ function overviewLines(data, width) {
1146
1162
  }
1147
1163
  return lines;
1148
1164
  }
1149
- function buildOverviewPairs(usage, scope) {
1150
- const pairs = usagePairs(usage);
1165
+ function buildOverviewPairs(usage, scope, estimates = true) {
1166
+ const pairs = usagePairs(usage, estimates);
1151
1167
  if (scope === "all") {
1152
1168
  pairs.push(["first", usage.firstAt === undefined ? "\u2013" : new Date(usage.firstAt).toLocaleString("en-GB")]);
1153
1169
  pairs.push(["last", usage.lastAt === undefined ? "\u2013" : new Date(usage.lastAt).toLocaleString("en-GB")]);
@@ -1158,7 +1174,7 @@ function coveragePairs(coverage) {
1158
1174
  const share = (missing) => coverage.steps === 0 ? "\u2013" : `${(missing / coverage.steps * 100).toFixed(1)}%`;
1159
1175
  return [
1160
1176
  ["models", `${formatCount(coverage.models)} \xB7 unknown ${share(coverage.missingModel)}`],
1161
- ["endpoints", `${formatCount(coverage.endpoints)} \xB7 unknown ${share(coverage.missingEndpoint)}`],
1177
+ ["providers", formatCount(coverage.providers)],
1162
1178
  ["unsettled", `${formatCount(coverage.unsettled)} \xB7 no tps ${share(coverage.missingTps)}`],
1163
1179
  [
1164
1180
  "window",
@@ -1181,7 +1197,7 @@ function modelColumns(width) {
1181
1197
  }
1182
1198
  return layouts[layouts.length - 1];
1183
1199
  }
1184
- function modelsLines(rows, width, extras, limit = 40) {
1200
+ function modelsLines(rows, width, extras, limit = 40, estimates = true) {
1185
1201
  const columns = modelColumns(width);
1186
1202
  const widths = [columns.model, columns.steps, columns.prompt, columns.cached];
1187
1203
  const aligns = ["left", "right", "right", "right"];
@@ -1202,24 +1218,24 @@ function modelsLines(rows, width, extras, limit = 40) {
1202
1218
  if (columns.spread > 0) {
1203
1219
  widths.push(columns.spread);
1204
1220
  aligns.push("left");
1205
- header.push("served by");
1221
+ header.push("providers");
1206
1222
  }
1207
1223
  const lines = [{ text: formatTableRow(header, widths, aligns), tone: HEADER_TONE }];
1208
1224
  for (const model of rows.slice(0, limit)) {
1209
1225
  const key = modelKey(model.modelID, model.variant);
1210
1226
  const name = modelCell(model.modelID, model.variant, columns.model);
1211
1227
  const buckets = usageBuckets(model.totals);
1212
- const endpoints = unique(model.providers.flatMap((provider) => provider.routers));
1228
+ const providers = unique(model.providers.map((provider) => provider.providerID));
1213
1229
  const cache = extras?.cache?.get(key);
1214
- const changes = extras?.changes?.get(key);
1230
+ const switches = extras?.switches?.get(key);
1215
1231
  const cells = [name, formatCount(buckets.steps), formatTokens(buckets.prompt), formatTokens(buckets.cached)];
1216
1232
  if (columns.hit > 0)
1217
1233
  cells.push(formatPercent(cache?.hit ?? buckets.hit));
1218
1234
  cells.push(formatTokens(buckets.output));
1219
1235
  if (columns.cost > 0)
1220
- cells.push(formatCost(buckets.cost));
1236
+ cells.push(formatSpend(buckets.cost, estimates ? buckets.listCost : 0));
1221
1237
  if (columns.spread > 0)
1222
- cells.push(endpoints.length > 0 ? endpoints.join(", ") : "\u2013");
1238
+ cells.push(providers.join(", "));
1223
1239
  lines.push({
1224
1240
  text: formatTableRow(cells, widths, aligns),
1225
1241
  tone: "base",
@@ -1228,10 +1244,12 @@ function modelsLines(rows, width, extras, limit = 40) {
1228
1244
  const details = [];
1229
1245
  if (cache !== undefined)
1230
1246
  details.push(`p50 hit ${formatPercent(cache.hitP50)}`);
1231
- if (changes !== undefined && changes > 0)
1232
- details.push(count(changes, "identity change"));
1233
- if (endpoints.length === 0)
1234
- details.push("no routing endpoint observed");
1247
+ if (switches !== undefined && switches.changes > 0) {
1248
+ const scope = switches.providerChanges > 0 ? ` (${formatCount(switches.providerChanges)} provider)` : "";
1249
+ details.push(`${count(switches.changes, "switch", "switches")}${scope}`);
1250
+ if (switches.cacheLost > 0)
1251
+ details.push(`${formatTokens(switches.cacheLost)} lost on a switch`);
1252
+ }
1235
1253
  if (details.length > 0) {
1236
1254
  lines.push({ text: truncate(`${" ".repeat(columns.model + 1)}${details.join(" \xB7 ")}`, width), tone: "muted" });
1237
1255
  }
@@ -1276,9 +1294,9 @@ function renderTable(rows, columns, width, options) {
1276
1294
  lines.push({ text: `\u2026 ${count(rows.length - options.limit, "more row")}`, tone: "muted" });
1277
1295
  return lines;
1278
1296
  }
1279
- function endpointSummaryLines(rows, width, limit = 40) {
1297
+ function providerSummaryLines(rows, width, limit = 40, estimates = true) {
1280
1298
  const lines = renderTable(rows, [
1281
- { header: "endpoint", width: 24, cell: (row) => truncate(row.endpoint ?? "\u2013 (never observed)", 24) },
1299
+ { header: "provider", width: 24, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 24) },
1282
1300
  { header: "models", width: 13, align: "right", optional: true, cell: (row) => formatCount(row.models.length) },
1283
1301
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
1284
1302
  { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
@@ -1287,19 +1305,19 @@ function endpointSummaryLines(rows, width, limit = 40) {
1287
1305
  { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1288
1306
  { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1289
1307
  { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1290
- { 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) }
1291
1309
  ], width, {
1292
1310
  limit,
1293
- empty: "no routing endpoint was observed in this range",
1294
- row: (row) => row.endpoint === undefined ? undefined : { kind: "endpoint", value: row.endpoint },
1295
- tone: (row) => row.endpoint === undefined ? "muted" : "base"
1311
+ empty: "no usage recorded for this range",
1312
+ row: (row) => row.provider === undefined ? undefined : { kind: "provider", value: row.provider },
1313
+ tone: (row) => row.provider === undefined ? "muted" : "base"
1296
1314
  });
1297
1315
  return lines;
1298
1316
  }
1299
- function endpointsLines(rows, width, limit = 40) {
1317
+ function providerLines(rows, width, limit = 40, estimates = true) {
1300
1318
  return renderTable(rows, [
1301
1319
  { header: "model", width: 26, cell: (row) => modelCell(row.modelID, row.variant, 26) },
1302
- { header: "endpoint", width: 22, cell: (row) => truncate(row.endpoint ?? "\u2013 (never observed)", 22) },
1320
+ { header: "provider", width: 22, cell: (row) => truncate(row.provider ?? "\u2013 (unknown)", 22) },
1303
1321
  { header: "steps", width: 6, align: "right", cell: (row) => formatCount(row.usage.steps) },
1304
1322
  { header: "share", width: 6, align: "right", optional: true, cell: (row) => formatPercent(row.share, 0) },
1305
1323
  { header: "prompt", width: 10, align: "right", cell: (row) => formatTokens(row.cache.prompt) },
@@ -1307,62 +1325,14 @@ function endpointsLines(rows, width, limit = 40) {
1307
1325
  { header: "hit", width: 7, align: "right", optional: true, cell: (row) => formatPercent(row.cache.hit) },
1308
1326
  { header: "tps p50", width: 8, align: "right", optional: true, cell: (row) => formatTps(row.tps) },
1309
1327
  { header: "wall", width: 8, align: "right", optional: true, cell: (row) => formatMs(row.wall) },
1310
- { 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) }
1311
1329
  ], width, {
1312
1330
  limit,
1313
1331
  empty: "no usage recorded for this range",
1314
1332
  row: (row) => ({ kind: "model", value: row.modelID, ...row.variant !== undefined ? { variant: row.variant } : {} }),
1315
- tone: (row) => row.endpoint === undefined ? "muted" : "base"
1333
+ tone: (row) => row.provider === undefined ? "muted" : "base"
1316
1334
  });
1317
1335
  }
1318
- function affinityLines(report, width, limit = 40) {
1319
- const lines = [];
1320
- const rate = report.totals.pairs === 0 ? undefined : report.totals.changes / report.totals.pairs;
1321
- lines.push({
1322
- text: `${count(report.totals.pairs, "comparable step pair")} \xB7 ${count(report.totals.changes, "identity change")} (${formatPercent(rate)}) \xB7 cache lost on change ${formatTokens(report.totals.cacheLost)}`,
1323
- tone: report.totals.changes > 0 ? "warning" : "muted"
1324
- });
1325
- lines.push({ text: "a change is the step's model or endpoint differing from the step before it", tone: "muted" });
1326
- lines.push({ text: "", tone: "muted" });
1327
- const widths = tableWidths(width, [
1328
- [28, 7, 8, 9, 9, 11, 9],
1329
- [18, 6, 7, 8, 8, 9, 8]
1330
- ]);
1331
- const header = ["model", "steps", "changes", "model", "endpoint", "cache lost", "avg"];
1332
- lines.push({ text: formatTableRow(header, widths, widths.map((_, index) => index === 0 ? "left" : "right")), tone: HEADER_TONE });
1333
- if (report.rows.length === 0) {
1334
- lines.push({ text: "no comparable consecutive steps in this range", tone: "muted" });
1335
- }
1336
- for (const row of report.rows.slice(0, limit)) {
1337
- const perChange = row.cacheLostEvents > 0 ? row.cacheLost / row.cacheLostEvents : undefined;
1338
- lines.push({
1339
- text: formatTableRow([
1340
- modelCell(row.modelID, row.variant, widths[0]),
1341
- formatCount(row.steps),
1342
- formatCount(row.changes),
1343
- formatCount(row.modelChanges),
1344
- formatCount(row.endpointChanges),
1345
- row.cacheLost > 0 ? `\u2212${formatTokens(row.cacheLost)}` : "\u2013",
1346
- perChange === undefined ? "\u2013" : `\u2212${formatTokens(perChange)}`
1347
- ], widths, widths.map((_, index) => index === 0 ? "left" : "right")),
1348
- tone: row.changes > 0 ? "warning" : "base",
1349
- row: { kind: "model", value: row.modelID, ...row.variant !== undefined ? { variant: row.variant } : {} }
1350
- });
1351
- }
1352
- if (report.rows.length > limit)
1353
- lines.push({ text: `\u2026 ${count(report.rows.length - limit, "more model")}`, tone: "muted" });
1354
- if (report.transitions.length > 0) {
1355
- lines.push({ text: "", tone: "muted" });
1356
- lines.push({ text: "top transitions", tone: HEADER_TONE });
1357
- for (const transition of report.transitions.slice(0, 8)) {
1358
- lines.push({
1359
- text: truncate(` ${padCell(transition.dimension, 9)}${transition.from} \u2192 ${transition.to} \xD7${formatCount(transition.count)}`, width),
1360
- tone: "muted"
1361
- });
1362
- }
1363
- }
1364
- return lines;
1365
- }
1366
1336
  function cacheLines(data, width) {
1367
1337
  const lines = [];
1368
1338
  const total = data.drops.reduce((sum, drop) => sum + drop.tokens, 0);
@@ -1403,14 +1373,14 @@ function cacheLines(data, width) {
1403
1373
  tone: bucket.drops > 0 ? "warning" : "base"
1404
1374
  });
1405
1375
  }
1406
- if (data.gap.endpoints.length > 1) {
1376
+ if (data.gap.providers.length > 1) {
1407
1377
  lines.push({ text: "", tone: "muted" });
1408
- lines.push({ text: "reuse kept, by endpoint", tone: HEADER_TONE });
1409
- const endpointWidths = [26, 8, 9, 9];
1410
- lines.push({ text: formatTableRow(["endpoint", "pairs", "kept", "lost"], endpointWidths, ["left", "right", "right", "right"]), tone: "muted" });
1411
- for (const row of data.gap.endpoints.slice(0, 8)) {
1378
+ lines.push({ text: "reuse kept, by provider", tone: HEADER_TONE });
1379
+ const providerWidths = [26, 8, 9, 9];
1380
+ lines.push({ text: formatTableRow(["provider", "pairs", "kept", "lost"], providerWidths, ["left", "right", "right", "right"]), tone: "muted" });
1381
+ for (const row of data.gap.providers.slice(0, 8)) {
1412
1382
  lines.push({
1413
- text: formatTableRow([row.endpoint, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], endpointWidths, ["left", "right", "right", "right"]),
1383
+ text: formatTableRow([row.provider, formatCount(row.samples), formatPercent(row.retainedRatio, 0), formatTokens(row.lostTokens)], providerWidths, ["left", "right", "right", "right"]),
1414
1384
  tone: "base"
1415
1385
  });
1416
1386
  }
@@ -1443,7 +1413,7 @@ function cacheLines(data, width) {
1443
1413
  }
1444
1414
  return lines;
1445
1415
  }
1446
- function periodLines(rows, width, granularity, limit = 40) {
1416
+ function periodLines(rows, width, granularity, limit = 40, estimates = true) {
1447
1417
  const lines = [];
1448
1418
  const totals = rows.reduce((sum, row) => {
1449
1419
  sum.steps += row.usage.steps;
@@ -1454,8 +1424,9 @@ function periodLines(rows, width, granularity, limit = 40) {
1454
1424
  sum.output += row.usage.output;
1455
1425
  sum.reasoning += row.usage.reasoning;
1456
1426
  sum.cost += row.usage.cost;
1427
+ sum.listCost += row.usage.listCost;
1457
1428
  return sum;
1458
- }, { 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 });
1459
1430
  const overall = usageBuckets(totals);
1460
1431
  lines.push({
1461
1432
  text: `${granularityLabel(granularity)} \xB7 ${count(rows.length, "period")} \xB7 ${count(totals.steps, "step")} \xB7 hit ${formatPercent(overall.hit)}`,
@@ -1464,7 +1435,10 @@ function periodLines(rows, width, granularity, limit = 40) {
1464
1435
  if (rows.length > 1) {
1465
1436
  lines.push({ text: `steps ${sparkline(rows.map((row) => row.usage.steps))}`, tone: "muted" });
1466
1437
  lines.push({ text: `cached ${sparkline(rows.map((row) => row.usage.cached))}`, tone: "muted" });
1467
- 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
+ });
1468
1442
  }
1469
1443
  const withSessions = tableWidths(width, [[12, 7, 7, 11, 10, 7, 9, 9]]).length === 8;
1470
1444
  const widths = withSessions ? [12, 7, 7, 11, 10, 7, 9, 9] : [12, 7, 11, 10, 7, 9, 9];
@@ -1482,7 +1456,7 @@ function periodLines(rows, width, granularity, limit = 40) {
1482
1456
  formatTokens(buckets.cached),
1483
1457
  formatPercent(buckets.hit, 0),
1484
1458
  formatTokens(buckets.output),
1485
- formatCost(buckets.cost)
1459
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1486
1460
  ];
1487
1461
  lines.push({ text: formatTableRow(cells, widths, aligns), tone: "base", row: { kind: "period", value: row.key } });
1488
1462
  }
@@ -1496,7 +1470,7 @@ function periodLines(rows, width, granularity, limit = 40) {
1496
1470
  formatTokens(overall.cached),
1497
1471
  formatPercent(overall.hit, 0),
1498
1472
  formatTokens(overall.output),
1499
- formatCost(overall.cost)
1473
+ formatSpend(overall.cost, estimates ? overall.listCost : 0)
1500
1474
  ], widths, aligns),
1501
1475
  tone: HEADER_TONE
1502
1476
  });
@@ -1504,7 +1478,7 @@ function periodLines(rows, width, granularity, limit = 40) {
1504
1478
  lines.push({ text: "no usage recorded for this range", tone: "muted" });
1505
1479
  return lines;
1506
1480
  }
1507
- function latencyLines(report, width, groups, limit = 12) {
1481
+ function latencyLines(report, width, groups, limit = 12, estimates = true) {
1508
1482
  const lines = [];
1509
1483
  lines.push({
1510
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]),
@@ -1534,7 +1508,16 @@ function latencyLines(report, width, groups, limit = 12) {
1534
1508
  for (const row of groups.slice(0, limit)) {
1535
1509
  const thin = row.count < 5;
1536
1510
  lines.push({
1537
- 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),
1538
1521
  tone: thin ? "muted" : "base",
1539
1522
  row: { kind: "model", value: row.key }
1540
1523
  });
@@ -1545,6 +1528,7 @@ function latencyLines(report, width, groups, limit = 12) {
1545
1528
  }
1546
1529
  function sessionsLines(rows, width, options) {
1547
1530
  const limit = options?.limit ?? 20;
1531
+ const estimates = options?.estimates !== false;
1548
1532
  const widths = [Math.max(18, Math.floor(width * 0.36)), 7, 11, 10, 7, 9, 9];
1549
1533
  const aligns = ["left", "right", "right", "right", "right", "right", "right"];
1550
1534
  const lines = [
@@ -1566,7 +1550,7 @@ function sessionsLines(rows, width, options) {
1566
1550
  formatTokens(buckets.cached),
1567
1551
  formatPercent(buckets.hit, 0),
1568
1552
  formatTokens(buckets.output),
1569
- formatCost(buckets.cost)
1553
+ formatSpend(buckets.cost, estimates ? buckets.listCost : 0)
1570
1554
  ], widths, aligns),
1571
1555
  tone: child ? "muted" : "base",
1572
1556
  row: { kind: "session", value: row.sessionID }
@@ -1578,7 +1562,7 @@ function sessionsLines(rows, width, options) {
1578
1562
  const share = rows.reduce((sum, row) => sum + row.steps, 0);
1579
1563
  lines.push({ text: "", tone: "muted" });
1580
1564
  lines.push({
1581
- 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)}`,
1582
1566
  tone: "muted"
1583
1567
  });
1584
1568
  }
@@ -1608,6 +1592,12 @@ function dbLines(data, width) {
1608
1592
  lines.push({ text: "", tone: "muted" });
1609
1593
  lines.push({ text: "clean up", tone: HEADER_TONE });
1610
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
+ }
1611
1601
  const widths = [10, 13, 10];
1612
1602
  lines.push({ text: formatTableRow(["keep", "prunes", "older than"], widths, ["left", "right", "left"]), tone: "muted" });
1613
1603
  for (const option of data.info.removable) {
@@ -1633,9 +1623,6 @@ function turnStats(turn) {
1633
1623
  providerID: turn.providerID,
1634
1624
  modelID: turn.modelID,
1635
1625
  variant: turn.variant,
1636
- router: turn.router,
1637
- identityChanged: turn.routerChanged,
1638
- affinityKey: undefined,
1639
1626
  providerChanged: turn.providerChanged,
1640
1627
  modelChanged: turn.modelChanged,
1641
1628
  totals: turn.totals,
@@ -1644,8 +1631,7 @@ function turnStats(turn) {
1644
1631
  drops: turn.drops.map((drop) => ({ messageID: drop.messageID, tokens: drop.tokens, prevCached: 0, gapMs: drop.gapMs })),
1645
1632
  cacheDropTokens: turn.drops.reduce((sum, drop) => sum + drop.tokens, 0),
1646
1633
  cacheExpired: turn.drops.length > 0,
1647
- steps: turn.steps,
1648
- stepIDs: []
1634
+ steps: turn.steps
1649
1635
  };
1650
1636
  }
1651
1637
  function turnsLines(rows, width, options) {
@@ -1664,7 +1650,7 @@ function turnsLines(rows, width, options) {
1664
1650
  const title = showSession ? `${truncate(options.sessionTitles.get(turn.sessionID) ?? turn.sessionID, 18)} ` : "";
1665
1651
  lines.push({
1666
1652
  text: truncate(`${title}${line}`, width),
1667
- tone: turn.drops.length > 0 || turn.routerChanged ? "warning" : "base",
1653
+ tone: turn.drops.length > 0 || turn.providerChanged ? "warning" : "base",
1668
1654
  row: { kind: "turn", value: turn.sessionID }
1669
1655
  });
1670
1656
  }
@@ -1672,7 +1658,7 @@ function turnsLines(rows, width, options) {
1672
1658
  lines.push({ text: "no finished turns for this range", tone: "muted" });
1673
1659
  return lines;
1674
1660
  }
1675
- function sessionSummaryLines(usage, budget = 34) {
1661
+ function sessionSummaryLines(usage, budget = 34, estimates = true) {
1676
1662
  const buckets = usageBuckets(usage);
1677
1663
  const steps = formatCount(buckets.steps);
1678
1664
  const input = formatTokens(buckets.input);
@@ -1680,7 +1666,7 @@ function sessionSummaryLines(usage, budget = 34) {
1680
1666
  const out = formatTokens(buckets.output);
1681
1667
  const hit = formatPercent(buckets.hit);
1682
1668
  const tps = formatTpsCompact(usage.tps);
1683
- const cost = formatCost(buckets.cost);
1669
+ const cost = (estimates ? formatMoney(buckets.cost, buckets.listCost) : undefined) ?? formatCost(buckets.cost);
1684
1670
  const first = [
1685
1671
  ` ${steps} steps \xB7 in ${input}`,
1686
1672
  ` ${steps} steps`
@@ -1706,14 +1692,14 @@ function sidebarLines(rows, options) {
1706
1692
  const budget = options?.budget ?? 34;
1707
1693
  const labels = { input: options?.labels?.input ?? "in", output: options?.labels?.output ?? "out" };
1708
1694
  const lines = [];
1709
- for (const turn of rows) {
1695
+ for (const [index, turn] of rows.entries()) {
1710
1696
  const clock = turn.endAt !== undefined ? formatClock(turn.endAt).slice(0, 5) : "--:--";
1711
- const identity = turn.router ?? (turn.providerID !== undefined && turn.modelID !== undefined ? `${turn.providerID}/${turn.modelID}` : "unknown");
1697
+ const provider = turn.providerID ?? "unknown";
1712
1698
  const display = displayTotals(turn.latest);
1713
1699
  const input = formatTokens(display.input);
1714
1700
  const prompt = formatTokens(display.prompt);
1715
1701
  const output = formatTokens(display.output);
1716
- 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);
1717
1703
  const hit = formatPercent(display.prompt > 0 ? display.cached / display.prompt : undefined).replace(/\.0%$/, "%");
1718
1704
  const tps = turn.tps === undefined ? undefined : formatTpsCompact(turn.tps);
1719
1705
  const suffix = turn.drops.length > 0 ? " \xB7 \u26A0" : "";
@@ -1728,7 +1714,12 @@ function sidebarLines(rows, options) {
1728
1714
  ` ${tps === undefined ? "" : `${tps} \xB7 `}${cost}${suffix}`,
1729
1715
  ` hit ${hit}${suffix}`
1730
1716
  ];
1731
- lines.push({ text: truncate(`${clock} ${identity}`, budget), tone: turn.routerChanged ? "warning" : "base" });
1717
+ lines.push({ text: truncate(`${clock} ${provider}`, budget), tone: turn.providerChanged ? "warning" : "base" });
1718
+ const edge = index === 0 || index === rows.length - 1;
1719
+ if (edge || turn.modelChanged || turn.providerChanged) {
1720
+ const model = turn.modelID === undefined ? "unknown" : `${turn.modelID}${turn.variant === undefined ? "" : ` ${turn.variant}`}`;
1721
+ lines.push({ text: truncate(` ${model}`, budget), tone: "muted" });
1722
+ }
1732
1723
  lines.push({
1733
1724
  text: truncate(volumes.find((text) => text.length <= budget) ?? volumes[volumes.length - 1], budget),
1734
1725
  tone: "muted"
@@ -1777,11 +1768,12 @@ function groupBy(items, key) {
1777
1768
  return groups;
1778
1769
  }
1779
1770
  var STEP_COLUMNS = `message_id AS messageID, session_id AS sessionID, provider_id AS providerID,
1780
- model_id AS modelID, variant, router,
1771
+ model_id AS modelID, variant,
1781
1772
  COALESCE(input_tokens, 0) AS input, COALESCE(cache_read, 0) AS cached, COALESCE(cache_write, 0) AS cacheWrite,
1782
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,
1783
1775
  created_at AS createdAt, streamed_at AS streamedAt, completed_at AS completedAt, ${STEP_AT} AS at`;
1784
- var STEP_OPTIONAL = ["providerID", "modelID", "variant", "router", "createdAt", "streamedAt", "completedAt"];
1776
+ var STEP_OPTIONAL = ["providerID", "modelID", "variant", "createdAt", "streamedAt", "completedAt"];
1785
1777
  var PAIR_COLUMNS = STEP_COLUMNS.replace("COALESCE(output_tokens, 0) AS output, COALESCE(reasoning_tokens, 0) AS reasoning, ", "");
1786
1778
  function stepRows(db, options) {
1787
1779
  const filter = buildWhere(options?.range, options?.filters);
@@ -1839,7 +1831,7 @@ function pairsOf(rows) {
1839
1831
  return pairs;
1840
1832
  }
1841
1833
  function usageOf(steps) {
1842
- 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 };
1843
1835
  for (const step of steps) {
1844
1836
  usage.steps += 1;
1845
1837
  usage.input += step.input;
@@ -1848,6 +1840,7 @@ function usageOf(steps) {
1848
1840
  usage.output += step.output;
1849
1841
  usage.reasoning += step.reasoning;
1850
1842
  usage.cost += step.cost;
1843
+ usage.listCost += step.listCost;
1851
1844
  }
1852
1845
  return usage;
1853
1846
  }
@@ -1855,9 +1848,8 @@ function coverageOf(db, options) {
1855
1848
  const filter = buildWhere(options?.range, options?.filters);
1856
1849
  const row = db.query(`SELECT COUNT(*) AS steps,
1857
1850
  COUNT(DISTINCT CASE WHEN model_id IS NOT NULL THEN model_id || '#' || COALESCE(variant, '') END) AS models,
1858
- COUNT(DISTINCT router) AS endpoints,
1851
+ COUNT(DISTINCT provider_id) AS providers,
1859
1852
  COALESCE(SUM(CASE WHEN model_id IS NULL THEN 1 ELSE 0 END), 0) AS missingModel,
1860
- COALESCE(SUM(CASE WHEN router IS NULL THEN 1 ELSE 0 END), 0) AS missingEndpoint,
1861
1853
  COALESCE(SUM(CASE WHEN completed_at IS NOT NULL OR finish IS NOT NULL THEN 0 ELSE 1 END), 0) AS unsettled,
1862
1854
  COALESCE(SUM(CASE WHEN (output_tokens + reasoning_tokens) > 0 AND created_at IS NOT NULL AND streamed_at IS NOT NULL AND streamed_at > created_at THEN 0 ELSE 1 END), 0) AS missingTps,
1863
1855
  MIN(${STEP_AT}) AS firstAt,
@@ -1866,9 +1858,8 @@ function coverageOf(db, options) {
1866
1858
  return {
1867
1859
  steps: row.steps,
1868
1860
  models: row.models,
1869
- endpoints: row.endpoints,
1861
+ providers: row.providers,
1870
1862
  missingModel: row.missingModel,
1871
- missingEndpoint: row.missingEndpoint,
1872
1863
  unsettled: row.unsettled,
1873
1864
  missingTps: row.missingTps,
1874
1865
  firstAt: row.firstAt ?? undefined,
@@ -1904,7 +1895,7 @@ function latencyOf(rows) {
1904
1895
  return { wall: latencyStats(wall), stream: latencyStats(stream), tps: latencyStats(tps) };
1905
1896
  }
1906
1897
  function latencyGroupsOf(rows, by) {
1907
- const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : by === "provider" ? step.providerID ?? "(unknown)" : step.router ?? "(unknown)";
1898
+ const key = (step) => by === "model" ? modelKey(step.modelID ?? "(unknown)", step.variant) : step.providerID ?? "(unknown)";
1908
1899
  const groups = [];
1909
1900
  for (const [group, steps] of groupBy(rows, key)) {
1910
1901
  const wall = [];
@@ -1942,9 +1933,9 @@ function cacheStatsOfSteps(steps) {
1942
1933
  input += step.input;
1943
1934
  cached += step.cached;
1944
1935
  cacheWrite += step.cacheWrite;
1945
- const prompt2 = step.input + step.cached + step.cacheWrite;
1946
- if (prompt2 > 0)
1947
- ratios.push(step.cached / prompt2);
1936
+ const prompt = step.input + step.cached + step.cacheWrite;
1937
+ if (prompt > 0)
1938
+ ratios.push(step.cached / prompt);
1948
1939
  }
1949
1940
  const prompt = input + cached + cacheWrite;
1950
1941
  return { steps: steps.length, input, cached, cacheWrite, prompt, hit: prompt > 0 ? cached / prompt : undefined, hitP50: percentile(ratios, 50) };
@@ -1961,17 +1952,8 @@ function cacheStatsByModel(rows) {
1961
1952
  }
1962
1953
  return out.sort((left, right) => right.cache.cached - left.cache.cached || left.modelID.localeCompare(right.modelID));
1963
1954
  }
1964
- function noteTransition(map, dimension, from, to) {
1965
- const key = `${dimension}\x00${from}\x00${to}`;
1966
- const entry = map.get(key);
1967
- if (entry !== undefined)
1968
- entry.count += 1;
1969
- else
1970
- map.set(key, { dimension, from, to, count: 1 });
1971
- }
1972
- function affinityOf(rows) {
1955
+ function switchesOf(rows) {
1973
1956
  const perModel = new Map;
1974
- const transitions = new Map;
1975
1957
  const totals = { pairs: 0, changes: 0, cacheLost: 0, cacheLostEvents: 0 };
1976
1958
  for (const { previous, current } of pairsOf(rows)) {
1977
1959
  if (previous.modelID === undefined || current.modelID === undefined)
@@ -1984,7 +1966,7 @@ function affinityOf(rows) {
1984
1966
  pairs: 0,
1985
1967
  changes: 0,
1986
1968
  modelChanges: 0,
1987
- endpointChanges: 0,
1969
+ providerChanges: 0,
1988
1970
  cacheLost: 0,
1989
1971
  cacheLostEvents: 0
1990
1972
  };
@@ -1992,19 +1974,15 @@ function affinityOf(rows) {
1992
1974
  row.pairs += 1;
1993
1975
  totals.pairs += 1;
1994
1976
  const modelChanged = key !== modelKey(previous.modelID, previous.variant);
1995
- const endpointChanged = previous.router !== undefined && current.router !== undefined && previous.router !== current.router;
1996
- if (modelChanged) {
1977
+ const providerChanged = previous.providerID !== undefined && current.providerID !== undefined && previous.providerID !== current.providerID;
1978
+ if (modelChanged)
1997
1979
  row.modelChanges += 1;
1998
- noteTransition(transitions, "model", modelLabel(previous.modelID, previous.variant), modelLabel(current.modelID, current.variant));
1999
- }
2000
- if (endpointChanged) {
2001
- row.endpointChanges += 1;
2002
- noteTransition(transitions, "endpoint", previous.router, current.router);
2003
- }
2004
- if (modelChanged || endpointChanged) {
1980
+ if (providerChanged)
1981
+ row.providerChanges += 1;
1982
+ if (modelChanged || providerChanged) {
2005
1983
  row.changes += 1;
2006
1984
  totals.changes += 1;
2007
- const lost = cacheDrop(message(previous), message(current));
1985
+ const lost = cacheDrop(message(previous), message(current), "model");
2008
1986
  if (lost !== undefined) {
2009
1987
  row.cacheLost += lost;
2010
1988
  row.cacheLostEvents += 1;
@@ -2016,7 +1994,6 @@ function affinityOf(rows) {
2016
1994
  }
2017
1995
  return {
2018
1996
  rows: [...perModel.values()].sort((left, right) => right.changes - left.changes || right.steps - left.steps || left.modelID.localeCompare(right.modelID)),
2019
- transitions: [...transitions.values()].sort((left, right) => right.count - left.count || left.dimension.localeCompare(right.dimension)),
2020
1997
  totals
2021
1998
  };
2022
1999
  }
@@ -2034,13 +2011,15 @@ function bucketFor(gapMs) {
2034
2011
  }
2035
2012
  function gapReportOf(rows) {
2036
2013
  const buckets = GAP_BUCKETS.map(([label]) => ({ label, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined }));
2037
- const endpoints = new Map;
2014
+ const providers = new Map;
2038
2015
  let samples = 0;
2039
2016
  for (const { previous, current } of pairsOf(rows)) {
2040
2017
  if (previous.modelID === undefined || current.modelID === undefined)
2041
2018
  continue;
2042
2019
  if (modelKey(previous.modelID, previous.variant) !== modelKey(current.modelID, current.variant))
2043
2020
  continue;
2021
+ if ((previous.providerID ?? "") !== (current.providerID ?? ""))
2022
+ continue;
2044
2023
  const gap = stepGap(message(previous), message(current));
2045
2024
  if (gap === undefined)
2046
2025
  continue;
@@ -2054,8 +2033,8 @@ function gapReportOf(rows) {
2054
2033
  bucket.drops += 1;
2055
2034
  bucket.lostTokens += lost;
2056
2035
  }
2057
- const endpoint = current.router ?? previous.router ?? "(unknown)";
2058
- const row = endpoints.get(endpoint) ?? { endpoint, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined };
2036
+ const provider = current.providerID ?? previous.providerID ?? "(unknown)";
2037
+ const row = providers.get(provider) ?? { provider, samples: 0, retained: 0, drops: 0, lostTokens: 0, retainedRatio: undefined };
2059
2038
  row.samples += 1;
2060
2039
  if (lost === undefined)
2061
2040
  row.retained += 1;
@@ -2063,15 +2042,15 @@ function gapReportOf(rows) {
2063
2042
  row.drops += 1;
2064
2043
  row.lostTokens += lost;
2065
2044
  }
2066
- endpoints.set(endpoint, row);
2045
+ providers.set(provider, row);
2067
2046
  }
2068
2047
  for (const bucket of buckets)
2069
2048
  bucket.retainedRatio = bucket.samples > 0 ? bucket.retained / bucket.samples : undefined;
2070
- for (const row of endpoints.values())
2049
+ for (const row of providers.values())
2071
2050
  row.retainedRatio = row.samples > 0 ? row.retained / row.samples : undefined;
2072
2051
  return {
2073
2052
  buckets,
2074
- endpoints: [...endpoints.values()].sort((left, right) => right.samples - left.samples || left.endpoint.localeCompare(right.endpoint)),
2053
+ providers: [...providers.values()].sort((left, right) => right.samples - left.samples || left.provider.localeCompare(right.provider)),
2075
2054
  samples
2076
2055
  };
2077
2056
  }
@@ -2109,7 +2088,7 @@ function cacheDropsOf(db, rows, options) {
2109
2088
  const ttlHint = options?.ttlHintMs ?? DEFAULT_TTL_HINT_MS;
2110
2089
  const losses = [];
2111
2090
  for (const { previous, current } of pairsOf(rows)) {
2112
- const tokens = cacheDrop(message(previous), message(current));
2091
+ const tokens = cacheDrop(message(previous), message(current), "model");
2113
2092
  if (tokens === undefined)
2114
2093
  continue;
2115
2094
  losses.push({ previous, current, tokens, gapMs: stepGap(message(previous), message(current)) });
@@ -2146,7 +2125,7 @@ function cacheDropsOf(db, rows, options) {
2146
2125
  };
2147
2126
  }).sort((left, right) => left.at - right.at);
2148
2127
  }
2149
- function endpointValues(steps) {
2128
+ function groupValues(steps) {
2150
2129
  const wall = [];
2151
2130
  const tps = [];
2152
2131
  for (const step of steps) {
@@ -2158,12 +2137,12 @@ function endpointValues(steps) {
2158
2137
  }
2159
2138
  return { cache: cacheStatsOfSteps(steps), tps: latencyStats(tps).p50, wall: latencyStats(wall).p50 };
2160
2139
  }
2161
- function endpointOf(steps, models2) {
2162
- const values = endpointValues(steps);
2140
+ function providerOf(steps, models) {
2141
+ const values = groupValues(steps);
2163
2142
  const times = steps.map((step) => step.at);
2164
2143
  return {
2165
- endpoint: steps[0].router,
2166
- models: models2.split("\x00"),
2144
+ provider: steps[0].providerID,
2145
+ models: models.split("\x00"),
2167
2146
  share: 0,
2168
2147
  usage: usageOf(steps),
2169
2148
  cache: values.cache,
@@ -2174,21 +2153,21 @@ function endpointOf(steps, models2) {
2174
2153
  };
2175
2154
  }
2176
2155
  var modelNames = (steps) => [...new Set(steps.map((step) => modelKey(step.modelID ?? "(unknown)", step.variant)))].map((key) => modelLabel(key.slice(0, key.indexOf("#")), key.slice(key.indexOf("#") + 1) || undefined)).join("\x00");
2177
- function endpointSummaryOf(rows) {
2156
+ function providerSummaryOf(rows) {
2178
2157
  const out = [];
2179
- for (const steps of groupBy(rows, (step) => step.router ?? "").values()) {
2180
- const summary = endpointOf(steps, modelNames(steps));
2158
+ for (const steps of groupBy(rows, (step) => step.providerID ?? "").values()) {
2159
+ const summary = providerOf(steps, modelNames(steps));
2181
2160
  out.push({ ...summary, share: rows.length === 0 ? 0 : steps.length / rows.length });
2182
2161
  }
2183
- return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.endpoint ?? "").localeCompare(right.endpoint ?? ""));
2162
+ return out.sort((left, right) => right.usage.steps - left.usage.steps || (left.provider ?? "").localeCompare(right.provider ?? ""));
2184
2163
  }
2185
- function endpointBreakdownOf(rows) {
2164
+ function providerBreakdownOf(rows) {
2186
2165
  const out = [];
2187
2166
  for (const [model, modelRows] of groupBy(rows, (step) => modelKey(step.modelID ?? "(unknown)", step.variant))) {
2188
- for (const steps of groupBy(modelRows, (step) => step.router ?? "").values()) {
2167
+ for (const steps of groupBy(modelRows, (step) => step.providerID ?? "").values()) {
2189
2168
  const [modelID, variant] = [model.slice(0, model.indexOf("#")), model.slice(model.indexOf("#") + 1)];
2190
2169
  out.push({
2191
- ...endpointOf(steps, modelNames(steps)),
2170
+ ...providerOf(steps, modelNames(steps)),
2192
2171
  modelID,
2193
2172
  variant: variant === "" ? undefined : variant,
2194
2173
  share: steps.length / modelRows.length
@@ -2210,8 +2189,8 @@ function periodStart(at, granularity) {
2210
2189
  const date = new Date(at);
2211
2190
  const pad = (value) => String(value).padStart(2, "0");
2212
2191
  if (granularity === "month") {
2213
- const start2 = new Date(date.getFullYear(), date.getMonth(), 1);
2214
- return { key: `${start2.getFullYear()}-${pad(start2.getMonth() + 1)}`, label: `${start2.getFullYear()}-${pad(start2.getMonth() + 1)}`, start: start2.getTime() };
2192
+ const start = new Date(date.getFullYear(), date.getMonth(), 1);
2193
+ return { key: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, label: `${start.getFullYear()}-${pad(start.getMonth() + 1)}`, start: start.getTime() };
2215
2194
  }
2216
2195
  if (granularity === "week") {
2217
2196
  const { year, week, monday } = isoWeek(date);
@@ -2241,8 +2220,7 @@ function periodsOf(rows, granularity) {
2241
2220
  // src/panel-build.ts
2242
2221
  var SORT_KEYS = {
2243
2222
  models: ["steps", "cached", "hit", "out", "cost"],
2244
- endpoints: ["steps", "cached", "hit", "cost", "share", "tps"],
2245
- affinity: ["changes", "lost", "steps"],
2223
+ providers: ["steps", "cached", "hit", "cost", "share", "tps"],
2246
2224
  latency: ["n", "tps", "wall"],
2247
2225
  sessions: ["last", "steps", "cached", "cost"],
2248
2226
  turns: ["time", "cost", "tokens"]
@@ -2271,8 +2249,6 @@ function detailLabel(row) {
2271
2249
  return `session ${row.value}`;
2272
2250
  case "period":
2273
2251
  return `period ${row.value}`;
2274
- case "endpoint":
2275
- return `endpoint ${row.value}`;
2276
2252
  case "provider":
2277
2253
  return `provider ${row.value}`;
2278
2254
  case "prune":
@@ -2283,17 +2259,18 @@ function buildPanel(request) {
2283
2259
  try {
2284
2260
  return build(request);
2285
2261
  } catch (error) {
2286
- const message2 = error instanceof Error ? error.message : String(error);
2287
- return [{ text: `stats query failed: ${message2}`, tone: "warning" }];
2262
+ const message = error instanceof Error ? error.message : String(error);
2263
+ return [{ text: `stats query failed: ${message}`, tone: "warning" }];
2288
2264
  }
2289
2265
  }
2290
2266
  function build(request) {
2291
2267
  const { db, view, now, sessionStart, width } = request;
2268
+ const estimates = request.estimates !== false;
2292
2269
  const scoped = request.range === "session" && request.sessionID !== "";
2293
2270
  const range = scoped ? undefined : request.range === "session" ? sessionStart === undefined ? undefined : { from: sessionStart } : rangeForRequest(request.range, now);
2294
2271
  const filters = scoped ? { ...request.filters, sessionID: request.sessionID } : request.filters;
2295
2272
  if (request.detail !== undefined)
2296
- return buildDetail(request, range, filters);
2273
+ return buildDetail(request, range, filters, estimates);
2297
2274
  switch (view) {
2298
2275
  case "overview": {
2299
2276
  const usage = overview(db, range, filters);
@@ -2306,22 +2283,21 @@ function build(request) {
2306
2283
  ...children.length > 0 ? { subagents: children } : {},
2307
2284
  range: request.range,
2308
2285
  activity: activityOf(db, range, now),
2309
- coverage: coverageOf(db, { range, filters })
2286
+ coverage: coverageOf(db, { range, filters }),
2287
+ estimates
2310
2288
  }, width);
2311
2289
  }
2312
2290
  case "models": {
2313
- const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc);
2291
+ const rows = sortModels(models(db, range, filters), request.sort, request.sortDesc, estimates);
2314
2292
  const pairs = cachePairs(db, { range, filters });
2315
- const affinity = affinityOf(pairs);
2293
+ const switches = switchesOf(pairs);
2316
2294
  return modelsLines(rows, width, {
2317
2295
  cache: cacheByModel(pairs),
2318
- changes: new Map(affinity.rows.map((row) => [modelKey(row.modelID, row.variant), row.changes]))
2319
- }, 40);
2296
+ switches: switchesByModel(switches.rows)
2297
+ }, 40, estimates);
2320
2298
  }
2321
- case "endpoints":
2322
- return endpointSummaryLines(sortEndpoints(endpointSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc), width, 40);
2323
- case "affinity":
2324
- return affinityLines(sortAffinity(affinityOf(cachePairs(db, { range, filters })), request.sort, request.sortDesc), width, 40);
2299
+ case "providers":
2300
+ return providerSummaryLines(sortProviders(providerSummaryOf(stepRows(db, { range, filters })), request.sort, request.sortDesc, estimates), width, 40, estimates);
2325
2301
  case "cache": {
2326
2302
  const pairs = cachePairs(db, { range, filters });
2327
2303
  return cacheLines({
@@ -2332,27 +2308,32 @@ function build(request) {
2332
2308
  }, width);
2333
2309
  }
2334
2310
  case "periods":
2335
- 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);
2336
2312
  case "latency": {
2337
2313
  const timings = timingRows(db, { range, filters });
2338
- const by = filters.modelID !== undefined ? "endpoint" : "model";
2339
- return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14);
2314
+ const by = filters.modelID !== undefined ? "provider" : "model";
2315
+ return latencyLines(latencyOf(timings), width, sortLatency(latencyGroupsOf(timings, by), request.sort, request.sortDesc), 14, estimates);
2340
2316
  }
2341
2317
  case "sessions": {
2342
- 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);
2343
2319
  const child = rows.filter((row) => row.parentID !== undefined && rows.some((parent) => parent.sessionID === row.parentID));
2344
2320
  return sessionsLines(rows, width, {
2345
2321
  limit: 20,
2346
- 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
+ }
2347
2328
  });
2348
2329
  }
2349
2330
  case "db":
2350
- 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);
2351
2332
  case "turns": {
2352
2333
  const sessionID = request.turnsScope === "session" ? request.sessionID : undefined;
2353
- 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);
2354
2335
  const titles = request.turnsScope === "all" ? new Map(sessions(db, { range, filters, limit: 200 }).map((row) => [row.sessionID, row.title ?? row.sessionID])) : undefined;
2355
- return turnsLines(rows.slice(0, 60), width, { ...request.format, sessionTitles: titles });
2336
+ return turnsLines(rows.slice(0, 60), width, { ...request.format, estimates, sessionTitles: titles });
2356
2337
  }
2357
2338
  }
2358
2339
  }
@@ -2371,7 +2352,7 @@ function rangeForRequest(key, now) {
2371
2352
  return;
2372
2353
  }
2373
2354
  }
2374
- function buildDetail(request, range, filters) {
2355
+ function buildDetail(request, range, filters, estimates) {
2375
2356
  const row = request.detail;
2376
2357
  const db = request.db;
2377
2358
  const width = request.width;
@@ -2380,6 +2361,7 @@ function buildDetail(request, range, filters) {
2380
2361
  if (row.kind === "model") {
2381
2362
  const scoped = { ...filters, modelKey: modelKey(row.value, row.variant) };
2382
2363
  const stats = cacheStatsOf(db, { range, filters: scoped });
2364
+ const steps = stepRows(db, { range, filters: scoped });
2383
2365
  return [
2384
2366
  head,
2385
2367
  {
@@ -2387,19 +2369,19 @@ function buildDetail(request, range, filters) {
2387
2369
  tone: "muted"
2388
2370
  },
2389
2371
  { text: "", tone: "muted" },
2390
- ...endpointsLines(endpointBreakdownOf(stepRows(db, { range, filters: scoped })), width, 40),
2372
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2391
2373
  { text: "", tone: "muted" },
2392
- ...affinityLines(affinityOf(cachePairs(db, { range, filters: scoped })), width, 10),
2374
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "provider"), 14, estimates),
2393
2375
  { text: "", tone: "muted" },
2394
2376
  back
2395
2377
  ];
2396
2378
  }
2397
2379
  if (row.kind === "session" || row.kind === "turn") {
2398
2380
  const rows = turns(db, { sessionID: row.value, limit: 80 });
2399
- 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];
2400
2382
  }
2401
- if (row.kind === "endpoint") {
2402
- const scoped = { ...filters, router: row.value };
2383
+ if (row.kind === "provider") {
2384
+ const scoped = { ...filters, provider: row.value };
2403
2385
  const steps = stepRows(db, { range, filters: scoped });
2404
2386
  const stats = cacheStatsOf(db, { range, filters: scoped });
2405
2387
  return [
@@ -2409,9 +2391,9 @@ function buildDetail(request, range, filters) {
2409
2391
  tone: "muted"
2410
2392
  },
2411
2393
  { text: "", tone: "muted" },
2412
- ...endpointsLines(endpointBreakdownOf(steps), width, 40),
2394
+ ...providerLines(providerBreakdownOf(steps), width, 40, estimates),
2413
2395
  { text: "", tone: "muted" },
2414
- ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14),
2396
+ ...latencyLines(latencyOf(steps), width, latencyGroupsOf(steps, "model"), 14, estimates),
2415
2397
  { text: "", tone: "muted" },
2416
2398
  back
2417
2399
  ];
@@ -2423,7 +2405,7 @@ function buildDetail(request, range, filters) {
2423
2405
  head,
2424
2406
  { text: `${formatCount(period?.steps ?? 0)} steps`, tone: "muted" },
2425
2407
  { text: "", tone: "muted" },
2426
- ...endpointSummaryLines(endpointSummaryOf(stepRows(db, { range, filters })), width, 40),
2408
+ ...providerSummaryLines(providerSummaryOf(stepRows(db, { range, filters })), width, 40, estimates),
2427
2409
  { text: "", tone: "muted" },
2428
2410
  back
2429
2411
  ];
@@ -2433,7 +2415,7 @@ function buildDetail(request, range, filters) {
2433
2415
  function percent(value) {
2434
2416
  return value === undefined ? "\u2013" : `${(value * 100).toFixed(1)}%`;
2435
2417
  }
2436
- function sortModels(rows, sort, desc) {
2418
+ function sortModels(rows, sort, desc, estimates = true) {
2437
2419
  const sign = desc ? -1 : 1;
2438
2420
  const pick = (model) => {
2439
2421
  if (sort === "cached")
@@ -2441,12 +2423,12 @@ function sortModels(rows, sort, desc) {
2441
2423
  if (sort === "out")
2442
2424
  return model.totals.output;
2443
2425
  if (sort === "cost")
2444
- return model.totals.cost;
2426
+ return estimates ? spend(model.totals) : model.totals.cost;
2445
2427
  return model.totals.steps;
2446
2428
  };
2447
2429
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2448
2430
  }
2449
- function sortEndpoints(rows, sort, desc) {
2431
+ function sortProviders(rows, sort, desc, estimates = true) {
2450
2432
  const sign = desc ? -1 : 1;
2451
2433
  const pick = (row) => {
2452
2434
  if (sort === "cached")
@@ -2454,7 +2436,7 @@ function sortEndpoints(rows, sort, desc) {
2454
2436
  if (sort === "hit")
2455
2437
  return row.cache.hit ?? -1;
2456
2438
  if (sort === "cost")
2457
- return row.usage.cost;
2439
+ return estimates ? spend(row.usage) : row.usage.cost;
2458
2440
  if (sort === "share")
2459
2441
  return row.share;
2460
2442
  if (sort === "tps")
@@ -2463,17 +2445,6 @@ function sortEndpoints(rows, sort, desc) {
2463
2445
  };
2464
2446
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2465
2447
  }
2466
- function sortAffinity(report, sort, desc) {
2467
- const sign = desc ? -1 : 1;
2468
- const pick = (row) => {
2469
- if (sort === "lost")
2470
- return row.cacheLost;
2471
- if (sort === "steps")
2472
- return row.steps;
2473
- return row.changes;
2474
- };
2475
- return { ...report, rows: [...report.rows].sort((left, right) => sign * (pick(right) - pick(left))) };
2476
- }
2477
2448
  function sortLatency(rows, sort, desc) {
2478
2449
  const sign = desc ? -1 : 1;
2479
2450
  const pick = (row) => {
@@ -2485,7 +2456,7 @@ function sortLatency(rows, sort, desc) {
2485
2456
  };
2486
2457
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2487
2458
  }
2488
- function sortSessions(rows, sort, desc) {
2459
+ function sortSessions(rows, sort, desc, estimates = true) {
2489
2460
  const sign = desc ? -1 : 1;
2490
2461
  const pick = (row) => {
2491
2462
  if (sort === "steps")
@@ -2493,16 +2464,16 @@ function sortSessions(rows, sort, desc) {
2493
2464
  if (sort === "cached")
2494
2465
  return row.cached;
2495
2466
  if (sort === "cost")
2496
- return row.cost;
2467
+ return estimates ? spend(row) : row.cost;
2497
2468
  return row.lastAt ?? 0;
2498
2469
  };
2499
2470
  return [...rows].sort((left, right) => sign * (pick(right) - pick(left)));
2500
2471
  }
2501
- function sortTurns(rows, sort, desc) {
2472
+ function sortTurns(rows, sort, desc, estimates = true) {
2502
2473
  const sign = desc ? -1 : 1;
2503
2474
  const pick = (row) => {
2504
2475
  if (sort === "cost")
2505
- return row.totals.cost;
2476
+ return estimates ? spend(row.totals) : row.totals.cost;
2506
2477
  if (sort === "tokens")
2507
2478
  return row.totals.cached + row.totals.input + row.totals.output;
2508
2479
  return row.endAt ?? 0;
@@ -2516,6 +2487,9 @@ function cacheByModel(pairs) {
2516
2487
  }
2517
2488
  return map;
2518
2489
  }
2490
+ function switchesByModel(rows) {
2491
+ return new Map(rows.map((row) => [modelKey(row.modelID, row.variant), row]));
2492
+ }
2519
2493
  function topCacheModels(pairs) {
2520
2494
  return cacheStatsByModel(pairs).slice(0, 10).map((row) => ({ usage: { modelID: row.modelID, variant: row.variant }, cache: row.cache }));
2521
2495
  }
@@ -2590,7 +2564,7 @@ function ensureRegularFile(path) {
2590
2564
  }
2591
2565
 
2592
2566
  // src/stats/db.ts
2593
- var SCHEMA_VERSION = 8;
2567
+ var SCHEMA_VERSION = 10;
2594
2568
  var LABEL_LIMIT = 4 * TEXT_LIMIT;
2595
2569
  var SCHEMA = `
2596
2570
  CREATE TABLE IF NOT EXISTS meta (
@@ -2628,17 +2602,16 @@ CREATE TABLE IF NOT EXISTS steps (
2628
2602
  cache_read INTEGER NOT NULL DEFAULT 0,
2629
2603
  cache_write INTEGER NOT NULL DEFAULT 0,
2630
2604
  cost REAL NOT NULL DEFAULT 0,
2605
+ list_cost REAL,
2631
2606
  created_at INTEGER,
2632
2607
  streamed_at INTEGER,
2633
2608
  completed_at INTEGER,
2634
2609
  finish TEXT,
2635
- router TEXT,
2636
2610
  recorded_at INTEGER NOT NULL
2637
2611
  );
2638
2612
  CREATE INDEX IF NOT EXISTS steps_session ON steps(session_id, created_at);
2639
2613
  CREATE INDEX IF NOT EXISTS steps_model ON steps(provider_id, model_id, variant);
2640
2614
  CREATE INDEX IF NOT EXISTS steps_completed ON steps(completed_at);
2641
- CREATE INDEX IF NOT EXISTS steps_router ON steps(router);
2642
2615
  -- Every range filter and every ordering compares the step's own clock, which
2643
2616
  -- falls back to the recording time for a step that was already in flight when
2644
2617
  -- the plugin loaded. The index has to cover that expression, or every ranged
@@ -2669,10 +2642,7 @@ function jsonText(value) {
2669
2642
  return null;
2670
2643
  }
2671
2644
  }
2672
- var MIGRATIONS = [
2673
- ["router", "ALTER TABLE steps ADD COLUMN router TEXT"]
2674
- ];
2675
- var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps"];
2645
+ var REMOVED_COLUMNS = ["provider_state", "upstream", "upstream_source", "upstream_model", "tps", "router"];
2676
2646
  var REMOVED_EVENT_KINDS = ["execution", "step-failed", "model-selected", "usage-recorded"];
2677
2647
  function dropUnused(db) {
2678
2648
  const objects = db.query("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'index')").all();
@@ -2682,6 +2652,8 @@ function dropUnused(db) {
2682
2652
  db.exec("DROP TABLE http_responses");
2683
2653
  if (indexes.has("steps_upstream"))
2684
2654
  db.exec("DROP INDEX steps_upstream");
2655
+ if (indexes.has("steps_router"))
2656
+ db.exec("DROP INDEX steps_router");
2685
2657
  const columns = new Set(db.query("PRAGMA table_info(steps)").all().map((column) => column.name));
2686
2658
  for (const name of REMOVED_COLUMNS) {
2687
2659
  if (columns.has(name))
@@ -2691,30 +2663,16 @@ function dropUnused(db) {
2691
2663
  const kinds = REMOVED_EVENT_KINDS.map((kind) => `'${kind}'`).join(", ");
2692
2664
  db.exec(`DELETE FROM events WHERE kind IN (${kinds})`);
2693
2665
  }
2694
- db.exec("UPDATE steps SET router = NULL WHERE router IN ('opencode', 'openrouter', 'vercel-ai-gateway')");
2695
2666
  }
2696
- function schemaVersion(db) {
2697
- const row = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
2698
- const parsed = row === null ? Number.NaN : Number.parseInt(row.value, 10);
2699
- return Number.isFinite(parsed) ? parsed : 0;
2700
- }
2701
- function normalizeRouters(db) {
2702
- db.exec("UPDATE steps SET router = lower(router) WHERE router IS NOT NULL AND router <> lower(router)");
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
+ }
2703
2672
  }
2704
2673
  function migrate(db) {
2705
- const version = schemaVersion(db);
2706
- const steps = db.query("PRAGMA table_info(steps)").all();
2707
- const existing = new Set(steps.map((column) => column.name));
2708
- for (const [name, statement, backfill] of MIGRATIONS) {
2709
- if (existing.has(name))
2710
- continue;
2711
- db.exec(statement);
2712
- if (backfill !== undefined)
2713
- db.exec(backfill);
2714
- }
2715
2674
  dropUnused(db);
2716
- if (version < 7)
2717
- normalizeRouters(db);
2675
+ addMissing(db);
2718
2676
  }
2719
2677
  var POSIX = process.platform !== "win32";
2720
2678
  function hardenDirectory(path) {
@@ -2777,12 +2735,12 @@ function openStatsDbWrite(path) {
2777
2735
  function recordStep(db, record) {
2778
2736
  db.query(`INSERT INTO steps (
2779
2737
  message_id, session_id, parent_id, provider_id, model_id, variant,
2780
- input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost,
2781
- created_at, streamed_at, completed_at, finish, router, recorded_at
2738
+ input_tokens, output_tokens, reasoning_tokens, cache_read, cache_write, cost, list_cost,
2739
+ created_at, streamed_at, completed_at, finish, recorded_at
2782
2740
  ) VALUES (
2783
2741
  $messageID, $sessionID, $parentID, $providerID, $modelID, $variant,
2784
- $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost,
2785
- $createdAt, $streamedAt, $completedAt, $finish, $router, $recordedAt
2742
+ $input, $output, $reasoning, $cacheRead, $cacheWrite, $cost, $listCost,
2743
+ $createdAt, $streamedAt, $completedAt, $finish, $recordedAt
2786
2744
  )
2787
2745
  ON CONFLICT(message_id) DO UPDATE SET
2788
2746
  session_id = excluded.session_id,
@@ -2796,16 +2754,18 @@ function recordStep(db, record) {
2796
2754
  cache_read = excluded.cache_read,
2797
2755
  cache_write = excluded.cache_write,
2798
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,
2799
2760
  created_at = COALESCE(excluded.created_at, steps.created_at),
2800
2761
  streamed_at = COALESCE(excluded.streamed_at, steps.streamed_at),
2801
2762
  completed_at = COALESCE(excluded.completed_at, steps.completed_at),
2802
2763
  finish = COALESCE(excluded.finish, steps.finish),
2803
- router = COALESCE(excluded.router, steps.router),
2804
2764
  recorded_at = excluded.recorded_at`).run({
2805
2765
  $messageID: record.messageID,
2806
2766
  $sessionID: record.sessionID,
2807
2767
  $parentID: record.parentID ?? null,
2808
- $providerID: record.providerID ?? null,
2768
+ $providerID: record.providerID !== undefined && isToken(record.providerID) ? record.providerID : null,
2809
2769
  $modelID: record.modelID ?? null,
2810
2770
  $variant: record.variant ?? null,
2811
2771
  $input: record.input ?? 0,
@@ -2814,11 +2774,11 @@ function recordStep(db, record) {
2814
2774
  $cacheRead: record.cacheRead ?? 0,
2815
2775
  $cacheWrite: record.cacheWrite ?? 0,
2816
2776
  $cost: record.cost ?? 0,
2777
+ $listCost: (record.cost ?? 0) <= 0 && record.listCost !== undefined && Number.isFinite(record.listCost) && record.listCost >= 0 ? record.listCost : null,
2817
2778
  $createdAt: record.createdAt ?? null,
2818
2779
  $streamedAt: record.streamedAt ?? null,
2819
2780
  $completedAt: record.completedAt ?? null,
2820
2781
  $finish: record.finish === undefined ? null : sanitizeLabel(record.finish, 64),
2821
- $router: record.router === undefined ? null : normalizeToken(record.router) ?? null,
2822
2782
  $recordedAt: record.recordedAt ?? Date.now()
2823
2783
  });
2824
2784
  }
@@ -2858,15 +2818,6 @@ function upsertSession(db, record) {
2858
2818
  $updatedAt: record.updatedAt ?? null
2859
2819
  });
2860
2820
  }
2861
- function setStepRouterForSessionModel(db, sessionID, modelID, info) {
2862
- const router = info.router === undefined ? undefined : normalizeToken(info.router);
2863
- if (router === undefined)
2864
- return 0;
2865
- const result = db.query(`UPDATE steps
2866
- SET router = $router
2867
- WHERE session_id = $sessionID AND router IS NULL AND ($modelID IS NULL OR model_id = $modelID)`).run({ $router: router, $sessionID: sessionID, $modelID: modelID ?? null });
2868
- return result.changes;
2869
- }
2870
2821
 
2871
2822
  // src/stats/maintenance.ts
2872
2823
  var STEP_TIME2 = "COALESCE(created_at, recorded_at)";
@@ -2887,6 +2838,11 @@ function dbInfo(db, path, now = Date.now()) {
2887
2838
  const version = db.query("SELECT value FROM meta WHERE key = 'schema_version'").get();
2888
2839
  return {
2889
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,
2890
2846
  bytes: size(path),
2891
2847
  walBytes: path === ":memory:" ? undefined : size(`${path}-wal`) || undefined,
2892
2848
  schemaVersion: version === null ? 0 : Number.parseInt(version.value, 10),
@@ -2928,6 +2884,61 @@ function vacuum(db, path) {
2928
2884
  const after = footprint(path);
2929
2885
  return { before, after, freed: Math.max(0, before - after) };
2930
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
+ }
2931
2942
 
2932
2943
  // src/panel.tsx
2933
2944
  function Panel(props) {
@@ -2946,8 +2957,8 @@ function Panel(props) {
2946
2957
  ...current.modelID !== "" ? {
2947
2958
  modelID: current.modelID
2948
2959
  } : {},
2949
- ...current.routerID !== "" ? {
2950
- router: current.routerID
2960
+ ...current.providerID !== "" ? {
2961
+ provider: current.providerID
2951
2962
  } : {}
2952
2963
  };
2953
2964
  };
@@ -2990,6 +3001,7 @@ function Panel(props) {
2990
3001
  sessionStart: props.deps.sessionStart(props.input.sessionID),
2991
3002
  now: props.deps.now(),
2992
3003
  format: props.format,
3004
+ estimates: props.format?.estimates !== false,
2993
3005
  ...detail() !== undefined ? {
2994
3006
  detail: detail()
2995
3007
  } : {},
@@ -3003,8 +3015,8 @@ function Panel(props) {
3003
3015
  });
3004
3016
  const header = createMemo(() => {
3005
3017
  const current = settings();
3006
- const filters2 = filterSummary(current);
3007
- const where = detail() !== undefined ? " \xB7 backspace returns" : filters2 === undefined ? "" : ` \xB7 ${filters2}`;
3018
+ const filters = filterSummary(current);
3019
+ const where = detail() !== undefined ? " \xB7 backspace returns" : filters === undefined ? "" : ` \xB7 ${filters}`;
3008
3020
  return [{
3009
3021
  text: `usage insights \xB7 ${rangeLabel(current.range)}${where}`,
3010
3022
  tone: "accent"
@@ -3113,6 +3125,62 @@ function Panel(props) {
3113
3125
  }
3114
3126
  setAnchor(undefined);
3115
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?.();
3116
3184
  }
3117
3185
  async function compact() {
3118
3186
  if (sessionRunning()) {
@@ -3165,11 +3233,11 @@ function Panel(props) {
3165
3233
  if (db === undefined)
3166
3234
  return;
3167
3235
  const all = filterOptions(db);
3168
- const list = kind === "model" ? all.models : all.endpoints;
3236
+ const list = kind === "model" ? all.models : all.providers;
3169
3237
  const current = settings();
3170
- const selected = kind === "model" ? current.modelID : current.routerID;
3238
+ const selected = kind === "model" ? current.modelID : current.providerID;
3171
3239
  const value = await props.ctx.ui.dialog.select({
3172
- title: kind === "model" ? "Filter by model" : "Filter by endpoint (who served it)",
3240
+ title: kind === "model" ? "Filter by model" : "Filter by provider",
3173
3241
  current: selected,
3174
3242
  options: [{
3175
3243
  title: `any \xB7 ${list.length} observed`,
@@ -3187,7 +3255,7 @@ function Panel(props) {
3187
3255
  if (kind === "model")
3188
3256
  draft.modelID = value;
3189
3257
  else
3190
- draft.routerID = value;
3258
+ draft.providerID = value;
3191
3259
  });
3192
3260
  setAnchor(undefined);
3193
3261
  setDetail(undefined);
@@ -3225,13 +3293,16 @@ function Panel(props) {
3225
3293
  })), command("usage-insights.scope", "Toggle the turns scope", "a", () => props.update((draft) => {
3226
3294
  draft.turnsScope = sanitizeSettings(draft).turnsScope === "session" ? "all" : "session";
3227
3295
  draft.view = "turns";
3228
- })), command("usage-insights.filter.model", "Filter by model", "m", () => void pickFilter("model")), command("usage-insights.filter.endpoint", "Filter by endpoint", "e", () => void pickFilter("endpoint")), command("usage-insights.filter.clear", "Clear filters", "x", () => {
3296
+ })), command("usage-insights.filter.model", "Filter by model", "m", () => void pickFilter("model")), command("usage-insights.filter.provider", "Filter by provider", "p", () => void pickFilter("provider")), command("usage-insights.filter.clear", "Clear filters", "x", () => {
3229
3297
  props.update((draft) => {
3230
3298
  draft.modelID = "";
3231
- draft.routerID = "";
3299
+ draft.providerID = "";
3232
3300
  });
3233
3301
  setAnchor(undefined);
3234
- }), 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), () => {
3235
3306
  setHelp(false);
3236
3307
  props.update((draft) => {
3237
3308
  draft.view = name;
@@ -3334,6 +3405,75 @@ function selectedLineIndex(lines, cursor) {
3334
3405
  return -1;
3335
3406
  }
3336
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
+
3337
3477
  // src/sidebar.tsx
3338
3478
  import { effect as _$effect2 } from "@opentui/solid";
3339
3479
  import { insert as _$insert2 } from "@opentui/solid";
@@ -3363,7 +3503,7 @@ function TurnsSidebar(props) {
3363
3503
  try {
3364
3504
  const summary = sessionSummaryLines(overview(db, undefined, {
3365
3505
  sessionID: props.sessionID
3366
- }), budget);
3506
+ }), budget, props.options?.estimates !== false);
3367
3507
  const history = sidebarLines(turns(db, {
3368
3508
  sessionID: props.sessionID,
3369
3509
  limit: props.deps.limit
@@ -3400,8 +3540,6 @@ function TurnsSidebar(props) {
3400
3540
  }
3401
3541
 
3402
3542
  // src/tui.tsx
3403
- var ROUTER_CACHE_MS = 5000;
3404
- var MAX_ROUTER_CACHE = 512;
3405
3543
  var REFRESH_THROTTLE_MS = 300;
3406
3544
  var __test = {
3407
3545
  line: undefined,
@@ -3416,6 +3554,31 @@ var tui_default = Plugin.define({
3416
3554
  if (options.enabled === false)
3417
3555
  return;
3418
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
+ }
3419
3582
  const [settings, updateSettings] = ctx.storage.store("panel", {
3420
3583
  initial: DEFAULT_SETTINGS
3421
3584
  });
@@ -3423,12 +3586,13 @@ var tui_default = Plugin.define({
3423
3586
  updateSettings(mutation);
3424
3587
  };
3425
3588
  const [refresh, setRefresh] = createSignal2(0);
3426
- const routerCache = new Map;
3427
3589
  let database;
3428
3590
  let databaseFailed = false;
3429
3591
  let refreshTimer;
3430
3592
  let lastRefresh = 0;
3593
+ const sessionCostCache = new Map;
3431
3594
  function bumpRefresh() {
3595
+ sessionCostCache.clear();
3432
3596
  const now = Date.now();
3433
3597
  const wait = lastRefresh + REFRESH_THROTTLE_MS - now;
3434
3598
  if (wait <= 0) {
@@ -3458,6 +3622,28 @@ var tui_default = Plugin.define({
3458
3622
  return;
3459
3623
  }
3460
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
+ }
3461
3647
  function withWrite(run) {
3462
3648
  let handle;
3463
3649
  try {
@@ -3469,38 +3655,17 @@ var tui_default = Plugin.define({
3469
3655
  handle?.close();
3470
3656
  }
3471
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
+ }
3472
3666
  function sessionStart(sessionID) {
3473
3667
  return ctx.data.session.get(sessionID)?.time.created;
3474
3668
  }
3475
- function lookupRouter(sessionID, stepIDs) {
3476
- if (stepIDs.length === 0)
3477
- return;
3478
- const key = `${sessionID}#${stepIDs[stepIDs.length - 1]}#${stepIDs.length}`;
3479
- const now = Date.now();
3480
- const cached = routerCache.get(key);
3481
- if (cached !== undefined && now - cached.at < ROUTER_CACHE_MS)
3482
- return cached.value;
3483
- let value;
3484
- const handle = db();
3485
- if (handle !== undefined) {
3486
- try {
3487
- value = routerForSteps(handle, sessionID, stepIDs);
3488
- } catch {
3489
- value = undefined;
3490
- }
3491
- }
3492
- routerCache.set(key, {
3493
- value,
3494
- at: now
3495
- });
3496
- while (routerCache.size > MAX_ROUTER_CACHE) {
3497
- const oldest = routerCache.keys().next();
3498
- if (oldest.done === true)
3499
- break;
3500
- routerCache.delete(oldest.value);
3501
- }
3502
- return value;
3503
- }
3504
3669
  function sessionIdle(sessionID) {
3505
3670
  try {
3506
3671
  return ctx.data.session.status(sessionID) === "idle";
@@ -3511,25 +3676,12 @@ var tui_default = Plugin.define({
3511
3676
  function lineFor(sessionID) {
3512
3677
  if (!sessionIdle(sessionID))
3513
3678
  return;
3679
+ if (pricing)
3680
+ refresh();
3514
3681
  const messages = ctx.data.session.message.list(sessionID);
3515
3682
  const info = ctx.data.session.get(sessionID);
3516
- const stats = computeTurn(toTranscriptTail(messages, 2), sessionTotals(info));
3517
- if (stats !== undefined) {
3518
- const router = lookupRouter(sessionID, stats.stepIDs);
3519
- if (router !== undefined) {
3520
- stats.router = router;
3521
- const handle = db();
3522
- if (handle !== undefined) {
3523
- try {
3524
- const previous = routerBefore(handle, sessionID, stats.startAt);
3525
- stats.identityChanged = previous !== undefined && previous !== stats.router;
3526
- } catch {
3527
- stats.identityChanged = false;
3528
- }
3529
- }
3530
- }
3531
- }
3532
- return stats;
3683
+ const session = info === undefined ? undefined : sessionTotals(info, sessionListCostFor(sessionID));
3684
+ return computeTurn(toTranscriptTail(messages, 2, priceFor()), session);
3533
3685
  }
3534
3686
  function toneColor(tone) {
3535
3687
  if (tone === "warning")
@@ -3543,7 +3695,7 @@ var tui_default = Plugin.define({
3543
3695
  labels: options.labels,
3544
3696
  fields: options.fields,
3545
3697
  turnTotals: options.turnTotals,
3546
- identity: options.identity
3698
+ estimates: pricing
3547
3699
  }));
3548
3700
  return _$createComponent3(Show, {
3549
3701
  get when() {
@@ -3586,9 +3738,11 @@ var tui_default = Plugin.define({
3586
3738
  db,
3587
3739
  dbPath: () => resolveDbPath(options.db),
3588
3740
  withWrite,
3741
+ backfill,
3589
3742
  now: () => Date.now(),
3590
3743
  sessionStart,
3591
- refresh
3744
+ refresh,
3745
+ bump: bumpRefresh
3592
3746
  },
3593
3747
  settings,
3594
3748
  update: patchSettings,
@@ -3597,7 +3751,7 @@ var tui_default = Plugin.define({
3597
3751
  labels: options.labels,
3598
3752
  fields: options.fields,
3599
3753
  turnTotals: options.turnTotals,
3600
- identity: options.identity
3754
+ estimates: pricing
3601
3755
  };
3602
3756
  }
3603
3757
  }) : null
@@ -3621,7 +3775,7 @@ var tui_default = Plugin.define({
3621
3775
  labels: options.labels,
3622
3776
  fields: options.fields,
3623
3777
  turnTotals: options.turnTotals,
3624
- identity: options.identity
3778
+ estimates: pricing
3625
3779
  };
3626
3780
  }
3627
3781
  })
@@ -3672,19 +3826,20 @@ var tui_default = Plugin.define({
3672
3826
  });
3673
3827
  }
3674
3828
  const disposeEvents = [
3675
- ctx.data.on("session.step.ended", () => {
3676
- routerCache.clear();
3677
- bumpRefresh();
3678
- }),
3829
+ ctx.data.on("session.step.ended", () => bumpRefresh()),
3679
3830
  ctx.data.on("session.execution.succeeded", () => bumpRefresh()),
3680
3831
  ctx.data.on("session.execution.failed", () => bumpRefresh()),
3681
3832
  ctx.data.on("session.execution.interrupted", () => bumpRefresh()),
3682
- 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
+ })
3683
3837
  ];
3684
3838
  __test.line = lineFor;
3685
3839
  __test.lineText = (sessionID) => lineText(lineParts(lineFor(sessionID), {
3686
3840
  labels: options.labels,
3687
- fields: options.fields
3841
+ fields: options.fields,
3842
+ estimates: pricing
3688
3843
  }));
3689
3844
  __test.open = open;
3690
3845
  __test.state = () => {
@@ -3707,8 +3862,8 @@ var tui_default = Plugin.define({
3707
3862
  }
3708
3863
  });
3709
3864
  export {
3710
- tui_default as default,
3711
- __test
3865
+ __test,
3866
+ tui_default as default
3712
3867
  };
3713
3868
 
3714
- //# debugId=8AFC5B22D32833D364756E2164756E21
3869
+ //# debugId=EAEFC12B046D781964756E2164756E21