pantheon-opencode 1.6.0-beta.8 → 1.6.0

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.
Files changed (141) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +126 -346
  4. package/README.md +83 -608
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +366 -132
  7. package/commands/pantheon-audit.md +7 -1
  8. package/commands/pantheon-consolidate.md +1 -1
  9. package/commands/pantheon-deepwork.md +14 -3
  10. package/commands/pantheon-focus.md +17 -0
  11. package/commands/pantheon-vision.md +61 -12
  12. package/package.json +19 -11
  13. package/plugin.json +1 -1
  14. package/pyproject.toml +6 -2
  15. package/scripts/_pantheon_paths.py +24 -0
  16. package/scripts/build-agents-md.mjs +368 -69
  17. package/scripts/changelog-merge.mjs +161 -0
  18. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  19. package/scripts/docs-check-changelog.mjs +204 -0
  20. package/scripts/docs-link-check.mjs +314 -0
  21. package/scripts/docs-media.mjs +157 -0
  22. package/scripts/doctor.mjs +828 -40
  23. package/scripts/install/agents-md.mjs +2 -2
  24. package/scripts/install/backup.mjs +648 -0
  25. package/scripts/install/cli-ui.mjs +303 -72
  26. package/scripts/install/component-selection.mjs +61 -0
  27. package/scripts/install/config-migration.mjs +583 -27
  28. package/scripts/install/exit-codes.mjs +26 -0
  29. package/scripts/install/file-inventory.mjs +555 -0
  30. package/scripts/install/health-check.mjs +31 -25
  31. package/scripts/install/interactive.mjs +78 -383
  32. package/scripts/install/migrate.mjs +49 -25
  33. package/scripts/install/model-picker.mjs +218 -250
  34. package/scripts/install/opencode-version.mjs +83 -21
  35. package/scripts/install/opencode.mjs +1465 -180
  36. package/scripts/install/plan-artifact.mjs +517 -0
  37. package/scripts/install/plan.mjs +475 -0
  38. package/scripts/install/plugin.mjs +251 -30
  39. package/scripts/install/prompt-result.mjs +2 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +60 -4
  43. package/scripts/install/venv.mjs +90 -47
  44. package/scripts/install/verify.mjs +128 -0
  45. package/scripts/install/vision-prompt.mjs +173 -0
  46. package/scripts/install-mcp.mjs +2 -2
  47. package/scripts/manifest-inventory.mjs +49 -3
  48. package/scripts/mcp_persistence.py +1535 -1050
  49. package/scripts/memory_mcp.py +12 -843
  50. package/scripts/node-engine-policy.mjs +85 -0
  51. package/scripts/package-evidence.mjs +10 -2
  52. package/scripts/postinstall.mjs +26 -26
  53. package/scripts/probe-pantheon-cost.mjs +118 -19
  54. package/scripts/prune.mjs +9 -3
  55. package/scripts/reconcile.mjs +325 -0
  56. package/scripts/release-gates.mjs +682 -0
  57. package/scripts/restore.mjs +222 -0
  58. package/scripts/run-node-tests.mjs +24 -8
  59. package/scripts/sync-artifacts.mjs +20 -7
  60. package/scripts/sync-tui.mjs +29 -4
  61. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  62. package/scripts/uninstall.mjs +369 -34
  63. package/scripts/update.mjs +164 -0
  64. package/scripts/validate-node-engine-policy.mjs +13 -0
  65. package/scripts/version-check.mjs +34 -1
  66. package/scripts/versioning.mjs +23 -3
  67. package/scripts/vision-status.mjs +682 -0
  68. package/skills-lock.json +8 -8
  69. package/src/agents/aphrodite.md +13 -10
  70. package/src/agents/apollo.md +4 -5
  71. package/src/agents/athena.md +74 -46
  72. package/src/agents/demeter.md +10 -7
  73. package/src/agents/gaia.md +0 -1
  74. package/src/agents/hephaestus.md +4 -3
  75. package/src/agents/hermes.md +10 -9
  76. package/src/agents/iris.md +6 -1
  77. package/src/agents/mnemosyne.md +14 -15
  78. package/src/agents/nyx.md +4 -4
  79. package/src/agents/prometheus.md +12 -11
  80. package/src/agents/talos.md +6 -0
  81. package/src/agents/zeus.md +84 -56
  82. package/src/instructions/agent-return-format.instructions.md +12 -41
  83. package/src/instructions/memory-protocol.instructions.md +5 -11
  84. package/src/instructions/test-economy.instructions.md +12 -0
  85. package/src/instructions/yagni.instructions.md +6 -15
  86. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  87. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  88. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  89. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  90. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  91. package/src/mcp/_pantheon_paths.py +24 -0
  92. package/src/mcp/mcp_codemap_module.py +86 -18
  93. package/src/mcp/mcp_persistence.py +1535 -1050
  94. package/src/mcp/memory_mcp.py +444 -94
  95. package/src/mcp/pantheon_vision.py +285 -41
  96. package/src/mcp/requirements-mcp.txt +5 -0
  97. package/src/pantheon/context-pruner.ts +541 -0
  98. package/src/pantheon/cost-command.ts +814 -60
  99. package/src/pantheon/goal-loop.ts +11 -8
  100. package/src/pantheon/memory-context.ts +1017 -0
  101. package/src/pantheon/model-agents.ts +19 -0
  102. package/src/pantheon/model-command.ts +218 -56
  103. package/src/pantheon/model-pricing.ts +536 -0
  104. package/src/pantheon/presets.mjs +2 -0
  105. package/src/pantheon/task-result-guard.ts +50 -14
  106. package/src/pantheon/v2-bounded-read.ts +640 -0
  107. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  108. package/src/pantheon/v2-execute-after.ts +135 -24
  109. package/src/pantheon/v2-model-overrides.ts +275 -0
  110. package/src/pantheon/v2-tools.ts +89 -35
  111. package/src/pantheon/v2-unsupported.mjs +2 -3
  112. package/src/pantheon/v2-vision.ts +622 -0
  113. package/src/pantheon/vision-local.ts +531 -0
  114. package/src/pantheon/vision.ts +1160 -115
  115. package/src/plugin-v2.ts +654 -162
  116. package/src/plugin.ts +15 -11
  117. package/src/plugins/tui/dist/tui-v2.d.ts +1036 -0
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -0
  119. package/src/plugins/tui/dist/tui-v2.js +3808 -0
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -0
  121. package/src/plugins/tui/dist/tui.js +4 -4
  122. package/src/plugins/tui/index-v2.ts +6 -0
  123. package/src/plugins/tui/package-lock.json +5416 -1297
  124. package/src/plugins/tui/package.json +14 -10
  125. package/src/plugins/tui/src/index-v2.tsx +4372 -0
  126. package/src/plugins/tui/src/index.tsx +3 -3
  127. package/src/plugins/tui/src/opencode-v2.d.ts +13 -0
  128. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  129. package/src/plugins/tui/tsdown.config.ts +2 -2
  130. package/src/plugins/tui/tui-v2.ts +2 -0
  131. package/src/plugins/tui/tui.ts +3 -0
  132. package/src/routing.yml +50 -5
  133. package/src/skills/agent-coordination/SKILL.md +7 -2
  134. package/src/skills/artifact-management/SKILL.md +5 -1
  135. package/src/skills/auto-continue/SKILL.md +14 -6
  136. package/src/skills/codemap/SKILL.md +1 -1
  137. package/src/skills/memory-bank/SKILL.md +21 -13
  138. package/src/skills/session-goal/SKILL.md +14 -15
  139. package/src/skills/spec-driven-development/SKILL.md +3 -1
  140. package/src/skills/worktrees/SKILL.md +30 -11
  141. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -1,9 +1,13 @@
1
1
  /**
2
- * Token Command — `pantheon_cost` structural tool: token visibility for
3
- * delegation traffic, straight from opencode.db.
2
+ * Cost Command — `pantheon_cost` structural tool: token AND money visibility
3
+ * for delegation traffic, straight from opencode.db.
4
4
  *
5
5
  * Reads the opencode session database READ-ONLY (sum tokens by agent and
6
- * phase over the last N days → markdown table). Zero new dependencies:
6
+ * phase over the last N days → markdown table) and prices those tokens with
7
+ * the models.dev catalog (see {@link module:model-pricing}), which is cached on
8
+ * disk and never awaited by a tool call unless `refreshPricing` asks for it. A
9
+ * session view attributes spend to a root session plus its descendant sessions
10
+ * using the parent ids already in the database. Zero new dependencies:
7
11
  * - only path: node:sqlite (DatabaseSync, readOnly) — node ≥ 22.5;
8
12
  * - missing/unreadable db → a diagnostic contract status as TEXT.
9
13
  *
@@ -37,6 +41,15 @@ import { homedir } from 'node:os'
37
41
  import { delimiter, dirname, join } from 'node:path'
38
42
  import { fileURLToPath } from 'node:url'
39
43
  import { z } from 'zod'
44
+ import {
45
+ computeModelCost,
46
+ forceRefreshPricing,
47
+ loadPricing,
48
+ lookupModelPrice,
49
+ type PricingOptions,
50
+ type PricingSnapshot,
51
+ type UnpricedReason,
52
+ } from './model-pricing.ts'
40
53
  import type { NativeTaskStatus } from './native-task-status.ts'
41
54
  import type { ToolContextLike } from './tool-context.ts'
42
55
 
@@ -50,6 +63,48 @@ export interface CostRow {
50
63
  tokensInput: number
51
64
  tokensOutput: number
52
65
  tokensTotal: number
66
+ /** USD for this row; absent when any contributing model is unpriced. */
67
+ costUsd?: number
68
+ }
69
+
70
+ /** One aggregated row per (agent, phase, provider, model). */
71
+ export interface CostModelRow {
72
+ agent: string
73
+ phase: string
74
+ provider: string
75
+ model: string
76
+ tokensInput: number
77
+ tokensOutput: number
78
+ tokensCacheRead: number
79
+ tokensCacheWrite: number
80
+ tokensTotal: number
81
+ costUsd?: number
82
+ unpricedReason?: UnpricedReason
83
+ }
84
+
85
+ /** One aggregated row per session (a node of the session tree). */
86
+ export interface CostSessionRow {
87
+ sessionId: string
88
+ title?: string
89
+ agents: string[]
90
+ tokensInput: number
91
+ tokensOutput: number
92
+ tokensCacheRead: number
93
+ tokensCacheWrite: number
94
+ tokensTotal: number
95
+ costUsd?: number
96
+ unpricedReason?: UnpricedReason
97
+ }
98
+
99
+ /** The session subtree a report was scoped to, when `session` was requested. */
100
+ export interface CostSessionScope {
101
+ rootId: string
102
+ /** Root plus every descendant found in the session tables. */
103
+ ids: string[]
104
+ /** False when the root id has no row in the session tables. */
105
+ rootKnown: boolean
106
+ /** False when the database carries no session metadata table at all. */
107
+ hierarchy: boolean
53
108
  }
54
109
 
55
110
  /**
@@ -89,6 +144,12 @@ export interface CostCoverage {
89
144
  export interface CostQuery {
90
145
  rows: CostRow[]
91
146
  coverage: CostCoverage
147
+ /** Per-model breakdown. Absent on the CLI-fallback path, which reports tokens only. */
148
+ byModel?: CostModelRow[]
149
+ /** Per-session breakdown. Absent on the CLI-fallback path. */
150
+ bySession?: CostSessionRow[]
151
+ /** Set when the report was scoped to one session tree. */
152
+ sessionScope?: CostSessionScope
92
153
  }
93
154
 
94
155
  export interface CostCommandOptions {
@@ -98,6 +159,8 @@ export interface CostCommandOptions {
98
159
  sqliteLoader?: () => Promise<SqliteModule>
99
160
  /** Injectable CLI-fallback process boundary (tests / unusual runtimes). */
100
161
  cliFallback?: CliFallbackDeps
162
+ /** Pricing cache / fetch boundary (tests, air-gapped hosts). */
163
+ pricing?: PricingOptions
101
164
  }
102
165
 
103
166
  export type OpenCodeVersion = 'v1' | 'v2'
@@ -129,9 +192,25 @@ const costArgs = {
129
192
  .min(1)
130
193
  .max(365)
131
194
  .optional()
132
- .describe('Number of days of delegation history to include (default 7).'),
195
+ .describe('Number of rolling 24-hour days of history to include (default 7).'),
196
+ session: z
197
+ .string()
198
+ .min(1)
199
+ .optional()
200
+ .describe(
201
+ 'Session id to scope the report to: the root session plus every descendant session in its subtree.',
202
+ ),
203
+ refreshPricing: z
204
+ .boolean()
205
+ .optional()
206
+ .describe(
207
+ 'Await a models.dev price refresh (bounded by a short timeout) instead of using the cached catalog. This is the only path that waits on the network.',
208
+ ),
133
209
  } satisfies z.ZodRawShape
134
210
 
211
+ /** Parsed arguments of the cost tool. */
212
+ type CostArgs = z.infer<z.ZodObject<typeof costArgs>>
213
+
135
214
  /** The XDG state directory every real host installation writes its ledger to. */
136
215
  function defaultDbPath(): string {
137
216
  const xdg = process.env.XDG_DATA_HOME
@@ -215,63 +294,209 @@ function resolveSources(db: SqliteDatabase, requested: OpenCodeVersion | undefin
215
294
  }
216
295
 
217
296
  /**
218
- * Per-family aggregation.
297
+ * Per-family aggregation, grouped finely enough to price and to attribute.
219
298
  *
220
299
  * Aggregating in SQL instead of pulling `data` blobs into JS is not a
221
300
  * micro-optimisation: the host's own 7-day window is 271 MB across 26410
222
301
  * assistant rows, and the equivalent SQL finishes in 0.9 s over the
223
302
  * time_created index.
224
303
  *
225
- * Two correctness details are load-bearing:
304
+ * The grouping key is (agent, phase, provider, model, session): the first two
305
+ * keep the historical by-agent table, the middle two are what a price can be
306
+ * looked up for, and the last one is what a spend attribution needs. Cost is
307
+ * computed in JS from these groups, so there is exactly ONE set of token sums
308
+ * behind every table in the report.
309
+ *
310
+ * Three correctness details are load-bearing:
226
311
  * - `json_valid(data)` gates every extraction, because `json_extract` and
227
312
  * `->>` both RAISE on malformed JSON in node:sqlite's bundled SQLite. The
228
313
  * inner CTE applies it before extracting anything, so the outer query can
229
314
  * never see an unparseable payload whatever order SQLite evaluates terms in.
230
315
  * - `COALESCE(SUM(...), 0)` — a group whose tokens are all NULL sums to NULL,
231
316
  * and adding NULL into an accumulator would print NaN into the report.
317
+ * - `session_id` is read only when the LEDGER table carries it. A real V1 and
318
+ * V2 table both do, but a partial database (or a hand-built fixture) may
319
+ * not, and selecting a missing column would fail the whole report instead
320
+ * of dropping the session view.
232
321
  *
233
322
  * V1 marks assistant turns with `data.role`; V2 marks them with the `type`
234
323
  * COLUMN. V2 carries no `role` key, so the V1 predicate would match nothing.
235
324
  */
236
- const AGGREGATE_SQL: Record<CostSource, string> = {
237
- message: `
325
+ const COST_AGGREGATE_SQL: Record<CostSource, (sessionId: boolean) => string> = {
326
+ message: (sessionId) => `
238
327
  WITH valid AS (
239
328
  SELECT json_extract(data, '$.role') AS role,
240
329
  json_extract(data, '$.agent') AS agent,
241
- json_extract(data, '$.phase') AS phase,
242
- json_extract(data, '$.metadata.phase') AS metadataPhase,
330
+ COALESCE(NULLIF(json_extract(data, '$.phase'), ''),
331
+ NULLIF(json_extract(data, '$.metadata.phase'), ''),
332
+ 'unknown') AS phase,
333
+ COALESCE(json_extract(data, '$.model.providerID'),
334
+ json_extract(data, '$.providerID')) AS provider,
335
+ COALESCE(json_extract(data, '$.model.id'),
336
+ json_extract(data, '$.modelID')) AS model,
337
+ ${sessionId ? 'session_id' : 'NULL'} AS sessionId,
243
338
  CAST(json_extract(data, '$.tokens.input') AS INTEGER) AS inTok,
244
- CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok
339
+ CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok,
340
+ CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER) AS cacheReadTok,
341
+ CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER) AS cacheWriteTok
245
342
  FROM message
246
343
  WHERE time_created >= ? AND json_valid(data)
247
344
  )
248
345
  SELECT agent AS agent,
249
- COALESCE(NULLIF(phase, ''), NULLIF(metadataPhase, ''), 'unknown') AS phase,
346
+ phase AS phase,
347
+ provider AS provider,
348
+ model AS model,
349
+ sessionId AS sessionId,
250
350
  COALESCE(SUM(inTok), 0) AS tokensInput,
251
351
  COALESCE(SUM(outTok), 0) AS tokensOutput,
252
- COUNT(*) AS rows
352
+ COALESCE(SUM(cacheReadTok), 0) AS tokensCacheRead,
353
+ COALESCE(SUM(cacheWriteTok), 0) AS tokensCacheWrite
253
354
  FROM valid
254
355
  WHERE role = 'assistant'
255
- GROUP BY 1, 2
356
+ GROUP BY agent, phase, provider, model, sessionId
256
357
  HAVING agent IS NOT NULL AND agent != ''`,
257
- session_message: `
358
+ session_message: (sessionId) => `
258
359
  WITH valid AS (
259
360
  SELECT json_extract(data, '$.agent') AS agent,
361
+ 'unknown' AS phase,
362
+ COALESCE(json_extract(data, '$.model.providerID'),
363
+ json_extract(data, '$.providerID')) AS provider,
364
+ COALESCE(json_extract(data, '$.model.id'),
365
+ json_extract(data, '$.modelID')) AS model,
366
+ ${sessionId ? 'session_id' : 'NULL'} AS sessionId,
260
367
  CAST(json_extract(data, '$.tokens.input') AS INTEGER) AS inTok,
261
- CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok
368
+ CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok,
369
+ CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER) AS cacheReadTok,
370
+ CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER) AS cacheWriteTok
262
371
  FROM session_message
263
372
  WHERE time_created >= ? AND type = 'assistant' AND json_valid(data)
264
373
  )
265
374
  SELECT agent AS agent,
266
- 'unknown' AS phase,
375
+ phase AS phase,
376
+ provider AS provider,
377
+ model AS model,
378
+ sessionId AS sessionId,
267
379
  COALESCE(SUM(inTok), 0) AS tokensInput,
268
380
  COALESCE(SUM(outTok), 0) AS tokensOutput,
269
- COUNT(*) AS rows
381
+ COALESCE(SUM(cacheReadTok), 0) AS tokensCacheRead,
382
+ COALESCE(SUM(cacheWriteTok), 0) AS tokensCacheWrite
270
383
  FROM valid
271
- GROUP BY 1
384
+ GROUP BY agent, phase, provider, model, sessionId
272
385
  HAVING agent IS NOT NULL AND agent != ''`,
273
386
  }
274
387
 
388
+ /** One row of the aggregated ledger query. */
389
+ interface LedgerGroup {
390
+ agent?: unknown
391
+ phase?: unknown
392
+ provider?: unknown
393
+ model?: unknown
394
+ sessionId?: unknown
395
+ tokensInput?: unknown
396
+ tokensOutput?: unknown
397
+ tokensCacheRead?: unknown
398
+ tokensCacheWrite?: unknown
399
+ }
400
+
401
+ /** One session row from the metadata tables. */
402
+ interface CostSessionInfo {
403
+ id: string
404
+ parentId?: string
405
+ title?: string
406
+ }
407
+
408
+ /** Session metadata of the whole database, plus the parent→children index. */
409
+ interface CostSessionIndex {
410
+ nodes: Map<string, CostSessionInfo>
411
+ children: Map<string, string[]>
412
+ /** Metadata tables that were read. */
413
+ tables: string[]
414
+ }
415
+
416
+ /** Table families that carry session ids and parent ids. */
417
+ const SESSION_TABLES: readonly string[] = ['session_v2', 'session']
418
+
419
+ /** Column names of one table; empty when the table does not exist. */
420
+ function tableColumns(db: SqliteDatabase, table: string): Set<string> {
421
+ // Interpolated names come from the module's own constant list, never from a
422
+ // caller or a payload, so no value can reach this string.
423
+ try {
424
+ const rows = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name?: unknown }>
425
+ return new Set(rows.map((row) => String(row.name)))
426
+ } catch {
427
+ return new Set()
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Read session metadata: ids, parent ids and titles.
433
+ *
434
+ * A migrated database carries BOTH families, and their id spaces are disjoint,
435
+ * so both are read and merged. Fields a family does not have are simply absent
436
+ * rather than fabricated.
437
+ */
438
+ function readSessionIndex(db: SqliteDatabase): CostSessionIndex {
439
+ const nodes = new Map<string, CostSessionInfo>()
440
+ const children = new Map<string, string[]>()
441
+ const tables: string[] = []
442
+ for (const table of SESSION_TABLES) {
443
+ const columns = tableColumns(db, table)
444
+ if (columns.size === 0 || !columns.has('id')) continue
445
+ tables.push(table)
446
+ const parent = columns.has('parent_id') ? 'parent_id' : 'NULL'
447
+ const title = columns.has('title') ? 'title' : 'NULL'
448
+ const rows = db
449
+ .prepare(`SELECT id, ${parent} AS parentId, ${title} AS title FROM ${table}`)
450
+ .all() as Array<{
451
+ id?: unknown
452
+ parentId?: unknown
453
+ title?: unknown
454
+ }>
455
+ for (const row of rows) {
456
+ const id = String(row.id ?? '')
457
+ if (id === '') continue
458
+ const parentId =
459
+ row.parentId === null || row.parentId === undefined ? undefined : String(row.parentId)
460
+ const title = row.title === null || row.title === undefined ? undefined : String(row.title)
461
+ nodes.set(id, {
462
+ id,
463
+ ...(parentId === undefined ? {} : { parentId }),
464
+ ...(title === undefined ? {} : { title }),
465
+ })
466
+ if (parentId !== undefined) {
467
+ const bucket = children.get(parentId) ?? []
468
+ bucket.push(id)
469
+ children.set(parentId, bucket)
470
+ }
471
+ }
472
+ }
473
+ return { nodes, children, tables }
474
+ }
475
+
476
+ /**
477
+ * Root session plus every descendant, by parent id.
478
+ *
479
+ * A visited set bounds the walk: a database that (through a bug or a manual
480
+ * edit) contains a parent cycle must not hang a tool call.
481
+ */
482
+ function resolveSessionTree(
483
+ index: CostSessionIndex,
484
+ rootId: string,
485
+ ): { ids: string[]; rootKnown: boolean } {
486
+ const ids = new Set<string>([rootId])
487
+ const queue: string[] = [rootId]
488
+ for (let cursor = 0; cursor < queue.length; cursor += 1) {
489
+ const current = queue[cursor]
490
+ if (current === undefined) continue
491
+ for (const child of index.children.get(current) ?? []) {
492
+ if (ids.has(child)) continue
493
+ ids.add(child)
494
+ queue.push(child)
495
+ }
496
+ }
497
+ return { ids: [...ids], rootKnown: index.nodes.has(rootId) }
498
+ }
499
+
275
500
  /**
276
501
  * Window counters — the evidence a diagnosis is built from. A report that
277
502
  * scanned rows but matched no assistant row must say so rather than render an
@@ -310,6 +535,64 @@ function emptyCoverage(sources: CostSource[]): CostCoverage {
310
535
  return { sources, scanned: 0, assistantRows: 0 }
311
536
  }
312
537
 
538
+ /** Options for one ledger read. */
539
+ export interface CostQueryOptions {
540
+ /** Prices to apply. Absent ⇒ every cost is reported as unavailable. */
541
+ pricing?: PricingSnapshot
542
+ /** Session id to scope to: the root plus every descendant session. */
543
+ sessionRoot?: string
544
+ }
545
+
546
+ /** One model group while a report is being assembled. */
547
+ interface ModelAccumulator {
548
+ agent: string
549
+ phase: string
550
+ provider: string
551
+ model: string
552
+ tokensInput: number
553
+ tokensOutput: number
554
+ tokensCacheRead: number
555
+ tokensCacheWrite: number
556
+ usd: number | undefined
557
+ unpriced: boolean
558
+ reason: UnpricedReason | undefined
559
+ }
560
+
561
+ /** One session group while a report is being assembled. */
562
+ interface SessionAccumulator {
563
+ sessionId: string
564
+ agents: Set<string>
565
+ tokensInput: number
566
+ tokensOutput: number
567
+ tokensCacheRead: number
568
+ tokensCacheWrite: number
569
+ usd: number | undefined
570
+ unpriced: boolean
571
+ reason: UnpricedReason | undefined
572
+ }
573
+
574
+ /** A ledger label the catalog cannot know; never an empty string. */
575
+ function ledgerLabel(value: unknown): string {
576
+ if (value === undefined || value === null) return 'unknown'
577
+ const text = String(value).trim()
578
+ return text === '' ? 'unknown' : text
579
+ }
580
+
581
+ /** Price one group, or explain why it cannot be priced. */
582
+ function priceTokens(
583
+ pricing: PricingSnapshot | undefined,
584
+ provider: string,
585
+ model: string,
586
+ tokens: { input: number; output: number; cacheRead: number; cacheWrite: number },
587
+ ): { usd: number } | { reason: UnpricedReason } {
588
+ if (pricing === undefined) return { reason: 'no-pricing' }
589
+ const lookup = lookupModelPrice(pricing, provider, model)
590
+ if (!lookup.ok) return { reason: lookup.reason }
591
+ const cost = computeModelCost(lookup.price, tokens)
592
+ if (!cost.ok) return { reason: cost.reason }
593
+ return { usd: cost.usd }
594
+ }
595
+
313
596
  /**
314
597
  * Read the token ledger of one database, read-only.
315
598
  *
@@ -317,19 +600,29 @@ function emptyCoverage(sources: CostSource[]): CostCoverage {
317
600
  * the same answer in tests. The script cannot import this module: it runs on a
318
601
  * plain Node precisely because node:sqlite is missing from the plugin runtime.
319
602
  */
320
- export async function queryCostRows(dbPath: string, days: number): Promise<CostQuery> {
603
+ export async function queryCostRows(
604
+ dbPath: string,
605
+ days: number,
606
+ options?: CostQueryOptions,
607
+ ): Promise<CostQuery> {
321
608
  const sqlite = (await import('node:sqlite')) as SqliteModule
322
- return queryWithSqlite(dbPath, days, sqlite)
609
+ return queryWithSqlite(dbPath, days, sqlite, options)
323
610
  }
324
611
 
325
612
  /** Shared aggregation path for the in-process reader and queryCostRows. */
326
- function queryWithSqlite(dbPath: string, days: number, sqlite: SqliteModule): CostQuery {
613
+ function queryWithSqlite(
614
+ dbPath: string,
615
+ days: number,
616
+ sqlite: SqliteModule,
617
+ options?: CostQueryOptions,
618
+ ): CostQuery {
327
619
  const db = new sqlite.DatabaseSync(dbPath, { readOnly: true })
328
620
  try {
329
621
  const sources = resolveSources(db, requestedVersion())
330
622
  const since = Date.now() - days * 86_400_000
331
- const byAgentAndPhase = new Map<string, CostRow>()
332
623
  const coverage = emptyCoverage([])
624
+ const models = new Map<string, ModelAccumulator>()
625
+ const sessions = new Map<string, SessionAccumulator>()
333
626
 
334
627
  const note = (key: 'windowStart' | 'databaseStart', value: number | undefined): void => {
335
628
  if (value === undefined) return
@@ -337,6 +630,23 @@ function queryWithSqlite(dbPath: string, days: number, sqlite: SqliteModule): Co
337
630
  coverage[key] = current === undefined ? value : Math.min(current, value)
338
631
  }
339
632
 
633
+ // Session metadata is read once: the tree is needed both to scope a report
634
+ // and to label the rows of the session view.
635
+ const sessionIndex = readSessionIndex(db)
636
+ const sessionRoot = options?.sessionRoot
637
+ let sessionScope: CostSessionScope | undefined
638
+ let scopedIds: Set<string> | undefined
639
+ if (sessionRoot !== undefined) {
640
+ const tree = resolveSessionTree(sessionIndex, sessionRoot)
641
+ scopedIds = new Set(tree.ids)
642
+ sessionScope = {
643
+ rootId: sessionRoot,
644
+ ids: tree.ids,
645
+ rootKnown: tree.rootKnown,
646
+ hierarchy: sessionIndex.tables.length > 0,
647
+ }
648
+ }
649
+
340
650
  for (const source of sources) {
341
651
  const countersRow = (
342
652
  db.prepare(COUNTER_SQL[source]).all(since, since, since) as Array<Counters>
@@ -353,38 +663,176 @@ function queryWithSqlite(dbPath: string, days: number, sqlite: SqliteModule): Co
353
663
  ),
354
664
  )
355
665
 
356
- const groups = db.prepare(AGGREGATE_SQL[source]).all(since) as Array<{
357
- agent?: unknown
358
- phase?: unknown
359
- tokensInput?: unknown
360
- tokensOutput?: unknown
361
- }>
666
+ const hasSessionColumn = tableColumns(db, source).has('session_id')
667
+ const groups = db
668
+ .prepare(COST_AGGREGATE_SQL[source](hasSessionColumn))
669
+ .all(since) as Array<LedgerGroup>
670
+
362
671
  for (const group of groups) {
363
672
  const agent = String(group.agent ?? '')
364
673
  if (agent === '') continue
365
- const phase =
366
- group.phase === undefined || group.phase === null ? 'unknown' : String(group.phase)
367
- const tokensInput = numberOf(group.tokensInput) ?? 0
368
- const tokensOutput = numberOf(group.tokensOutput) ?? 0
369
- // Keyed on a NUL separator: agent names cannot contain it, so an agent
370
- // whose name ends in the phase cannot collide with a phase-only row.
371
- const key = `${agent}\u0000${phase}`
372
- const acc = byAgentAndPhase.get(key) ?? {
674
+ const phase = ledgerLabel(group.phase)
675
+ const provider = ledgerLabel(group.provider)
676
+ const model = ledgerLabel(group.model)
677
+ const sessionId =
678
+ group.sessionId === undefined || group.sessionId === null
679
+ ? undefined
680
+ : String(group.sessionId)
681
+ // A scoped report keeps only rows inside the requested subtree. A row
682
+ // with no session id cannot be proven to belong to it, so it is out.
683
+ if (scopedIds !== undefined && (sessionId === undefined || !scopedIds.has(sessionId))) {
684
+ continue
685
+ }
686
+ const tokens = {
687
+ input: numberOf(group.tokensInput) ?? 0,
688
+ output: numberOf(group.tokensOutput) ?? 0,
689
+ cacheRead: numberOf(group.tokensCacheRead) ?? 0,
690
+ cacheWrite: numberOf(group.tokensCacheWrite) ?? 0,
691
+ }
692
+ const priced = priceTokens(options?.pricing, provider, model, tokens)
693
+
694
+ // Keyed on NUL separators: none of these labels can contain one, so no
695
+ // label ending in another label's text can collide with it.
696
+ const modelKey = `${agent}\u0000${phase}\u0000${provider}\u0000${model}`
697
+ const modelAcc = models.get(modelKey) ?? {
373
698
  agent,
374
699
  phase,
700
+ provider,
701
+ model,
375
702
  tokensInput: 0,
376
703
  tokensOutput: 0,
377
- tokensTotal: 0,
704
+ tokensCacheRead: 0,
705
+ tokensCacheWrite: 0,
706
+ usd: 0,
707
+ unpriced: false,
708
+ reason: undefined,
709
+ }
710
+ modelAcc.tokensInput += tokens.input
711
+ modelAcc.tokensOutput += tokens.output
712
+ modelAcc.tokensCacheRead += tokens.cacheRead
713
+ modelAcc.tokensCacheWrite += tokens.cacheWrite
714
+ if ('usd' in priced && modelAcc.usd !== undefined) {
715
+ modelAcc.usd += priced.usd
716
+ } else {
717
+ modelAcc.unpriced = true
718
+ modelAcc.usd = undefined
719
+ modelAcc.reason = modelAcc.reason ?? ('reason' in priced ? priced.reason : undefined)
720
+ }
721
+ models.set(modelKey, modelAcc)
722
+
723
+ if (sessionId === undefined) continue
724
+ const sessionAcc = sessions.get(sessionId) ?? {
725
+ sessionId,
726
+ agents: new Set<string>(),
727
+ tokensInput: 0,
728
+ tokensOutput: 0,
729
+ tokensCacheRead: 0,
730
+ tokensCacheWrite: 0,
731
+ usd: 0,
732
+ unpriced: false,
733
+ reason: undefined,
734
+ }
735
+ sessionAcc.agents.add(agent)
736
+ sessionAcc.tokensInput += tokens.input
737
+ sessionAcc.tokensOutput += tokens.output
738
+ sessionAcc.tokensCacheRead += tokens.cacheRead
739
+ sessionAcc.tokensCacheWrite += tokens.cacheWrite
740
+ if ('usd' in priced && sessionAcc.usd !== undefined) {
741
+ sessionAcc.usd += priced.usd
742
+ } else {
743
+ sessionAcc.unpriced = true
744
+ sessionAcc.usd = undefined
745
+ sessionAcc.reason = sessionAcc.reason ?? ('reason' in priced ? priced.reason : undefined)
378
746
  }
379
- acc.tokensInput += tokensInput
380
- acc.tokensOutput += tokensOutput
381
- acc.tokensTotal += tokensInput + tokensOutput
382
- byAgentAndPhase.set(key, acc)
747
+ sessions.set(sessionId, sessionAcc)
748
+ }
749
+ }
750
+
751
+ // The by-agent table is derived from the model groups, so every table in
752
+ // the report is backed by exactly one set of token sums. `costUsd` is the
753
+ // only added field, and only when every contributing model was priced, so
754
+ // the historical row shape keeps its old keys.
755
+ const byAgentPhase = new Map<
756
+ string,
757
+ { row: CostRow; usd: number | undefined; unpriced: boolean }
758
+ >()
759
+ for (const acc of models.values()) {
760
+ const key = `${acc.agent}\u0000${acc.phase}`
761
+ const entry = byAgentPhase.get(key) ?? {
762
+ row: {
763
+ agent: acc.agent,
764
+ phase: acc.phase,
765
+ tokensInput: 0,
766
+ tokensOutput: 0,
767
+ tokensTotal: 0,
768
+ },
769
+ usd: 0,
770
+ unpriced: false,
383
771
  }
772
+ entry.row.tokensInput += acc.tokensInput
773
+ entry.row.tokensOutput += acc.tokensOutput
774
+ entry.row.tokensTotal += acc.tokensInput + acc.tokensOutput
775
+ if (acc.unpriced || entry.usd === undefined) {
776
+ entry.unpriced = true
777
+ entry.usd = undefined
778
+ } else if (acc.usd !== undefined) {
779
+ entry.usd += acc.usd
780
+ }
781
+ byAgentPhase.set(key, entry)
384
782
  }
385
783
 
386
- const rows = [...byAgentAndPhase.values()].sort((a, b) => b.tokensTotal - a.tokensTotal)
387
- return { rows, coverage }
784
+ const rows: CostRow[] = [...byAgentPhase.values()]
785
+ .map((entry) =>
786
+ entry.unpriced || entry.usd === undefined
787
+ ? { ...entry.row }
788
+ : { ...entry.row, costUsd: entry.usd },
789
+ )
790
+ .sort((a, b) => b.tokensTotal - a.tokensTotal)
791
+
792
+ const byModel: CostModelRow[] = [...models.values()]
793
+ .map((acc) => ({
794
+ agent: acc.agent,
795
+ phase: acc.phase,
796
+ provider: acc.provider,
797
+ model: acc.model,
798
+ tokensInput: acc.tokensInput,
799
+ tokensOutput: acc.tokensOutput,
800
+ tokensCacheRead: acc.tokensCacheRead,
801
+ tokensCacheWrite: acc.tokensCacheWrite,
802
+ // "Total" means input+output everywhere in the report; cache tokens are
803
+ // reported in their own columns rather than folded into this one, so two
804
+ // tables cannot disagree about what a total counts.
805
+ tokensTotal: acc.tokensInput + acc.tokensOutput,
806
+ ...(acc.usd === undefined ? {} : { costUsd: acc.usd }),
807
+ ...(acc.reason === undefined ? {} : { unpricedReason: acc.reason }),
808
+ }))
809
+ .sort((a, b) => b.tokensTotal - a.tokensTotal)
810
+
811
+ const bySession: CostSessionRow[] = [...sessions.values()]
812
+ .map((acc) => {
813
+ const info = sessionIndex.nodes.get(acc.sessionId)
814
+ return {
815
+ sessionId: acc.sessionId,
816
+ ...(info?.title === undefined ? {} : { title: info.title }),
817
+ agents: [...acc.agents].sort(),
818
+ tokensInput: acc.tokensInput,
819
+ tokensOutput: acc.tokensOutput,
820
+ tokensCacheRead: acc.tokensCacheRead,
821
+ tokensCacheWrite: acc.tokensCacheWrite,
822
+ tokensTotal: acc.tokensInput + acc.tokensOutput,
823
+ ...(acc.usd === undefined ? {} : { costUsd: acc.usd }),
824
+ ...(acc.reason === undefined ? {} : { unpricedReason: acc.reason }),
825
+ }
826
+ })
827
+ .sort((a, b) => b.tokensTotal - a.tokensTotal)
828
+
829
+ return {
830
+ rows,
831
+ coverage,
832
+ byModel,
833
+ bySession,
834
+ ...(sessionScope === undefined ? {} : { sessionScope }),
835
+ }
388
836
  } finally {
389
837
  db.close()
390
838
  }
@@ -443,7 +891,18 @@ function diagnoseUnreadableLedger(query: CostQuery, days: number): string | unde
443
891
  'database whose token layout this build understands.'
444
892
  )
445
893
  }
446
- if (!query.rows.some((row) => row.tokensInput !== 0 || row.tokensOutput !== 0)) {
894
+ // A scoped report can legitimately be empty: the session filter, not the
895
+ // ledger layout, removed every row. Diagnosing the user's database from a
896
+ // filtered view reports a fault that does not exist, so the "no tokens"
897
+ // branch is reserved for an UNSCOPED read.
898
+ if (query.sessionScope !== undefined) return undefined
899
+ if (
900
+ !query.rows.some((row) => row.tokensInput !== 0 || row.tokensOutput !== 0) &&
901
+ // Cache-only usage is still usage: a turn whose whole payload was served
902
+ // from cache has zero input/output but a real cache-read count, and
903
+ // calling that "unreadable" would hide spend that this report can price.
904
+ !(query.byModel ?? []).some((row) => row.tokensCacheRead !== 0 || row.tokensCacheWrite !== 0)
905
+ ) {
447
906
  return (
448
907
  `no readable token source: ${assistantRows} assistant row(s) were found in ${tables} ` +
449
908
  'but none carried both an attributable agent and a token payload, so no usage can be ' +
@@ -453,36 +912,307 @@ function diagnoseUnreadableLedger(query: CostQuery, days: number): string | unde
453
912
  return undefined
454
913
  }
455
914
 
456
- /** Render the aggregate as a markdown table with a total row. */
457
- function renderMarkdown(query: CostQuery, days: number): string {
915
+ /** Smallest amount the four-decimal rendering can show without claiming zero. */
916
+ const MIN_DISPLAYABLE_USD = 0.0001
917
+
918
+ /**
919
+ * Human money. `—` is "could not be priced", never "free".
920
+ *
921
+ * A real zero renders as `$0.00`, but a non-zero amount below the display
922
+ * resolution renders as `< $0.0001`: rounding $0.00004 to `$0.0000` would show a
923
+ * free model where the catalog charged for one, and this is the column a spend
924
+ * decision is read from.
925
+ */
926
+ function formatUsd(usd: number | undefined): string {
927
+ if (usd === undefined) return '—'
928
+ if (usd === 0) return '$0.00'
929
+ if (usd < MIN_DISPLAYABLE_USD) return '< $0.0001'
930
+ return usd < 1 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`
931
+ }
932
+
933
+ /**
934
+ * A total row's cost cell.
935
+ *
936
+ * With no priced row at all the cell is `—`, not `$0.00`: a report that could
937
+ * not price anything has not measured zero spend, and this number is what a
938
+ * tier decision would be made on.
939
+ */
940
+ function totalCostCell(pricedUsd: number, pricedRows: number, unpricedRows: number): string {
941
+ if (pricedRows === 0) return unpricedRows === 0 ? '**$0.00**' : '**—** (nothing priceable)'
942
+ const cell = `**${formatUsd(pricedUsd)}**`
943
+ return unpricedRows === 0 ? cell : `${cell} (partial)`
944
+ }
945
+
946
+ /** Session rows shown before the tail is summarised. */
947
+ const MAX_SESSION_ROWS = 20
948
+
949
+ /** Cut a session title to something that fits a markdown cell. */
950
+ function shortTitle(title: string | undefined): string {
951
+ if (title === undefined) return '—'
952
+ const flat = title.replaceAll('|', '/').replaceAll('\n', ' ').trim()
953
+ return flat.length > 48 ? `${flat.slice(0, 47)}…` : flat === '' ? '—' : flat
954
+ }
955
+
956
+ /**
957
+ * Where the prices came from and how stale they are.
958
+ *
959
+ * This is a claim the report makes about its own numbers, so it is stated even
960
+ * when the answer is "no prices": a cost column full of `—` with no explanation
961
+ * reads as zero spend.
962
+ */
963
+ function pricingNote(pricing: PricingSnapshot | undefined): string[] {
964
+ if (pricing === undefined) {
965
+ return [
966
+ 'Pricing: unavailable for this run — every cost reads — and no model is treated as free.',
967
+ ]
968
+ }
969
+ if (pricing.refused === true) {
970
+ const detail = pricing.unavailableReason ?? 'a price refresh was refused'
971
+ const suffix =
972
+ pricing.index.size === 0
973
+ ? 'every cost reads — and no model is treated as free.'
974
+ : 'costs below use the cached catalog; nothing was fetched.'
975
+ return [`Pricing: REFUSED — ${detail}; ${suffix}`]
976
+ }
977
+ if (pricing.index.size === 0) {
978
+ const detail = pricing.unavailableReason ?? 'no cached catalog'
979
+ return [
980
+ `Pricing: unavailable (${detail}) — every cost reads — and unpriced models are EXCLUDED from totals, never priced at zero.`,
981
+ // Never recommend a call the host has forbidden: an offline report that
982
+ // says "run refreshPricing" is advice that cannot work.
983
+ pricing.offline === true
984
+ ? 'Pricing: this host is offline (PANTHEON_COST_OFFLINE=1); no catalog can be fetched until that is cleared.'
985
+ : 'Pricing: run pantheon_cost({ refreshPricing: true }) to fetch the models.dev catalog; that is the only path that waits on the network, bounded by a 3 s timeout.',
986
+ ]
987
+ }
988
+ const fetched = pricing.fetchedAt === undefined ? 'unknown date' : isoDay(pricing.fetchedAt)
989
+ const head = `Pricing: models.dev catalog (USD per 1M tokens), cached ${fetched}`
990
+ if (pricing.unavailableReason !== undefined) {
991
+ return [
992
+ `${head} — the requested refresh failed (${pricing.unavailableReason}); costs below use cached prices.`,
993
+ ]
994
+ }
995
+ if (pricing.refreshing) {
996
+ return [`${head} — stale, refreshing in the background; costs below use these cached prices.`]
997
+ }
998
+ if (pricing.stale) {
999
+ const why =
1000
+ pricing.offline === true
1001
+ ? 'offline, so no background refresh was scheduled'
1002
+ : 'no background refresh was scheduled'
1003
+ return [`${head} — stale, and ${why}; costs below use cached prices.`]
1004
+ }
1005
+ return [`${head}.`]
1006
+ }
1007
+
1008
+ /** Model rows collapsed across agents: one line per provider/model pair. */
1009
+ function modelTotals(byModel: readonly CostModelRow[]): Array<{
1010
+ provider: string
1011
+ model: string
1012
+ tokensInput: number
1013
+ tokensOutput: number
1014
+ tokensCacheRead: number
1015
+ tokensCacheWrite: number
1016
+ tokensTotal: number
1017
+ costUsd: number | undefined
1018
+ }> {
1019
+ const groups = new Map<
1020
+ string,
1021
+ {
1022
+ provider: string
1023
+ model: string
1024
+ tokensInput: number
1025
+ tokensOutput: number
1026
+ tokensCacheRead: number
1027
+ tokensCacheWrite: number
1028
+ tokensTotal: number
1029
+ usd: number | undefined
1030
+ unpriced: boolean
1031
+ }
1032
+ >()
1033
+ for (const row of byModel) {
1034
+ const key = `${row.provider}\u0000${row.model}`
1035
+ const acc = groups.get(key) ?? {
1036
+ provider: row.provider,
1037
+ model: row.model,
1038
+ tokensInput: 0,
1039
+ tokensOutput: 0,
1040
+ tokensCacheRead: 0,
1041
+ tokensCacheWrite: 0,
1042
+ tokensTotal: 0,
1043
+ usd: 0,
1044
+ unpriced: false,
1045
+ }
1046
+ acc.tokensInput += row.tokensInput
1047
+ acc.tokensOutput += row.tokensOutput
1048
+ acc.tokensCacheRead += row.tokensCacheRead
1049
+ acc.tokensCacheWrite += row.tokensCacheWrite
1050
+ acc.tokensTotal += row.tokensTotal
1051
+ if (row.costUsd === undefined || acc.usd === undefined) {
1052
+ acc.unpriced = true
1053
+ acc.usd = undefined
1054
+ } else {
1055
+ acc.usd += row.costUsd
1056
+ }
1057
+ groups.set(key, acc)
1058
+ }
1059
+ return [...groups.values()]
1060
+ .map((acc) => ({
1061
+ provider: acc.provider,
1062
+ model: acc.model,
1063
+ tokensInput: acc.tokensInput,
1064
+ tokensOutput: acc.tokensOutput,
1065
+ tokensCacheRead: acc.tokensCacheRead,
1066
+ tokensCacheWrite: acc.tokensCacheWrite,
1067
+ tokensTotal: acc.tokensTotal,
1068
+ costUsd: acc.unpriced ? undefined : acc.usd,
1069
+ }))
1070
+ .sort((a, b) => b.tokensTotal - a.tokensTotal)
1071
+ }
1072
+
1073
+ /** The `## Cost by model` section. */
1074
+ function renderModelSection(byModel: readonly CostModelRow[] | undefined, days: number): string[] {
1075
+ const header = `## Cost by model (last ${days} days)`
1076
+ if (byModel === undefined) {
1077
+ return [header, '', 'Unavailable: this run reports tokens only (CLI fallback path).']
1078
+ }
1079
+ if (byModel.length === 0) return [header, '', 'No model rows in this window.']
1080
+ const totals = modelTotals(byModel)
1081
+ const pricedUsd = totals.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
1082
+ const priced = totals.filter((row) => row.costUsd !== undefined).length
1083
+ const unpriced = totals.length - priced
1084
+ const totalCell = totalCostCell(pricedUsd, priced, unpriced)
1085
+ return [
1086
+ header,
1087
+ '',
1088
+ '| Provider | Model | Tokens In | Tokens Out | Cache Read | Cache Write | Cost (USD) |',
1089
+ '|----------|-------|----------:|-----------:|-----------:|------------:|-----------:|',
1090
+ ...totals.map(
1091
+ (row) =>
1092
+ `| ${row.provider} | ${row.model} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${formatUsd(row.costUsd)} |`,
1093
+ ),
1094
+ `| **Total** | — | **${totals.reduce((sum, row) => sum + row.tokensInput, 0)}** | **${totals.reduce((sum, row) => sum + row.tokensOutput, 0)}** | **${totals.reduce((sum, row) => sum + row.tokensCacheRead, 0)}** | **${totals.reduce((sum, row) => sum + row.tokensCacheWrite, 0)}** | ${totalCell} |`,
1095
+ ]
1096
+ }
1097
+
1098
+ /** The `## Cost by session` section, scoped or global. */
1099
+ function renderSessionSection(query: CostQuery, days: number): string[] {
1100
+ const scope = query.sessionScope
1101
+ const header =
1102
+ scope === undefined
1103
+ ? `## Cost by session (last ${days} days)`
1104
+ : `## Cost by session tree (last ${days} days) — root ${scope.rootId}`
1105
+ if (query.bySession === undefined) {
1106
+ return [header, '', 'Unavailable: this run reports tokens only (CLI fallback path).']
1107
+ }
1108
+ const lines = [header, '']
1109
+ if (scope !== undefined) {
1110
+ if (!scope.hierarchy) {
1111
+ lines.push(
1112
+ 'Session hierarchy unavailable: this database has no session metadata table, so only rows whose session_id equals the root are counted.',
1113
+ '',
1114
+ )
1115
+ } else if (!scope.rootKnown) {
1116
+ lines.push(
1117
+ 'Root session not found in this database: only rows whose session_id equals it are counted, and no descendants can be resolved.',
1118
+ '',
1119
+ )
1120
+ } else {
1121
+ lines.push(`Scope: the root session plus ${scope.ids.length - 1} descendant session(s).`, '')
1122
+ }
1123
+ }
1124
+ if (query.bySession.length === 0) {
1125
+ lines.push('No session rows in this window.')
1126
+ return lines
1127
+ }
1128
+ const shown = query.bySession.slice(0, MAX_SESSION_ROWS)
1129
+ const hidden = query.bySession.length - shown.length
1130
+ const pricedUsd = query.bySession.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
1131
+ const priced = query.bySession.filter((row) => row.costUsd !== undefined).length
1132
+ const unpriced = query.bySession.length - priced
1133
+ const totalCell = totalCostCell(pricedUsd, priced, unpriced)
1134
+ lines.push(
1135
+ '| Session | Title | Agent | Tokens In | Tokens Out | Cache Read | Cache Write | Tokens Total | Cost (USD) |',
1136
+ '|---------|-------|-------|----------:|-----------:|-----------:|------------:|-------------:|-----------:|',
1137
+ ...shown.map(
1138
+ (row) =>
1139
+ `| ${row.sessionId} | ${shortTitle(row.title)} | ${row.agents.join(', ') || '—'} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${row.tokensTotal} | ${formatUsd(row.costUsd)} |`,
1140
+ ),
1141
+ `| **${scope === undefined ? 'Total' : 'Root + descendants'}** | — | — | **${query.bySession.reduce((sum, row) => sum + row.tokensInput, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensOutput, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensCacheRead, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensCacheWrite, 0)}** | **${query.bySession.reduce((sum, row) => sum + row.tokensTotal, 0)}** | ${totalCell} |`,
1142
+ )
1143
+ if (hidden > 0) {
1144
+ lines.push('', `_+${hidden} more session(s) not listed; the totals include them._`)
1145
+ }
1146
+ return lines
1147
+ }
1148
+
1149
+ /** Render the aggregate as markdown tables with total rows. */
1150
+ function renderMarkdown(
1151
+ query: CostQuery,
1152
+ days: number,
1153
+ pricing: PricingSnapshot | undefined,
1154
+ ): string {
458
1155
  const { rows, coverage } = query
459
- const header = `## Token usage by agent and phase (last ${days} days)`
1156
+ const header = `## Token and cost usage by agent and phase (last ${days} days)`
460
1157
  const footer = [
461
1158
  formatCoverage(coverage, days),
1159
+ 'Window: rolling 24-hour days from query time (not calendar days or session boundaries).',
1160
+ 'Aggregation: per agent and phase (phase may be unknown on V2), per model, and per session.',
1161
+ 'Attribution: a session row covers that session alone; passing session:<id> sums the root session and its descendant sessions.',
1162
+ 'Limits: costs are catalog list prices (USD per 1M tokens), not a provider invoice; a row mixing a priced and an unpriced model reads — and is excluded from the totals, because an unknown model is never priced at zero.',
1163
+ ...pricingNote(pricing),
462
1164
  `Source: opencode.db (read-only) — table families: ${coverage.sources.join(' + ')} — ${coverage.assistantRows} assistant row(s) scanned`,
463
1165
  ].join('\n')
464
1166
  if (rows.length === 0) {
465
- return `${header}\n\nNo token records in the last ${days} days.\n\n${footer}`
1167
+ // The scope sentence lives in the session section, so an empty report must
1168
+ // still render that section — otherwise a valid empty subtree looks
1169
+ // indistinguishable from a database that holds nothing.
1170
+ const scope = query.sessionScope
1171
+ const empty =
1172
+ scope === undefined
1173
+ ? `No token records in the last ${days} days.`
1174
+ : `No token records in the last ${days} days for ${scope.rootId} or its descendant sessions.`
1175
+ return [
1176
+ header,
1177
+ '',
1178
+ empty,
1179
+ '',
1180
+ ...renderModelSection(query.byModel, days),
1181
+ '',
1182
+ ...renderSessionSection(query, days),
1183
+ '',
1184
+ footer,
1185
+ ].join('\n')
466
1186
  }
467
1187
  const total = rows.reduce(
468
1188
  (acc, r) => {
469
1189
  acc.tokensInput += r.tokensInput
470
1190
  acc.tokensOutput += r.tokensOutput
471
1191
  acc.tokensTotal += r.tokensTotal
1192
+ if (r.costUsd === undefined) acc.unpriced += 1
1193
+ else {
1194
+ acc.usd += r.costUsd
1195
+ acc.priced += 1
1196
+ }
472
1197
  return acc
473
1198
  },
474
- { tokensInput: 0, tokensOutput: 0, tokensTotal: 0 },
1199
+ { tokensInput: 0, tokensOutput: 0, tokensTotal: 0, usd: 0, unpriced: 0, priced: 0 },
475
1200
  )
1201
+ const totalCost = totalCostCell(total.usd, total.priced, total.unpriced)
476
1202
  const lines = [
477
1203
  header,
478
1204
  '',
479
- '| Agent | Phase | Tokens In | Tokens Out | Tokens Total |',
480
- '|-------|-------|----------:|-----------:|-------------:|',
1205
+ '| Agent | Phase | Tokens In | Tokens Out | Tokens Total | Cost (USD) |',
1206
+ '|-------|-------|----------:|-----------:|-------------:|-----------:|',
481
1207
  ...rows.map(
482
1208
  (r) =>
483
- `| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} |`,
1209
+ `| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} | ${formatUsd(r.costUsd)} |`,
484
1210
  ),
485
- `| **Total** | — | **${total.tokensInput}** | **${total.tokensOutput}** | **${total.tokensTotal}** |`,
1211
+ `| **Total** | — | **${total.tokensInput}** | **${total.tokensOutput}** | **${total.tokensTotal}** | ${totalCost} |`,
1212
+ '',
1213
+ ...renderModelSection(query.byModel, days),
1214
+ '',
1215
+ ...renderSessionSection(query, days),
486
1216
  '',
487
1217
  footer,
488
1218
  ]
@@ -782,13 +1512,13 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
782
1512
  }
783
1513
 
784
1514
  /** Run a query and turn its coverage into either a report or a diagnosis. */
785
- const render = (query: CostQuery, days: number): string => {
1515
+ const render = (query: CostQuery, days: number, pricing?: PricingSnapshot): string => {
786
1516
  const unreadable = diagnoseUnreadableLedger(query, days)
787
1517
  if (unreadable !== undefined) return failure('UNSUPPORTED', unreadable)
788
- return `status: OK\n${renderMarkdown(query, days)}`
1518
+ return `status: OK\n${renderMarkdown(query, days, pricing)}`
789
1519
  }
790
1520
 
791
- const execute = async (args: { days?: number }, _ctx: ToolContextLike): Promise<string> => {
1521
+ const execute = async (args: CostArgs, _ctx: ToolContextLike): Promise<string> => {
792
1522
  const days = args?.days ?? 7
793
1523
  try {
794
1524
  const dbPath = findExistingDb(options?.dbPath)
@@ -799,6 +1529,16 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
799
1529
  `opencode.db not found (expected at ${expected}). No token history is available until opencode has stored session data.`,
800
1530
  )
801
1531
  }
1532
+ // Pricing never blocks a default call: `refreshPricing` is the only path
1533
+ // that awaits the catalog, and it is bounded by a short timeout.
1534
+ const pricing =
1535
+ args?.refreshPricing === true
1536
+ ? await forceRefreshPricing(options?.pricing)
1537
+ : loadPricing(options?.pricing).snapshot
1538
+ const queryOptions: CostQueryOptions = {
1539
+ pricing,
1540
+ ...(args?.session === undefined ? {} : { sessionRoot: args.session }),
1541
+ }
802
1542
  let sqlite: SqliteModule | undefined
803
1543
  try {
804
1544
  sqlite = await loadSqlite()
@@ -806,15 +1546,29 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
806
1546
  // node:sqlite unavailable (e.g. Bun runtime) — fall back to CLI.
807
1547
  const status = statusForError(loadErr)
808
1548
  if (status === 'UNSUPPORTED') {
1549
+ // The mirror reports tokens only and carries no session ids, so it
1550
+ // cannot answer a scoped question. Rendering an unscoped total under a
1551
+ // scoped question is exactly the plausible-but-wrong number this
1552
+ // report exists to prevent, so the request is refused instead.
1553
+ if (args?.session !== undefined) {
1554
+ return failure(
1555
+ 'UNSUPPORTED',
1556
+ `session scoping requires the node:sqlite backend, which this runtime does not provide (${diagnostic(loadErr)}). The CLI fallback reports tokens only and cannot resolve a session tree; re-run on Node.js >= ${NODE_SQLITE_MIN_VERSION} or drop "session".`,
1557
+ )
1558
+ }
809
1559
  try {
810
- return render(await queryWithCliFallback(dbPath, days, options?.cliFallback), days)
1560
+ return render(
1561
+ await queryWithCliFallback(dbPath, days, options?.cliFallback),
1562
+ days,
1563
+ pricing,
1564
+ )
811
1565
  } catch (cliErr: unknown) {
812
1566
  return failure(statusForError(cliErr), diagnostic(cliErr))
813
1567
  }
814
1568
  }
815
1569
  throw loadErr
816
1570
  }
817
- return render(queryWithSqlite(dbPath, days, sqlite), days)
1571
+ return render(queryWithSqlite(dbPath, days, sqlite, queryOptions), days, pricing)
818
1572
  } catch (err: unknown) {
819
1573
  return failure(statusForError(err), diagnostic(err))
820
1574
  }
@@ -823,7 +1577,7 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
823
1577
  return {
824
1578
  pantheon_cost: {
825
1579
  description:
826
- 'Report input, output, and total token usage by agent and phase over the last N days, read from opencode.db (read-only, no monetary values). The report states the coverage window it actually covers.',
1580
+ 'Report input, output, cache and total token usage together with USD cost, by agent and phase, by model, and by session, in a rolling N × 24-hour window from query time (read-only). Costs come from the models.dev catalog, cached on disk; a tool call reads the cache and never waits on the network unless refreshPricing is set. An unknown or unpriced model reads — and is excluded from the totals, never priced at zero, and the total says it is partial. Pass session:<id> to aggregate that root session plus its descendant sessions. Phase may be unknown on V2. Costs are catalog list prices, not an invoice. The report states the coverage window it actually covers and whether its prices are stale.',
827
1581
  args: costArgs,
828
1582
  execute,
829
1583
  },