pantheon-opencode 1.6.0-beta.9 → 1.6.1
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/AGENTS.global.md +118 -0
- package/AGENTS.md +18 -168
- package/CHANGELOG.md +144 -365
- package/README.md +124 -607
- package/README.pt-BR.md +120 -345
- package/bin/pantheon-init.mjs +504 -141
- package/commands/pantheon-deepwork.md +14 -3
- package/commands/pantheon-vision.md +61 -12
- package/package.json +22 -13
- package/plugin.json +1 -1
- package/pyproject.toml +6 -2
- package/scripts/_pantheon_paths.py +24 -0
- package/scripts/build-agents-md.mjs +368 -69
- package/scripts/changelog-merge.mjs +161 -0
- package/scripts/check-plugin-v2-coverage.mjs +11 -8
- package/scripts/docs-check-changelog.mjs +204 -0
- package/scripts/docs-link-check.mjs +314 -0
- package/scripts/docs-media.mjs +157 -0
- package/scripts/doctor.mjs +850 -45
- package/scripts/install/agents-md.mjs +2 -2
- package/scripts/install/backup.mjs +648 -0
- package/scripts/install/cli-ui.mjs +303 -72
- package/scripts/install/component-selection.mjs +61 -0
- package/scripts/install/config-migration.mjs +583 -27
- package/scripts/install/exit-codes.mjs +26 -0
- package/scripts/install/file-inventory.mjs +555 -0
- package/scripts/install/health-check.mjs +31 -25
- package/scripts/install/interactive.mjs +99 -383
- package/scripts/install/interrupt.mjs +78 -0
- package/scripts/install/migrate.mjs +49 -25
- package/scripts/install/model-picker.mjs +218 -250
- package/scripts/install/opencode-state.mjs +91 -0
- package/scripts/install/opencode-version.mjs +83 -21
- package/scripts/install/opencode.mjs +1675 -187
- package/scripts/install/plan-artifact.mjs +517 -0
- package/scripts/install/plan.mjs +475 -0
- package/scripts/install/plugin.mjs +214 -27
- package/scripts/install/prompt-result.mjs +2 -0
- package/scripts/install/run-record.mjs +115 -0
- package/scripts/install/shared.mjs +256 -99
- package/scripts/install/state.mjs +63 -8
- package/scripts/install/strings.mjs +93 -8
- package/scripts/install/v2-capabilities.mjs +205 -0
- package/scripts/install/venv.mjs +90 -47
- package/scripts/install/verify.mjs +128 -0
- package/scripts/install/vision-prompt.mjs +173 -0
- package/scripts/install-mcp.mjs +2 -2
- package/scripts/manifest-inventory.mjs +49 -3
- package/scripts/mcp_persistence.py +1535 -1050
- package/scripts/memory_mcp.py +12 -843
- package/scripts/node-engine-policy.mjs +85 -0
- package/scripts/package-evidence.mjs +10 -2
- package/scripts/postinstall.mjs +26 -26
- package/scripts/probe-pantheon-cost.mjs +118 -19
- package/scripts/prune.mjs +9 -3
- package/scripts/reconcile.mjs +325 -0
- package/scripts/release-gates.mjs +687 -0
- package/scripts/restore.mjs +222 -0
- package/scripts/run-node-tests.mjs +24 -8
- package/scripts/sync-artifacts.mjs +19 -7
- package/scripts/sync-tui.mjs +5 -1
- package/scripts/test-opencode-v2-sandbox.sh +36 -123
- package/scripts/uninstall.mjs +369 -34
- package/scripts/update.mjs +164 -0
- package/scripts/validate-node-engine-policy.mjs +13 -0
- package/scripts/version-check.mjs +34 -1
- package/scripts/versioning.mjs +23 -3
- package/scripts/vision-status.mjs +682 -0
- package/skills-lock.json +8 -8
- package/src/agents/aphrodite.md +13 -10
- package/src/agents/apollo.md +4 -5
- package/src/agents/athena.md +74 -46
- package/src/agents/demeter.md +10 -7
- package/src/agents/gaia.md +0 -1
- package/src/agents/hephaestus.md +4 -3
- package/src/agents/hermes.md +10 -9
- package/src/agents/iris.md +6 -1
- package/src/agents/mnemosyne.md +10 -4
- package/src/agents/nyx.md +4 -4
- package/src/agents/prometheus.md +12 -11
- package/src/agents/talos.md +6 -0
- package/src/agents/zeus.md +84 -56
- package/src/instructions/agent-return-format.instructions.md +12 -41
- package/src/instructions/memory-protocol.instructions.md +5 -11
- package/src/instructions/test-economy.instructions.md +12 -0
- package/src/instructions/yagni.instructions.md +6 -15
- package/src/instructions/zeus-anti-stall.instructions.md +6 -6
- package/src/instructions/zeus-communication-rules.instructions.md +6 -6
- package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
- package/src/instructions/zeus-memory-operations.instructions.md +13 -7
- package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
- package/src/mcp/_pantheon_paths.py +24 -0
- package/src/mcp/mcp_codemap_module.py +86 -18
- package/src/mcp/mcp_persistence.py +1535 -1050
- package/src/mcp/memory_mcp.py +444 -94
- package/src/mcp/pantheon_vision.py +285 -41
- package/src/mcp/requirements-mcp.txt +6 -1
- package/src/mcp/requirements-vision.txt +1 -1
- package/src/pantheon/context-pruner.ts +541 -0
- package/src/pantheon/cost-command.ts +901 -60
- package/src/pantheon/delegation-enforce.ts +160 -23
- package/src/pantheon/goal-loop.ts +11 -8
- package/src/pantheon/guard-path.ts +162 -0
- package/src/pantheon/memory-context.ts +1017 -0
- package/src/pantheon/model-agents.ts +19 -0
- package/src/pantheon/model-command.ts +218 -56
- package/src/pantheon/model-pricing.ts +536 -0
- package/src/pantheon/presets.mjs +2 -0
- package/src/pantheon/task-result-guard.ts +50 -14
- package/src/pantheon/v2-bounded-read.ts +654 -0
- package/src/pantheon/v2-bridge.ts +27 -0
- package/src/pantheon/v2-delegation-enforce.ts +133 -6
- package/src/pantheon/v2-execute-after.ts +135 -24
- package/src/pantheon/v2-model-overrides.ts +275 -0
- package/src/pantheon/v2-shell-hooks.ts +260 -0
- package/src/pantheon/v2-tools.ts +89 -35
- package/src/pantheon/v2-unsupported.mjs +34 -7
- package/src/pantheon/v2-vision.ts +622 -0
- package/src/pantheon/vision-local.ts +531 -0
- package/src/pantheon/vision.ts +1166 -116
- package/src/plugin-v2.ts +1039 -171
- package/src/plugin.ts +37 -13
- package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +3742 -85
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +15 -15
- package/src/plugins/tui/package.json +7 -5
- package/src/plugins/tui/src/index-v2.tsx +4314 -50
- package/src/plugins/tui/tsconfig.typecheck.json +5 -0
- package/src/routing.yml +50 -5
- package/src/skills/agent-coordination/SKILL.md +7 -2
- package/src/skills/artifact-management/SKILL.md +5 -1
- package/src/skills/auto-continue/SKILL.md +14 -6
- package/src/skills/codemap/SKILL.md +1 -1
- package/src/skills/memory-bank/SKILL.md +21 -13
- package/src/skills/session-goal/SKILL.md +12 -22
- package/src/skills/spec-driven-development/SKILL.md +3 -1
- package/src/skills/worktrees/SKILL.md +30 -11
- package/scripts/probe-context-rehydrate.mjs +0 -263
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
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)
|
|
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,61 @@ export interface CostRow {
|
|
|
50
63
|
tokensInput: number
|
|
51
64
|
tokensOutput: number
|
|
52
65
|
tokensTotal: number
|
|
66
|
+
/**
|
|
67
|
+
* USD for this row: the sum of every contributing model's own priced cost.
|
|
68
|
+
* Absent only when NO contributing model could be priced — a row that mixes
|
|
69
|
+
* priced and unpriced models keeps its numeric part.
|
|
70
|
+
*/
|
|
71
|
+
costUsd?: number
|
|
72
|
+
/**
|
|
73
|
+
* Number of contributing model groups the catalog could not price. Present
|
|
74
|
+
* only alongside `costUsd`, so the reader can tell a partially priced row
|
|
75
|
+
* (money shown, some tokens unpriced) from a fully priced one.
|
|
76
|
+
*/
|
|
77
|
+
unpricedModels?: number
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** One aggregated row per (agent, phase, provider, model). */
|
|
81
|
+
export interface CostModelRow {
|
|
82
|
+
agent: string
|
|
83
|
+
phase: string
|
|
84
|
+
provider: string
|
|
85
|
+
model: string
|
|
86
|
+
tokensInput: number
|
|
87
|
+
tokensOutput: number
|
|
88
|
+
tokensCacheRead: number
|
|
89
|
+
tokensCacheWrite: number
|
|
90
|
+
tokensTotal: number
|
|
91
|
+
costUsd?: number
|
|
92
|
+
unpricedReason?: UnpricedReason
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** One aggregated row per session (a node of the session tree). */
|
|
96
|
+
export interface CostSessionRow {
|
|
97
|
+
sessionId: string
|
|
98
|
+
title?: string
|
|
99
|
+
agents: string[]
|
|
100
|
+
tokensInput: number
|
|
101
|
+
tokensOutput: number
|
|
102
|
+
tokensCacheRead: number
|
|
103
|
+
tokensCacheWrite: number
|
|
104
|
+
tokensTotal: number
|
|
105
|
+
/** Sum of the priced model rows in this session; absent when none priced. */
|
|
106
|
+
costUsd?: number
|
|
107
|
+
/** Unpriced model rows folded into this session; present with `costUsd`. */
|
|
108
|
+
unpricedModels?: number
|
|
109
|
+
unpricedReason?: UnpricedReason
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The session subtree a report was scoped to, when `session` was requested. */
|
|
113
|
+
export interface CostSessionScope {
|
|
114
|
+
rootId: string
|
|
115
|
+
/** Root plus every descendant found in the session tables. */
|
|
116
|
+
ids: string[]
|
|
117
|
+
/** False when the root id has no row in the session tables. */
|
|
118
|
+
rootKnown: boolean
|
|
119
|
+
/** False when the database carries no session metadata table at all. */
|
|
120
|
+
hierarchy: boolean
|
|
53
121
|
}
|
|
54
122
|
|
|
55
123
|
/**
|
|
@@ -89,6 +157,12 @@ export interface CostCoverage {
|
|
|
89
157
|
export interface CostQuery {
|
|
90
158
|
rows: CostRow[]
|
|
91
159
|
coverage: CostCoverage
|
|
160
|
+
/** Per-model breakdown. Absent on the CLI-fallback path, which reports tokens only. */
|
|
161
|
+
byModel?: CostModelRow[]
|
|
162
|
+
/** Per-session breakdown. Absent on the CLI-fallback path. */
|
|
163
|
+
bySession?: CostSessionRow[]
|
|
164
|
+
/** Set when the report was scoped to one session tree. */
|
|
165
|
+
sessionScope?: CostSessionScope
|
|
92
166
|
}
|
|
93
167
|
|
|
94
168
|
export interface CostCommandOptions {
|
|
@@ -98,6 +172,8 @@ export interface CostCommandOptions {
|
|
|
98
172
|
sqliteLoader?: () => Promise<SqliteModule>
|
|
99
173
|
/** Injectable CLI-fallback process boundary (tests / unusual runtimes). */
|
|
100
174
|
cliFallback?: CliFallbackDeps
|
|
175
|
+
/** Pricing cache / fetch boundary (tests, air-gapped hosts). */
|
|
176
|
+
pricing?: PricingOptions
|
|
101
177
|
}
|
|
102
178
|
|
|
103
179
|
export type OpenCodeVersion = 'v1' | 'v2'
|
|
@@ -129,9 +205,25 @@ const costArgs = {
|
|
|
129
205
|
.min(1)
|
|
130
206
|
.max(365)
|
|
131
207
|
.optional()
|
|
132
|
-
.describe('Number of days of
|
|
208
|
+
.describe('Number of rolling 24-hour days of history to include (default 7).'),
|
|
209
|
+
session: z
|
|
210
|
+
.string()
|
|
211
|
+
.min(1)
|
|
212
|
+
.optional()
|
|
213
|
+
.describe(
|
|
214
|
+
'Session id to scope the report to: the root session plus every descendant session in its subtree.',
|
|
215
|
+
),
|
|
216
|
+
refreshPricing: z
|
|
217
|
+
.boolean()
|
|
218
|
+
.optional()
|
|
219
|
+
.describe(
|
|
220
|
+
'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.',
|
|
221
|
+
),
|
|
133
222
|
} satisfies z.ZodRawShape
|
|
134
223
|
|
|
224
|
+
/** Parsed arguments of the cost tool. */
|
|
225
|
+
type CostArgs = z.infer<z.ZodObject<typeof costArgs>>
|
|
226
|
+
|
|
135
227
|
/** The XDG state directory every real host installation writes its ledger to. */
|
|
136
228
|
function defaultDbPath(): string {
|
|
137
229
|
const xdg = process.env.XDG_DATA_HOME
|
|
@@ -215,63 +307,209 @@ function resolveSources(db: SqliteDatabase, requested: OpenCodeVersion | undefin
|
|
|
215
307
|
}
|
|
216
308
|
|
|
217
309
|
/**
|
|
218
|
-
* Per-family aggregation.
|
|
310
|
+
* Per-family aggregation, grouped finely enough to price and to attribute.
|
|
219
311
|
*
|
|
220
312
|
* Aggregating in SQL instead of pulling `data` blobs into JS is not a
|
|
221
313
|
* micro-optimisation: the host's own 7-day window is 271 MB across 26410
|
|
222
314
|
* assistant rows, and the equivalent SQL finishes in 0.9 s over the
|
|
223
315
|
* time_created index.
|
|
224
316
|
*
|
|
225
|
-
*
|
|
317
|
+
* The grouping key is (agent, phase, provider, model, session): the first two
|
|
318
|
+
* keep the historical by-agent table, the middle two are what a price can be
|
|
319
|
+
* looked up for, and the last one is what a spend attribution needs. Cost is
|
|
320
|
+
* computed in JS from these groups, so there is exactly ONE set of token sums
|
|
321
|
+
* behind every table in the report.
|
|
322
|
+
*
|
|
323
|
+
* Three correctness details are load-bearing:
|
|
226
324
|
* - `json_valid(data)` gates every extraction, because `json_extract` and
|
|
227
325
|
* `->>` both RAISE on malformed JSON in node:sqlite's bundled SQLite. The
|
|
228
326
|
* inner CTE applies it before extracting anything, so the outer query can
|
|
229
327
|
* never see an unparseable payload whatever order SQLite evaluates terms in.
|
|
230
328
|
* - `COALESCE(SUM(...), 0)` — a group whose tokens are all NULL sums to NULL,
|
|
231
329
|
* and adding NULL into an accumulator would print NaN into the report.
|
|
330
|
+
* - `session_id` is read only when the LEDGER table carries it. A real V1 and
|
|
331
|
+
* V2 table both do, but a partial database (or a hand-built fixture) may
|
|
332
|
+
* not, and selecting a missing column would fail the whole report instead
|
|
333
|
+
* of dropping the session view.
|
|
232
334
|
*
|
|
233
335
|
* V1 marks assistant turns with `data.role`; V2 marks them with the `type`
|
|
234
336
|
* COLUMN. V2 carries no `role` key, so the V1 predicate would match nothing.
|
|
235
337
|
*/
|
|
236
|
-
const
|
|
237
|
-
message: `
|
|
338
|
+
const COST_AGGREGATE_SQL: Record<CostSource, (sessionId: boolean) => string> = {
|
|
339
|
+
message: (sessionId) => `
|
|
238
340
|
WITH valid AS (
|
|
239
341
|
SELECT json_extract(data, '$.role') AS role,
|
|
240
342
|
json_extract(data, '$.agent') AS agent,
|
|
241
|
-
json_extract(data, '$.phase')
|
|
242
|
-
|
|
343
|
+
COALESCE(NULLIF(json_extract(data, '$.phase'), ''),
|
|
344
|
+
NULLIF(json_extract(data, '$.metadata.phase'), ''),
|
|
345
|
+
'unknown') AS phase,
|
|
346
|
+
COALESCE(json_extract(data, '$.model.providerID'),
|
|
347
|
+
json_extract(data, '$.providerID')) AS provider,
|
|
348
|
+
COALESCE(json_extract(data, '$.model.id'),
|
|
349
|
+
json_extract(data, '$.modelID')) AS model,
|
|
350
|
+
${sessionId ? 'session_id' : 'NULL'} AS sessionId,
|
|
243
351
|
CAST(json_extract(data, '$.tokens.input') AS INTEGER) AS inTok,
|
|
244
|
-
CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok
|
|
352
|
+
CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok,
|
|
353
|
+
CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER) AS cacheReadTok,
|
|
354
|
+
CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER) AS cacheWriteTok
|
|
245
355
|
FROM message
|
|
246
356
|
WHERE time_created >= ? AND json_valid(data)
|
|
247
357
|
)
|
|
248
358
|
SELECT agent AS agent,
|
|
249
|
-
|
|
359
|
+
phase AS phase,
|
|
360
|
+
provider AS provider,
|
|
361
|
+
model AS model,
|
|
362
|
+
sessionId AS sessionId,
|
|
250
363
|
COALESCE(SUM(inTok), 0) AS tokensInput,
|
|
251
364
|
COALESCE(SUM(outTok), 0) AS tokensOutput,
|
|
252
|
-
|
|
365
|
+
COALESCE(SUM(cacheReadTok), 0) AS tokensCacheRead,
|
|
366
|
+
COALESCE(SUM(cacheWriteTok), 0) AS tokensCacheWrite
|
|
253
367
|
FROM valid
|
|
254
368
|
WHERE role = 'assistant'
|
|
255
|
-
GROUP BY
|
|
369
|
+
GROUP BY agent, phase, provider, model, sessionId
|
|
256
370
|
HAVING agent IS NOT NULL AND agent != ''`,
|
|
257
|
-
session_message: `
|
|
371
|
+
session_message: (sessionId) => `
|
|
258
372
|
WITH valid AS (
|
|
259
373
|
SELECT json_extract(data, '$.agent') AS agent,
|
|
374
|
+
'unknown' AS phase,
|
|
375
|
+
COALESCE(json_extract(data, '$.model.providerID'),
|
|
376
|
+
json_extract(data, '$.providerID')) AS provider,
|
|
377
|
+
COALESCE(json_extract(data, '$.model.id'),
|
|
378
|
+
json_extract(data, '$.modelID')) AS model,
|
|
379
|
+
${sessionId ? 'session_id' : 'NULL'} AS sessionId,
|
|
260
380
|
CAST(json_extract(data, '$.tokens.input') AS INTEGER) AS inTok,
|
|
261
|
-
CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok
|
|
381
|
+
CAST(json_extract(data, '$.tokens.output') AS INTEGER) AS outTok,
|
|
382
|
+
CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER) AS cacheReadTok,
|
|
383
|
+
CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER) AS cacheWriteTok
|
|
262
384
|
FROM session_message
|
|
263
385
|
WHERE time_created >= ? AND type = 'assistant' AND json_valid(data)
|
|
264
386
|
)
|
|
265
387
|
SELECT agent AS agent,
|
|
266
|
-
|
|
388
|
+
phase AS phase,
|
|
389
|
+
provider AS provider,
|
|
390
|
+
model AS model,
|
|
391
|
+
sessionId AS sessionId,
|
|
267
392
|
COALESCE(SUM(inTok), 0) AS tokensInput,
|
|
268
393
|
COALESCE(SUM(outTok), 0) AS tokensOutput,
|
|
269
|
-
|
|
394
|
+
COALESCE(SUM(cacheReadTok), 0) AS tokensCacheRead,
|
|
395
|
+
COALESCE(SUM(cacheWriteTok), 0) AS tokensCacheWrite
|
|
270
396
|
FROM valid
|
|
271
|
-
GROUP BY
|
|
397
|
+
GROUP BY agent, phase, provider, model, sessionId
|
|
272
398
|
HAVING agent IS NOT NULL AND agent != ''`,
|
|
273
399
|
}
|
|
274
400
|
|
|
401
|
+
/** One row of the aggregated ledger query. */
|
|
402
|
+
interface LedgerGroup {
|
|
403
|
+
agent?: unknown
|
|
404
|
+
phase?: unknown
|
|
405
|
+
provider?: unknown
|
|
406
|
+
model?: unknown
|
|
407
|
+
sessionId?: unknown
|
|
408
|
+
tokensInput?: unknown
|
|
409
|
+
tokensOutput?: unknown
|
|
410
|
+
tokensCacheRead?: unknown
|
|
411
|
+
tokensCacheWrite?: unknown
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** One session row from the metadata tables. */
|
|
415
|
+
interface CostSessionInfo {
|
|
416
|
+
id: string
|
|
417
|
+
parentId?: string
|
|
418
|
+
title?: string
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** Session metadata of the whole database, plus the parent→children index. */
|
|
422
|
+
interface CostSessionIndex {
|
|
423
|
+
nodes: Map<string, CostSessionInfo>
|
|
424
|
+
children: Map<string, string[]>
|
|
425
|
+
/** Metadata tables that were read. */
|
|
426
|
+
tables: string[]
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Table families that carry session ids and parent ids. */
|
|
430
|
+
const SESSION_TABLES: readonly string[] = ['session_v2', 'session']
|
|
431
|
+
|
|
432
|
+
/** Column names of one table; empty when the table does not exist. */
|
|
433
|
+
function tableColumns(db: SqliteDatabase, table: string): Set<string> {
|
|
434
|
+
// Interpolated names come from the module's own constant list, never from a
|
|
435
|
+
// caller or a payload, so no value can reach this string.
|
|
436
|
+
try {
|
|
437
|
+
const rows = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name?: unknown }>
|
|
438
|
+
return new Set(rows.map((row) => String(row.name)))
|
|
439
|
+
} catch {
|
|
440
|
+
return new Set()
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Read session metadata: ids, parent ids and titles.
|
|
446
|
+
*
|
|
447
|
+
* A migrated database carries BOTH families, and their id spaces are disjoint,
|
|
448
|
+
* so both are read and merged. Fields a family does not have are simply absent
|
|
449
|
+
* rather than fabricated.
|
|
450
|
+
*/
|
|
451
|
+
function readSessionIndex(db: SqliteDatabase): CostSessionIndex {
|
|
452
|
+
const nodes = new Map<string, CostSessionInfo>()
|
|
453
|
+
const children = new Map<string, string[]>()
|
|
454
|
+
const tables: string[] = []
|
|
455
|
+
for (const table of SESSION_TABLES) {
|
|
456
|
+
const columns = tableColumns(db, table)
|
|
457
|
+
if (columns.size === 0 || !columns.has('id')) continue
|
|
458
|
+
tables.push(table)
|
|
459
|
+
const parent = columns.has('parent_id') ? 'parent_id' : 'NULL'
|
|
460
|
+
const title = columns.has('title') ? 'title' : 'NULL'
|
|
461
|
+
const rows = db
|
|
462
|
+
.prepare(`SELECT id, ${parent} AS parentId, ${title} AS title FROM ${table}`)
|
|
463
|
+
.all() as Array<{
|
|
464
|
+
id?: unknown
|
|
465
|
+
parentId?: unknown
|
|
466
|
+
title?: unknown
|
|
467
|
+
}>
|
|
468
|
+
for (const row of rows) {
|
|
469
|
+
const id = String(row.id ?? '')
|
|
470
|
+
if (id === '') continue
|
|
471
|
+
const parentId =
|
|
472
|
+
row.parentId === null || row.parentId === undefined ? undefined : String(row.parentId)
|
|
473
|
+
const title = row.title === null || row.title === undefined ? undefined : String(row.title)
|
|
474
|
+
nodes.set(id, {
|
|
475
|
+
id,
|
|
476
|
+
...(parentId === undefined ? {} : { parentId }),
|
|
477
|
+
...(title === undefined ? {} : { title }),
|
|
478
|
+
})
|
|
479
|
+
if (parentId !== undefined) {
|
|
480
|
+
const bucket = children.get(parentId) ?? []
|
|
481
|
+
bucket.push(id)
|
|
482
|
+
children.set(parentId, bucket)
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return { nodes, children, tables }
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Root session plus every descendant, by parent id.
|
|
491
|
+
*
|
|
492
|
+
* A visited set bounds the walk: a database that (through a bug or a manual
|
|
493
|
+
* edit) contains a parent cycle must not hang a tool call.
|
|
494
|
+
*/
|
|
495
|
+
function resolveSessionTree(
|
|
496
|
+
index: CostSessionIndex,
|
|
497
|
+
rootId: string,
|
|
498
|
+
): { ids: string[]; rootKnown: boolean } {
|
|
499
|
+
const ids = new Set<string>([rootId])
|
|
500
|
+
const queue: string[] = [rootId]
|
|
501
|
+
for (let cursor = 0; cursor < queue.length; cursor += 1) {
|
|
502
|
+
const current = queue[cursor]
|
|
503
|
+
if (current === undefined) continue
|
|
504
|
+
for (const child of index.children.get(current) ?? []) {
|
|
505
|
+
if (ids.has(child)) continue
|
|
506
|
+
ids.add(child)
|
|
507
|
+
queue.push(child)
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return { ids: [...ids], rootKnown: index.nodes.has(rootId) }
|
|
511
|
+
}
|
|
512
|
+
|
|
275
513
|
/**
|
|
276
514
|
* Window counters — the evidence a diagnosis is built from. A report that
|
|
277
515
|
* scanned rows but matched no assistant row must say so rather than render an
|
|
@@ -310,6 +548,68 @@ function emptyCoverage(sources: CostSource[]): CostCoverage {
|
|
|
310
548
|
return { sources, scanned: 0, assistantRows: 0 }
|
|
311
549
|
}
|
|
312
550
|
|
|
551
|
+
/** Options for one ledger read. */
|
|
552
|
+
export interface CostQueryOptions {
|
|
553
|
+
/** Prices to apply. Absent ⇒ every cost is reported as unavailable. */
|
|
554
|
+
pricing?: PricingSnapshot
|
|
555
|
+
/** Session id to scope to: the root plus every descendant session. */
|
|
556
|
+
sessionRoot?: string
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** One model group while a report is being assembled. */
|
|
560
|
+
interface ModelAccumulator {
|
|
561
|
+
agent: string
|
|
562
|
+
phase: string
|
|
563
|
+
provider: string
|
|
564
|
+
model: 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
|
+
/** One session group while a report is being assembled. */
|
|
575
|
+
interface SessionAccumulator {
|
|
576
|
+
sessionId: string
|
|
577
|
+
agents: Set<string>
|
|
578
|
+
tokensInput: number
|
|
579
|
+
tokensOutput: number
|
|
580
|
+
tokensCacheRead: number
|
|
581
|
+
tokensCacheWrite: number
|
|
582
|
+
/** Priced dollars accumulated; meaningful only when `priced` > 0. */
|
|
583
|
+
usd: number
|
|
584
|
+
/** Model rows that produced a price. */
|
|
585
|
+
priced: number
|
|
586
|
+
/** Model rows with no usable catalog price. */
|
|
587
|
+
unpricedModels: number
|
|
588
|
+
reason: UnpricedReason | undefined
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** A ledger label the catalog cannot know; never an empty string. */
|
|
592
|
+
function ledgerLabel(value: unknown): string {
|
|
593
|
+
if (value === undefined || value === null) return 'unknown'
|
|
594
|
+
const text = String(value).trim()
|
|
595
|
+
return text === '' ? 'unknown' : text
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** Price one group, or explain why it cannot be priced. */
|
|
599
|
+
function priceTokens(
|
|
600
|
+
pricing: PricingSnapshot | undefined,
|
|
601
|
+
provider: string,
|
|
602
|
+
model: string,
|
|
603
|
+
tokens: { input: number; output: number; cacheRead: number; cacheWrite: number },
|
|
604
|
+
): { usd: number } | { reason: UnpricedReason } {
|
|
605
|
+
if (pricing === undefined) return { reason: 'no-pricing' }
|
|
606
|
+
const lookup = lookupModelPrice(pricing, provider, model)
|
|
607
|
+
if (!lookup.ok) return { reason: lookup.reason }
|
|
608
|
+
const cost = computeModelCost(lookup.price, tokens)
|
|
609
|
+
if (!cost.ok) return { reason: cost.reason }
|
|
610
|
+
return { usd: cost.usd }
|
|
611
|
+
}
|
|
612
|
+
|
|
313
613
|
/**
|
|
314
614
|
* Read the token ledger of one database, read-only.
|
|
315
615
|
*
|
|
@@ -317,19 +617,29 @@ function emptyCoverage(sources: CostSource[]): CostCoverage {
|
|
|
317
617
|
* the same answer in tests. The script cannot import this module: it runs on a
|
|
318
618
|
* plain Node precisely because node:sqlite is missing from the plugin runtime.
|
|
319
619
|
*/
|
|
320
|
-
export async function queryCostRows(
|
|
620
|
+
export async function queryCostRows(
|
|
621
|
+
dbPath: string,
|
|
622
|
+
days: number,
|
|
623
|
+
options?: CostQueryOptions,
|
|
624
|
+
): Promise<CostQuery> {
|
|
321
625
|
const sqlite = (await import('node:sqlite')) as SqliteModule
|
|
322
|
-
return queryWithSqlite(dbPath, days, sqlite)
|
|
626
|
+
return queryWithSqlite(dbPath, days, sqlite, options)
|
|
323
627
|
}
|
|
324
628
|
|
|
325
629
|
/** Shared aggregation path for the in-process reader and queryCostRows. */
|
|
326
|
-
function queryWithSqlite(
|
|
630
|
+
function queryWithSqlite(
|
|
631
|
+
dbPath: string,
|
|
632
|
+
days: number,
|
|
633
|
+
sqlite: SqliteModule,
|
|
634
|
+
options?: CostQueryOptions,
|
|
635
|
+
): CostQuery {
|
|
327
636
|
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true })
|
|
328
637
|
try {
|
|
329
638
|
const sources = resolveSources(db, requestedVersion())
|
|
330
639
|
const since = Date.now() - days * 86_400_000
|
|
331
|
-
const byAgentAndPhase = new Map<string, CostRow>()
|
|
332
640
|
const coverage = emptyCoverage([])
|
|
641
|
+
const models = new Map<string, ModelAccumulator>()
|
|
642
|
+
const sessions = new Map<string, SessionAccumulator>()
|
|
333
643
|
|
|
334
644
|
const note = (key: 'windowStart' | 'databaseStart', value: number | undefined): void => {
|
|
335
645
|
if (value === undefined) return
|
|
@@ -337,6 +647,23 @@ function queryWithSqlite(dbPath: string, days: number, sqlite: SqliteModule): Co
|
|
|
337
647
|
coverage[key] = current === undefined ? value : Math.min(current, value)
|
|
338
648
|
}
|
|
339
649
|
|
|
650
|
+
// Session metadata is read once: the tree is needed both to scope a report
|
|
651
|
+
// and to label the rows of the session view.
|
|
652
|
+
const sessionIndex = readSessionIndex(db)
|
|
653
|
+
const sessionRoot = options?.sessionRoot
|
|
654
|
+
let sessionScope: CostSessionScope | undefined
|
|
655
|
+
let scopedIds: Set<string> | undefined
|
|
656
|
+
if (sessionRoot !== undefined) {
|
|
657
|
+
const tree = resolveSessionTree(sessionIndex, sessionRoot)
|
|
658
|
+
scopedIds = new Set(tree.ids)
|
|
659
|
+
sessionScope = {
|
|
660
|
+
rootId: sessionRoot,
|
|
661
|
+
ids: tree.ids,
|
|
662
|
+
rootKnown: tree.rootKnown,
|
|
663
|
+
hierarchy: sessionIndex.tables.length > 0,
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
340
667
|
for (const source of sources) {
|
|
341
668
|
const countersRow = (
|
|
342
669
|
db.prepare(COUNTER_SQL[source]).all(since, since, since) as Array<Counters>
|
|
@@ -353,38 +680,185 @@ function queryWithSqlite(dbPath: string, days: number, sqlite: SqliteModule): Co
|
|
|
353
680
|
),
|
|
354
681
|
)
|
|
355
682
|
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
}>
|
|
683
|
+
const hasSessionColumn = tableColumns(db, source).has('session_id')
|
|
684
|
+
const groups = db
|
|
685
|
+
.prepare(COST_AGGREGATE_SQL[source](hasSessionColumn))
|
|
686
|
+
.all(since) as Array<LedgerGroup>
|
|
687
|
+
|
|
362
688
|
for (const group of groups) {
|
|
363
689
|
const agent = String(group.agent ?? '')
|
|
364
690
|
if (agent === '') continue
|
|
365
|
-
const phase =
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
const
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
691
|
+
const phase = ledgerLabel(group.phase)
|
|
692
|
+
const provider = ledgerLabel(group.provider)
|
|
693
|
+
const model = ledgerLabel(group.model)
|
|
694
|
+
const sessionId =
|
|
695
|
+
group.sessionId === undefined || group.sessionId === null
|
|
696
|
+
? undefined
|
|
697
|
+
: String(group.sessionId)
|
|
698
|
+
// A scoped report keeps only rows inside the requested subtree. A row
|
|
699
|
+
// with no session id cannot be proven to belong to it, so it is out.
|
|
700
|
+
if (scopedIds !== undefined && (sessionId === undefined || !scopedIds.has(sessionId))) {
|
|
701
|
+
continue
|
|
702
|
+
}
|
|
703
|
+
const tokens = {
|
|
704
|
+
input: numberOf(group.tokensInput) ?? 0,
|
|
705
|
+
output: numberOf(group.tokensOutput) ?? 0,
|
|
706
|
+
cacheRead: numberOf(group.tokensCacheRead) ?? 0,
|
|
707
|
+
cacheWrite: numberOf(group.tokensCacheWrite) ?? 0,
|
|
708
|
+
}
|
|
709
|
+
const priced = priceTokens(options?.pricing, provider, model, tokens)
|
|
710
|
+
|
|
711
|
+
// Keyed on NUL separators: none of these labels can contain one, so no
|
|
712
|
+
// label ending in another label's text can collide with it.
|
|
713
|
+
const modelKey = `${agent}\u0000${phase}\u0000${provider}\u0000${model}`
|
|
714
|
+
const modelAcc = models.get(modelKey) ?? {
|
|
373
715
|
agent,
|
|
374
716
|
phase,
|
|
717
|
+
provider,
|
|
718
|
+
model,
|
|
375
719
|
tokensInput: 0,
|
|
376
720
|
tokensOutput: 0,
|
|
377
|
-
|
|
721
|
+
tokensCacheRead: 0,
|
|
722
|
+
tokensCacheWrite: 0,
|
|
723
|
+
usd: 0,
|
|
724
|
+
unpriced: false,
|
|
725
|
+
reason: undefined,
|
|
726
|
+
}
|
|
727
|
+
modelAcc.tokensInput += tokens.input
|
|
728
|
+
modelAcc.tokensOutput += tokens.output
|
|
729
|
+
modelAcc.tokensCacheRead += tokens.cacheRead
|
|
730
|
+
modelAcc.tokensCacheWrite += tokens.cacheWrite
|
|
731
|
+
if ('usd' in priced && modelAcc.usd !== undefined) {
|
|
732
|
+
modelAcc.usd += priced.usd
|
|
733
|
+
} else {
|
|
734
|
+
modelAcc.unpriced = true
|
|
735
|
+
modelAcc.usd = undefined
|
|
736
|
+
modelAcc.reason = modelAcc.reason ?? ('reason' in priced ? priced.reason : undefined)
|
|
737
|
+
}
|
|
738
|
+
models.set(modelKey, modelAcc)
|
|
739
|
+
|
|
740
|
+
if (sessionId === undefined) continue
|
|
741
|
+
const sessionAcc = sessions.get(sessionId) ?? {
|
|
742
|
+
sessionId,
|
|
743
|
+
agents: new Set<string>(),
|
|
744
|
+
tokensInput: 0,
|
|
745
|
+
tokensOutput: 0,
|
|
746
|
+
tokensCacheRead: 0,
|
|
747
|
+
tokensCacheWrite: 0,
|
|
748
|
+
usd: 0,
|
|
749
|
+
priced: 0,
|
|
750
|
+
unpricedModels: 0,
|
|
751
|
+
reason: undefined,
|
|
378
752
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
753
|
+
sessionAcc.agents.add(agent)
|
|
754
|
+
sessionAcc.tokensInput += tokens.input
|
|
755
|
+
sessionAcc.tokensOutput += tokens.output
|
|
756
|
+
sessionAcc.tokensCacheRead += tokens.cacheRead
|
|
757
|
+
sessionAcc.tokensCacheWrite += tokens.cacheWrite
|
|
758
|
+
if ('usd' in priced) {
|
|
759
|
+
sessionAcc.usd += priced.usd
|
|
760
|
+
sessionAcc.priced += 1
|
|
761
|
+
} else {
|
|
762
|
+
sessionAcc.unpricedModels += 1
|
|
763
|
+
sessionAcc.reason = sessionAcc.reason ?? priced.reason
|
|
764
|
+
}
|
|
765
|
+
sessions.set(sessionId, sessionAcc)
|
|
383
766
|
}
|
|
384
767
|
}
|
|
385
768
|
|
|
386
|
-
|
|
387
|
-
|
|
769
|
+
// The by-agent table is derived from the model groups, so every table in
|
|
770
|
+
// the report is backed by exactly one set of token sums. Cost is attributed
|
|
771
|
+
// per model and summed here: a bucket that spans several models is a sum of
|
|
772
|
+
// its priced models, never `—`, because an ambiguous bucket is not the same
|
|
773
|
+
// thing as an unknown price. `unpricedModels` records how many contributors
|
|
774
|
+
// had no catalog price, so `(partial)` keeps a single, honest meaning.
|
|
775
|
+
const byAgentPhase = new Map<
|
|
776
|
+
string,
|
|
777
|
+
{ row: CostRow; usd: number; priced: number; unpricedModels: number }
|
|
778
|
+
>()
|
|
779
|
+
for (const acc of models.values()) {
|
|
780
|
+
const key = `${acc.agent}\u0000${acc.phase}`
|
|
781
|
+
const entry = byAgentPhase.get(key) ?? {
|
|
782
|
+
row: {
|
|
783
|
+
agent: acc.agent,
|
|
784
|
+
phase: acc.phase,
|
|
785
|
+
tokensInput: 0,
|
|
786
|
+
tokensOutput: 0,
|
|
787
|
+
tokensTotal: 0,
|
|
788
|
+
},
|
|
789
|
+
usd: 0,
|
|
790
|
+
priced: 0,
|
|
791
|
+
unpricedModels: 0,
|
|
792
|
+
}
|
|
793
|
+
entry.row.tokensInput += acc.tokensInput
|
|
794
|
+
entry.row.tokensOutput += acc.tokensOutput
|
|
795
|
+
entry.row.tokensTotal += acc.tokensInput + acc.tokensOutput
|
|
796
|
+
if (acc.usd === undefined) {
|
|
797
|
+
entry.unpricedModels += 1
|
|
798
|
+
} else {
|
|
799
|
+
entry.usd += acc.usd
|
|
800
|
+
entry.priced += 1
|
|
801
|
+
}
|
|
802
|
+
byAgentPhase.set(key, entry)
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
const rows: CostRow[] = [...byAgentPhase.values()]
|
|
806
|
+
.map(({ row, usd, priced, unpricedModels }) => ({
|
|
807
|
+
...row,
|
|
808
|
+
// Absent cost means "nothing in this row could be priced"; a numeric
|
|
809
|
+
// cost with `unpricedModels` means "this row is partly priced".
|
|
810
|
+
...(priced === 0 ? {} : { costUsd: usd }),
|
|
811
|
+
...(priced === 0 || unpricedModels === 0 ? {} : { unpricedModels }),
|
|
812
|
+
}))
|
|
813
|
+
.sort((a, b) => b.tokensTotal - a.tokensTotal)
|
|
814
|
+
|
|
815
|
+
const byModel: CostModelRow[] = [...models.values()]
|
|
816
|
+
.map((acc) => ({
|
|
817
|
+
agent: acc.agent,
|
|
818
|
+
phase: acc.phase,
|
|
819
|
+
provider: acc.provider,
|
|
820
|
+
model: acc.model,
|
|
821
|
+
tokensInput: acc.tokensInput,
|
|
822
|
+
tokensOutput: acc.tokensOutput,
|
|
823
|
+
tokensCacheRead: acc.tokensCacheRead,
|
|
824
|
+
tokensCacheWrite: acc.tokensCacheWrite,
|
|
825
|
+
// "Total" means input+output everywhere in the report; cache tokens are
|
|
826
|
+
// reported in their own columns rather than folded into this one, so two
|
|
827
|
+
// tables cannot disagree about what a total counts.
|
|
828
|
+
tokensTotal: acc.tokensInput + acc.tokensOutput,
|
|
829
|
+
...(acc.usd === undefined ? {} : { costUsd: acc.usd }),
|
|
830
|
+
...(acc.reason === undefined ? {} : { unpricedReason: acc.reason }),
|
|
831
|
+
}))
|
|
832
|
+
.sort((a, b) => b.tokensTotal - a.tokensTotal)
|
|
833
|
+
|
|
834
|
+
const bySession: CostSessionRow[] = [...sessions.values()]
|
|
835
|
+
.map((acc) => {
|
|
836
|
+
const info = sessionIndex.nodes.get(acc.sessionId)
|
|
837
|
+
return {
|
|
838
|
+
sessionId: acc.sessionId,
|
|
839
|
+
...(info?.title === undefined ? {} : { title: info.title }),
|
|
840
|
+
agents: [...acc.agents].sort(),
|
|
841
|
+
tokensInput: acc.tokensInput,
|
|
842
|
+
tokensOutput: acc.tokensOutput,
|
|
843
|
+
tokensCacheRead: acc.tokensCacheRead,
|
|
844
|
+
tokensCacheWrite: acc.tokensCacheWrite,
|
|
845
|
+
tokensTotal: acc.tokensInput + acc.tokensOutput,
|
|
846
|
+
...(acc.priced === 0 ? {} : { costUsd: acc.usd }),
|
|
847
|
+
...(acc.priced === 0 || acc.unpricedModels === 0
|
|
848
|
+
? {}
|
|
849
|
+
: { unpricedModels: acc.unpricedModels }),
|
|
850
|
+
...(acc.reason === undefined ? {} : { unpricedReason: acc.reason }),
|
|
851
|
+
}
|
|
852
|
+
})
|
|
853
|
+
.sort((a, b) => b.tokensTotal - a.tokensTotal)
|
|
854
|
+
|
|
855
|
+
return {
|
|
856
|
+
rows,
|
|
857
|
+
coverage,
|
|
858
|
+
byModel,
|
|
859
|
+
bySession,
|
|
860
|
+
...(sessionScope === undefined ? {} : { sessionScope }),
|
|
861
|
+
}
|
|
388
862
|
} finally {
|
|
389
863
|
db.close()
|
|
390
864
|
}
|
|
@@ -443,7 +917,18 @@ function diagnoseUnreadableLedger(query: CostQuery, days: number): string | unde
|
|
|
443
917
|
'database whose token layout this build understands.'
|
|
444
918
|
)
|
|
445
919
|
}
|
|
446
|
-
|
|
920
|
+
// A scoped report can legitimately be empty: the session filter, not the
|
|
921
|
+
// ledger layout, removed every row. Diagnosing the user's database from a
|
|
922
|
+
// filtered view reports a fault that does not exist, so the "no tokens"
|
|
923
|
+
// branch is reserved for an UNSCOPED read.
|
|
924
|
+
if (query.sessionScope !== undefined) return undefined
|
|
925
|
+
if (
|
|
926
|
+
!query.rows.some((row) => row.tokensInput !== 0 || row.tokensOutput !== 0) &&
|
|
927
|
+
// Cache-only usage is still usage: a turn whose whole payload was served
|
|
928
|
+
// from cache has zero input/output but a real cache-read count, and
|
|
929
|
+
// calling that "unreadable" would hide spend that this report can price.
|
|
930
|
+
!(query.byModel ?? []).some((row) => row.tokensCacheRead !== 0 || row.tokensCacheWrite !== 0)
|
|
931
|
+
) {
|
|
447
932
|
return (
|
|
448
933
|
`no readable token source: ${assistantRows} assistant row(s) were found in ${tables} ` +
|
|
449
934
|
'but none carried both an attributable agent and a token payload, so no usage can be ' +
|
|
@@ -453,36 +938,368 @@ function diagnoseUnreadableLedger(query: CostQuery, days: number): string | unde
|
|
|
453
938
|
return undefined
|
|
454
939
|
}
|
|
455
940
|
|
|
456
|
-
/**
|
|
457
|
-
|
|
941
|
+
/** Smallest amount the four-decimal rendering can show without claiming zero. */
|
|
942
|
+
const MIN_DISPLAYABLE_USD = 0.0001
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* Human money. `—` is "could not be priced", never "free".
|
|
946
|
+
*
|
|
947
|
+
* A real zero renders as `$0.00`, but a non-zero amount below the display
|
|
948
|
+
* resolution renders as `< $0.0001`: rounding $0.00004 to `$0.0000` would show a
|
|
949
|
+
* free model where the catalog charged for one, and this is the column a spend
|
|
950
|
+
* decision is read from.
|
|
951
|
+
*/
|
|
952
|
+
function formatUsd(usd: number | undefined): string {
|
|
953
|
+
if (usd === undefined) return '—'
|
|
954
|
+
if (usd === 0) return '$0.00'
|
|
955
|
+
if (usd < MIN_DISPLAYABLE_USD) return '< $0.0001'
|
|
956
|
+
return usd < 1 ? `$${usd.toFixed(4)}` : `$${usd.toFixed(2)}`
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* A total row's cost cell.
|
|
961
|
+
*
|
|
962
|
+
* With no priced row at all the cell is `—`, not `$0.00`: a report that could
|
|
963
|
+
* not price anything has not measured zero spend, and this number is what a
|
|
964
|
+
* tier decision would be made on. `unpricedRows` counts every row that is not
|
|
965
|
+
* FULLY priced, including rows whose numeric part is shown but incomplete.
|
|
966
|
+
*/
|
|
967
|
+
function totalCostCell(pricedUsd: number, pricedRows: number, unpricedRows: number): string {
|
|
968
|
+
if (pricedRows === 0) return unpricedRows === 0 ? '**$0.00**' : '**—** (nothing priceable)'
|
|
969
|
+
const cell = `**${formatUsd(pricedUsd)}**`
|
|
970
|
+
return unpricedRows === 0 ? cell : `${cell} (partial)`
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/**
|
|
974
|
+
* A per-row cost cell.
|
|
975
|
+
*
|
|
976
|
+
* A row that mixed priced and unpriced models shows the money it could account
|
|
977
|
+
* for, marked `(partial)`: hiding it behind `—` under-reported the total, and
|
|
978
|
+
* showing it unmarked claimed the row was fully priced.
|
|
979
|
+
*/
|
|
980
|
+
function rowCostCell(usd: number | undefined, unpricedModels: number | undefined): string {
|
|
981
|
+
const cell = formatUsd(usd)
|
|
982
|
+
return unpricedModels === undefined || usd === undefined ? cell : `${cell} (partial)`
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/** Session rows shown before the tail is summarised. */
|
|
986
|
+
const MAX_SESSION_ROWS = 20
|
|
987
|
+
|
|
988
|
+
/** Cut a session title to something that fits a markdown cell. */
|
|
989
|
+
function shortTitle(title: string | undefined): string {
|
|
990
|
+
if (title === undefined) return '—'
|
|
991
|
+
const flat = title.replaceAll('|', '/').replaceAll('\n', ' ').trim()
|
|
992
|
+
return flat.length > 48 ? `${flat.slice(0, 47)}…` : flat === '' ? '—' : flat
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* Where the prices came from and how stale they are.
|
|
997
|
+
*
|
|
998
|
+
* This is a claim the report makes about its own numbers, so it is stated even
|
|
999
|
+
* when the answer is "no prices": a cost column full of `—` with no explanation
|
|
1000
|
+
* reads as zero spend.
|
|
1001
|
+
*/
|
|
1002
|
+
function pricingNote(pricing: PricingSnapshot | undefined): string[] {
|
|
1003
|
+
if (pricing === undefined) {
|
|
1004
|
+
return [
|
|
1005
|
+
'Pricing: unavailable for this run — every cost reads — and no model is treated as free.',
|
|
1006
|
+
]
|
|
1007
|
+
}
|
|
1008
|
+
if (pricing.refused === true) {
|
|
1009
|
+
const detail = pricing.unavailableReason ?? 'a price refresh was refused'
|
|
1010
|
+
const suffix =
|
|
1011
|
+
pricing.index.size === 0
|
|
1012
|
+
? 'every cost reads — and no model is treated as free.'
|
|
1013
|
+
: 'costs below use the cached catalog; nothing was fetched.'
|
|
1014
|
+
return [`Pricing: REFUSED — ${detail}; ${suffix}`]
|
|
1015
|
+
}
|
|
1016
|
+
if (pricing.index.size === 0) {
|
|
1017
|
+
const detail = pricing.unavailableReason ?? 'no cached catalog'
|
|
1018
|
+
return [
|
|
1019
|
+
`Pricing: unavailable (${detail}) — every cost reads — and unpriced models are EXCLUDED from totals, never priced at zero.`,
|
|
1020
|
+
// Never recommend a call the host has forbidden: an offline report that
|
|
1021
|
+
// says "run refreshPricing" is advice that cannot work.
|
|
1022
|
+
pricing.offline === true
|
|
1023
|
+
? 'Pricing: this host is offline (PANTHEON_COST_OFFLINE=1); no catalog can be fetched until that is cleared.'
|
|
1024
|
+
: '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.',
|
|
1025
|
+
]
|
|
1026
|
+
}
|
|
1027
|
+
const fetched = pricing.fetchedAt === undefined ? 'unknown date' : isoDay(pricing.fetchedAt)
|
|
1028
|
+
const head = `Pricing: models.dev catalog (USD per 1M tokens), cached ${fetched}`
|
|
1029
|
+
if (pricing.unavailableReason !== undefined) {
|
|
1030
|
+
return [
|
|
1031
|
+
`${head} — the requested refresh failed (${pricing.unavailableReason}); costs below use cached prices.`,
|
|
1032
|
+
]
|
|
1033
|
+
}
|
|
1034
|
+
if (pricing.refreshing) {
|
|
1035
|
+
return [`${head} — stale, refreshing in the background; costs below use these cached prices.`]
|
|
1036
|
+
}
|
|
1037
|
+
if (pricing.stale) {
|
|
1038
|
+
const why =
|
|
1039
|
+
pricing.offline === true
|
|
1040
|
+
? 'offline, so no background refresh was scheduled'
|
|
1041
|
+
: 'no background refresh was scheduled'
|
|
1042
|
+
return [`${head} — stale, and ${why}; costs below use cached prices.`]
|
|
1043
|
+
}
|
|
1044
|
+
return [`${head}.`]
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* One line that reconciles the two dollar totals.
|
|
1049
|
+
*
|
|
1050
|
+
* Every dollar is attributed per `(agent, model)` and then summed, so a fully
|
|
1051
|
+
* priced report produces the SAME by-agent and by-model totals by construction.
|
|
1052
|
+
* The only legitimate difference is a model with no catalog price: its tokens
|
|
1053
|
+
* remain measured in both token columns and its cost is absent from both dollar
|
|
1054
|
+
* totals. The exclusion clause is shared by both branches, so one line can
|
|
1055
|
+
* never both claim agreement and name a difference for the same tokens.
|
|
1056
|
+
*/
|
|
1057
|
+
function reconciliationNote(
|
|
1058
|
+
rows: readonly CostRow[],
|
|
1059
|
+
byModel: readonly CostModelRow[] | undefined,
|
|
1060
|
+
): string | undefined {
|
|
1061
|
+
if (byModel === undefined) return undefined
|
|
1062
|
+
const unpriced = byModel.filter((row) => row.costUsd === undefined)
|
|
1063
|
+
if (unpriced.length === 0) return undefined
|
|
1064
|
+
const agentUsd = rows.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
|
|
1065
|
+
const modelUsd = byModel.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
|
|
1066
|
+
const totalTokens = byModel.reduce((sum, row) => sum + row.tokensTotal, 0)
|
|
1067
|
+
const unpricedTokens = unpriced.reduce((sum, row) => sum + row.tokensTotal, 0)
|
|
1068
|
+
const pricedRows = byModel.length - unpriced.length
|
|
1069
|
+
const totals =
|
|
1070
|
+
pricedRows === 0
|
|
1071
|
+
? 'nothing in either table could be priced'
|
|
1072
|
+
: Math.abs(agentUsd - modelUsd) < 0.005
|
|
1073
|
+
? `by-agent and by-model priced totals agree at ${formatUsd(agentUsd)}`
|
|
1074
|
+
: `by-agent ${formatUsd(agentUsd)} and by-model ${formatUsd(modelUsd)} differ by ${formatUsd(Math.abs(agentUsd - modelUsd))}`
|
|
1075
|
+
// The exclusion is stated once, in the same words in every branch: the count
|
|
1076
|
+
// can never be read as applying to one total but not the other.
|
|
1077
|
+
return `Cost reconciliation: ${totals}; ${unpricedTokens} token(s) from ${unpriced.length} unpriced model row(s) are counted in the token columns and excluded from both dollar totals (${totalTokens - unpricedTokens} priced token(s) carry the money).`
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
function modelTotals(byModel: readonly CostModelRow[]): Array<{
|
|
1081
|
+
provider: string
|
|
1082
|
+
model: string
|
|
1083
|
+
tokensInput: number
|
|
1084
|
+
tokensOutput: number
|
|
1085
|
+
tokensCacheRead: number
|
|
1086
|
+
tokensCacheWrite: number
|
|
1087
|
+
tokensTotal: number
|
|
1088
|
+
costUsd: number | undefined
|
|
1089
|
+
unpricedModels?: number
|
|
1090
|
+
}> {
|
|
1091
|
+
const groups = new Map<
|
|
1092
|
+
string,
|
|
1093
|
+
{
|
|
1094
|
+
provider: string
|
|
1095
|
+
model: string
|
|
1096
|
+
tokensInput: number
|
|
1097
|
+
tokensOutput: number
|
|
1098
|
+
tokensCacheRead: number
|
|
1099
|
+
tokensCacheWrite: number
|
|
1100
|
+
tokensTotal: number
|
|
1101
|
+
usd: number
|
|
1102
|
+
priced: number
|
|
1103
|
+
unpricedModels: number
|
|
1104
|
+
}
|
|
1105
|
+
>()
|
|
1106
|
+
for (const row of byModel) {
|
|
1107
|
+
const key = `${row.provider}\u0000${row.model}`
|
|
1108
|
+
const acc = groups.get(key) ?? {
|
|
1109
|
+
provider: row.provider,
|
|
1110
|
+
model: row.model,
|
|
1111
|
+
tokensInput: 0,
|
|
1112
|
+
tokensOutput: 0,
|
|
1113
|
+
tokensCacheRead: 0,
|
|
1114
|
+
tokensCacheWrite: 0,
|
|
1115
|
+
tokensTotal: 0,
|
|
1116
|
+
usd: 0,
|
|
1117
|
+
priced: 0,
|
|
1118
|
+
unpricedModels: 0,
|
|
1119
|
+
}
|
|
1120
|
+
acc.tokensInput += row.tokensInput
|
|
1121
|
+
acc.tokensOutput += row.tokensOutput
|
|
1122
|
+
acc.tokensCacheRead += row.tokensCacheRead
|
|
1123
|
+
acc.tokensCacheWrite += row.tokensCacheWrite
|
|
1124
|
+
acc.tokensTotal += row.tokensTotal
|
|
1125
|
+
if (row.costUsd === undefined) {
|
|
1126
|
+
acc.unpricedModels += 1
|
|
1127
|
+
} else {
|
|
1128
|
+
acc.usd += row.costUsd
|
|
1129
|
+
acc.priced += 1
|
|
1130
|
+
}
|
|
1131
|
+
groups.set(key, acc)
|
|
1132
|
+
}
|
|
1133
|
+
return [...groups.values()]
|
|
1134
|
+
.map((acc) => ({
|
|
1135
|
+
provider: acc.provider,
|
|
1136
|
+
model: acc.model,
|
|
1137
|
+
tokensInput: acc.tokensInput,
|
|
1138
|
+
tokensOutput: acc.tokensOutput,
|
|
1139
|
+
tokensCacheRead: acc.tokensCacheRead,
|
|
1140
|
+
tokensCacheWrite: acc.tokensCacheWrite,
|
|
1141
|
+
tokensTotal: acc.tokensTotal,
|
|
1142
|
+
// Same rule as the by-agent table: a model bucket that spans several
|
|
1143
|
+
// agent/phase groups is the SUM of its priced groups, and `unpricedModels`
|
|
1144
|
+
// records how many groups had no usable price.
|
|
1145
|
+
costUsd: acc.priced === 0 ? undefined : acc.usd,
|
|
1146
|
+
...(acc.priced === 0 || acc.unpricedModels === 0
|
|
1147
|
+
? {}
|
|
1148
|
+
: { unpricedModels: acc.unpricedModels }),
|
|
1149
|
+
}))
|
|
1150
|
+
.sort((a, b) => b.tokensTotal - a.tokensTotal)
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
/** The `## Cost by model` section. */
|
|
1154
|
+
function renderModelSection(byModel: readonly CostModelRow[] | undefined, days: number): string[] {
|
|
1155
|
+
const header = `## Cost by model (last ${days} days)`
|
|
1156
|
+
if (byModel === undefined) {
|
|
1157
|
+
return [header, '', 'Unavailable: this run reports tokens only (CLI fallback path).']
|
|
1158
|
+
}
|
|
1159
|
+
if (byModel.length === 0) return [header, '', 'No model rows in this window.']
|
|
1160
|
+
const totals = modelTotals(byModel)
|
|
1161
|
+
const pricedUsd = totals.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
|
|
1162
|
+
const priced = totals.filter((row) => row.costUsd !== undefined).length
|
|
1163
|
+
const unpriced = totals.filter(
|
|
1164
|
+
(row) => row.costUsd === undefined || (row.unpricedModels ?? 0) > 0,
|
|
1165
|
+
).length
|
|
1166
|
+
const totalCell = totalCostCell(pricedUsd, priced, unpriced)
|
|
1167
|
+
return [
|
|
1168
|
+
header,
|
|
1169
|
+
'',
|
|
1170
|
+
'| Provider | Model | Tokens In | Tokens Out | Cache Read | Cache Write | Cost (USD) |',
|
|
1171
|
+
'|----------|-------|----------:|-----------:|-----------:|------------:|-----------:|',
|
|
1172
|
+
...totals.map(
|
|
1173
|
+
(row) =>
|
|
1174
|
+
`| ${row.provider} | ${row.model} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${rowCostCell(row.costUsd, row.unpricedModels)} |`,
|
|
1175
|
+
),
|
|
1176
|
+
`| **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} |`,
|
|
1177
|
+
]
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/** The `## Cost by session` section, scoped or global. */
|
|
1181
|
+
function renderSessionSection(query: CostQuery, days: number): string[] {
|
|
1182
|
+
const scope = query.sessionScope
|
|
1183
|
+
const header =
|
|
1184
|
+
scope === undefined
|
|
1185
|
+
? `## Cost by session (last ${days} days)`
|
|
1186
|
+
: `## Cost by session tree (last ${days} days) — root ${scope.rootId}`
|
|
1187
|
+
if (query.bySession === undefined) {
|
|
1188
|
+
return [header, '', 'Unavailable: this run reports tokens only (CLI fallback path).']
|
|
1189
|
+
}
|
|
1190
|
+
const lines = [header, '']
|
|
1191
|
+
if (scope !== undefined) {
|
|
1192
|
+
if (!scope.hierarchy) {
|
|
1193
|
+
lines.push(
|
|
1194
|
+
'Session hierarchy unavailable: this database has no session metadata table, so only rows whose session_id equals the root are counted.',
|
|
1195
|
+
'',
|
|
1196
|
+
)
|
|
1197
|
+
} else if (!scope.rootKnown) {
|
|
1198
|
+
lines.push(
|
|
1199
|
+
'Root session not found in this database: only rows whose session_id equals it are counted, and no descendants can be resolved.',
|
|
1200
|
+
'',
|
|
1201
|
+
)
|
|
1202
|
+
} else {
|
|
1203
|
+
lines.push(`Scope: the root session plus ${scope.ids.length - 1} descendant session(s).`, '')
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
if (query.bySession.length === 0) {
|
|
1207
|
+
lines.push('No session rows in this window.')
|
|
1208
|
+
return lines
|
|
1209
|
+
}
|
|
1210
|
+
const shown = query.bySession.slice(0, MAX_SESSION_ROWS)
|
|
1211
|
+
const hidden = query.bySession.length - shown.length
|
|
1212
|
+
const pricedUsd = query.bySession.reduce((sum, row) => sum + (row.costUsd ?? 0), 0)
|
|
1213
|
+
const priced = query.bySession.filter((row) => row.costUsd !== undefined).length
|
|
1214
|
+
const unpriced = query.bySession.filter(
|
|
1215
|
+
(row) => row.costUsd === undefined || (row.unpricedModels ?? 0) > 0,
|
|
1216
|
+
).length
|
|
1217
|
+
const totalCell = totalCostCell(pricedUsd, priced, unpriced)
|
|
1218
|
+
lines.push(
|
|
1219
|
+
'| Session | Title | Agent | Tokens In | Tokens Out | Cache Read | Cache Write | Tokens Total | Cost (USD) |',
|
|
1220
|
+
'|---------|-------|-------|----------:|-----------:|-----------:|------------:|-------------:|-----------:|',
|
|
1221
|
+
...shown.map(
|
|
1222
|
+
(row) =>
|
|
1223
|
+
`| ${row.sessionId} | ${shortTitle(row.title)} | ${row.agents.join(', ') || '—'} | ${row.tokensInput} | ${row.tokensOutput} | ${row.tokensCacheRead} | ${row.tokensCacheWrite} | ${row.tokensTotal} | ${rowCostCell(row.costUsd, row.unpricedModels)} |`,
|
|
1224
|
+
),
|
|
1225
|
+
`| **${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} |`,
|
|
1226
|
+
)
|
|
1227
|
+
if (hidden > 0) {
|
|
1228
|
+
lines.push('', `_+${hidden} more session(s) not listed; the totals include them._`)
|
|
1229
|
+
}
|
|
1230
|
+
return lines
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/** Render the aggregate as markdown tables with total rows. */
|
|
1234
|
+
function renderMarkdown(
|
|
1235
|
+
query: CostQuery,
|
|
1236
|
+
days: number,
|
|
1237
|
+
pricing: PricingSnapshot | undefined,
|
|
1238
|
+
): string {
|
|
458
1239
|
const { rows, coverage } = query
|
|
459
|
-
const header = `## Token usage by agent and phase (last ${days} days)`
|
|
1240
|
+
const header = `## Token and cost usage by agent and phase (last ${days} days)`
|
|
1241
|
+
const reconciliation = reconciliationNote(rows, query.byModel)
|
|
460
1242
|
const footer = [
|
|
461
1243
|
formatCoverage(coverage, days),
|
|
1244
|
+
'Window: rolling 24-hour days from query time (not calendar days or session boundaries).',
|
|
1245
|
+
'Aggregation: per agent and phase (phase may be unknown on V2), per model, and per session.',
|
|
1246
|
+
'Attribution: a session row covers that session alone; passing session:<id> sums the root session and its descendant sessions.',
|
|
1247
|
+
'Limits: costs are catalog list prices (USD per 1M tokens), not a provider invoice; a row that mixes priced and unpriced models shows its priced part and is reported as partial, and an unknown model is never priced at zero.',
|
|
1248
|
+
...(reconciliation === undefined ? [] : [reconciliation]),
|
|
1249
|
+
...pricingNote(pricing),
|
|
462
1250
|
`Source: opencode.db (read-only) — table families: ${coverage.sources.join(' + ')} — ${coverage.assistantRows} assistant row(s) scanned`,
|
|
463
1251
|
].join('\n')
|
|
464
1252
|
if (rows.length === 0) {
|
|
465
|
-
|
|
1253
|
+
// The scope sentence lives in the session section, so an empty report must
|
|
1254
|
+
// still render that section — otherwise a valid empty subtree looks
|
|
1255
|
+
// indistinguishable from a database that holds nothing.
|
|
1256
|
+
const scope = query.sessionScope
|
|
1257
|
+
const empty =
|
|
1258
|
+
scope === undefined
|
|
1259
|
+
? `No token records in the last ${days} days.`
|
|
1260
|
+
: `No token records in the last ${days} days for ${scope.rootId} or its descendant sessions.`
|
|
1261
|
+
return [
|
|
1262
|
+
header,
|
|
1263
|
+
'',
|
|
1264
|
+
empty,
|
|
1265
|
+
'',
|
|
1266
|
+
...renderModelSection(query.byModel, days),
|
|
1267
|
+
'',
|
|
1268
|
+
...renderSessionSection(query, days),
|
|
1269
|
+
'',
|
|
1270
|
+
footer,
|
|
1271
|
+
].join('\n')
|
|
466
1272
|
}
|
|
467
1273
|
const total = rows.reduce(
|
|
468
1274
|
(acc, r) => {
|
|
469
1275
|
acc.tokensInput += r.tokensInput
|
|
470
1276
|
acc.tokensOutput += r.tokensOutput
|
|
471
1277
|
acc.tokensTotal += r.tokensTotal
|
|
1278
|
+
if (r.costUsd === undefined) acc.unpriced += 1
|
|
1279
|
+
else {
|
|
1280
|
+
acc.usd += r.costUsd
|
|
1281
|
+
acc.priced += 1
|
|
1282
|
+
if ((r.unpricedModels ?? 0) > 0) acc.partial += 1
|
|
1283
|
+
}
|
|
472
1284
|
return acc
|
|
473
1285
|
},
|
|
474
|
-
{ tokensInput: 0, tokensOutput: 0, tokensTotal: 0 },
|
|
1286
|
+
{ tokensInput: 0, tokensOutput: 0, tokensTotal: 0, usd: 0, unpriced: 0, priced: 0, partial: 0 },
|
|
475
1287
|
)
|
|
1288
|
+
const totalCost = totalCostCell(total.usd, total.priced, total.unpriced + total.partial)
|
|
476
1289
|
const lines = [
|
|
477
1290
|
header,
|
|
478
1291
|
'',
|
|
479
|
-
'| Agent | Phase | Tokens In | Tokens Out | Tokens Total |',
|
|
480
|
-
'
|
|
1292
|
+
'| Agent | Phase | Tokens In | Tokens Out | Tokens Total | Cost (USD) |',
|
|
1293
|
+
'|-------|-------|----------:|-----------:|-------------:|-----------:|',
|
|
481
1294
|
...rows.map(
|
|
482
1295
|
(r) =>
|
|
483
|
-
`| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} |`,
|
|
1296
|
+
`| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} | ${rowCostCell(r.costUsd, r.unpricedModels)} |`,
|
|
484
1297
|
),
|
|
485
|
-
`| **Total** | — | **${total.tokensInput}** | **${total.tokensOutput}** | **${total.tokensTotal}** |`,
|
|
1298
|
+
`| **Total** | — | **${total.tokensInput}** | **${total.tokensOutput}** | **${total.tokensTotal}** | ${totalCost} |`,
|
|
1299
|
+
'',
|
|
1300
|
+
...renderModelSection(query.byModel, days),
|
|
1301
|
+
'',
|
|
1302
|
+
...renderSessionSection(query, days),
|
|
486
1303
|
'',
|
|
487
1304
|
footer,
|
|
488
1305
|
]
|
|
@@ -782,13 +1599,13 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
782
1599
|
}
|
|
783
1600
|
|
|
784
1601
|
/** Run a query and turn its coverage into either a report or a diagnosis. */
|
|
785
|
-
const render = (query: CostQuery, days: number): string => {
|
|
1602
|
+
const render = (query: CostQuery, days: number, pricing?: PricingSnapshot): string => {
|
|
786
1603
|
const unreadable = diagnoseUnreadableLedger(query, days)
|
|
787
1604
|
if (unreadable !== undefined) return failure('UNSUPPORTED', unreadable)
|
|
788
|
-
return `status: OK\n${renderMarkdown(query, days)}`
|
|
1605
|
+
return `status: OK\n${renderMarkdown(query, days, pricing)}`
|
|
789
1606
|
}
|
|
790
1607
|
|
|
791
|
-
const execute = async (args:
|
|
1608
|
+
const execute = async (args: CostArgs, _ctx: ToolContextLike): Promise<string> => {
|
|
792
1609
|
const days = args?.days ?? 7
|
|
793
1610
|
try {
|
|
794
1611
|
const dbPath = findExistingDb(options?.dbPath)
|
|
@@ -799,6 +1616,16 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
799
1616
|
`opencode.db not found (expected at ${expected}). No token history is available until opencode has stored session data.`,
|
|
800
1617
|
)
|
|
801
1618
|
}
|
|
1619
|
+
// Pricing never blocks a default call: `refreshPricing` is the only path
|
|
1620
|
+
// that awaits the catalog, and it is bounded by a short timeout.
|
|
1621
|
+
const pricing =
|
|
1622
|
+
args?.refreshPricing === true
|
|
1623
|
+
? await forceRefreshPricing(options?.pricing)
|
|
1624
|
+
: loadPricing(options?.pricing).snapshot
|
|
1625
|
+
const queryOptions: CostQueryOptions = {
|
|
1626
|
+
pricing,
|
|
1627
|
+
...(args?.session === undefined ? {} : { sessionRoot: args.session }),
|
|
1628
|
+
}
|
|
802
1629
|
let sqlite: SqliteModule | undefined
|
|
803
1630
|
try {
|
|
804
1631
|
sqlite = await loadSqlite()
|
|
@@ -806,15 +1633,29 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
806
1633
|
// node:sqlite unavailable (e.g. Bun runtime) — fall back to CLI.
|
|
807
1634
|
const status = statusForError(loadErr)
|
|
808
1635
|
if (status === 'UNSUPPORTED') {
|
|
1636
|
+
// The mirror reports tokens only and carries no session ids, so it
|
|
1637
|
+
// cannot answer a scoped question. Rendering an unscoped total under a
|
|
1638
|
+
// scoped question is exactly the plausible-but-wrong number this
|
|
1639
|
+
// report exists to prevent, so the request is refused instead.
|
|
1640
|
+
if (args?.session !== undefined) {
|
|
1641
|
+
return failure(
|
|
1642
|
+
'UNSUPPORTED',
|
|
1643
|
+
`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".`,
|
|
1644
|
+
)
|
|
1645
|
+
}
|
|
809
1646
|
try {
|
|
810
|
-
return render(
|
|
1647
|
+
return render(
|
|
1648
|
+
await queryWithCliFallback(dbPath, days, options?.cliFallback),
|
|
1649
|
+
days,
|
|
1650
|
+
pricing,
|
|
1651
|
+
)
|
|
811
1652
|
} catch (cliErr: unknown) {
|
|
812
1653
|
return failure(statusForError(cliErr), diagnostic(cliErr))
|
|
813
1654
|
}
|
|
814
1655
|
}
|
|
815
1656
|
throw loadErr
|
|
816
1657
|
}
|
|
817
|
-
return render(queryWithSqlite(dbPath, days, sqlite), days)
|
|
1658
|
+
return render(queryWithSqlite(dbPath, days, sqlite, queryOptions), days, pricing)
|
|
818
1659
|
} catch (err: unknown) {
|
|
819
1660
|
return failure(statusForError(err), diagnostic(err))
|
|
820
1661
|
}
|
|
@@ -823,7 +1664,7 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
823
1664
|
return {
|
|
824
1665
|
pantheon_cost: {
|
|
825
1666
|
description:
|
|
826
|
-
'Report input, output, and total token usage by agent and phase
|
|
1667
|
+
'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
1668
|
args: costArgs,
|
|
828
1669
|
execute,
|
|
829
1670
|
},
|