pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.10
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/CHANGELOG.md +163 -0
- package/README.md +236 -60
- package/README.pt-BR.md +19 -1
- package/bin/pantheon-init.mjs +195 -13
- package/package.json +11 -3
- package/plugin.json +1 -1
- package/prompts/README.md +58 -0
- package/prompts/debug-issue.prompt.md +46 -0
- package/prompts/dynamic/agora-generated.txt +38 -0
- package/prompts/dynamic/orchestrate-generated.txt +51 -0
- package/prompts/focus.prompt.md +42 -0
- package/prompts/implement-feature.prompt.md +39 -0
- package/prompts/optimize-database.prompt.md +58 -0
- package/prompts/orchestrate-with-zeus.prompt.md +441 -0
- package/prompts/plan-architecture.prompt.md +59 -0
- package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
- package/prompts/quick-plan-large-feature.prompt.md +197 -0
- package/prompts/semantic-summarize.md +50 -0
- package/prompts/sketch.prompt.md +91 -0
- package/prompts/subtask.prompt.md +131 -0
- package/pyproject.toml +1 -1
- package/scripts/decision-router-budget.mjs +780 -0
- package/scripts/decision-router-v2-budget.mjs +218 -0
- package/scripts/decision-router-v2-egress.mjs +272 -0
- package/scripts/decision-router.mjs +758 -0
- package/scripts/docs-check-changelog.mjs +5 -3
- package/scripts/install/component-selection.mjs +9 -4
- package/scripts/install/decision-layer-preview.mjs +376 -0
- package/scripts/install/decision-router-config.mjs +560 -0
- package/scripts/install/health-check.mjs +20 -11
- package/scripts/install/interactive.mjs +103 -14
- package/scripts/install/interrupt.mjs +4 -3
- package/scripts/install/migrate.mjs +123 -72
- package/scripts/install/opencode.mjs +178 -122
- package/scripts/install/plan.mjs +8 -1
- package/scripts/install/plugin.mjs +4 -3
- package/scripts/install/state.mjs +12 -0
- package/scripts/install/strings.mjs +22 -0
- package/scripts/install/venv.mjs +34 -17
- package/scripts/mcp_resources.py +11 -9
- package/scripts/release-notes.mjs +30 -7
- package/scripts/restore.mjs +22 -10
- package/scripts/sync-tui.mjs +3 -3
- package/scripts/test-opencode-v2-sandbox.sh +10 -6
- package/scripts/versioning.mjs +41 -5
- package/src/agents/aphrodite.md +6 -1
- package/src/agents/apollo.md +1 -0
- package/src/agents/athena.md +1 -0
- package/src/agents/demeter.md +1 -1
- package/src/agents/gaia.md +1 -0
- package/src/agents/hephaestus.md +1 -1
- package/src/agents/hermes.md +8 -10
- package/src/agents/iris.md +1 -1
- package/src/agents/mnemosyne.md +1 -0
- package/src/agents/nyx.md +1 -1
- package/src/agents/prometheus.md +1 -1
- package/src/agents/talos.md +6 -1
- package/src/agents/themis.md +1 -1
- package/src/agents/zeus.md +52 -62
- package/src/mcp/eval_store.py +11 -4
- package/src/mcp/mcp_resources.py +11 -9
- package/src/mcp/memory_mcp.py +293 -150
- package/src/pantheon/cost-command.ts +30 -133
- package/src/pantheon/jev-decision-tool.ts +347 -0
- package/src/pantheon/jev-decisions.ts +625 -0
- package/src/pantheon/local-decision-agents.ts +170 -0
- package/src/pantheon/local-decision-budget.ts +1046 -0
- package/src/pantheon/local-decision-egress-gate.ts +144 -0
- package/src/pantheon/local-decision-prompt.ts +256 -0
- package/src/pantheon/local-decision-provider-matrix.ts +44 -0
- package/src/pantheon/local-decision-router.ts +225 -0
- package/src/pantheon/local-decision-skills.ts +281 -0
- package/src/pantheon/local-decision-tool.ts +160 -0
- package/src/pantheon/local-decision-turn.ts +101 -0
- package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
- package/src/pantheon/local-orchestration.ts +322 -0
- package/src/pantheon/model-pricing.ts +1 -536
- package/src/pantheon/pantheon-decision-catalog.ts +101 -0
- package/src/pantheon/v2-decision-budget.ts +456 -0
- package/src/pantheon/v2-decision-contracts.ts +300 -0
- package/src/pantheon/v2-decision-egress.ts +203 -0
- package/src/pantheon/v2-decision-events.ts +180 -0
- package/src/pantheon/v2-decision-heuristic.ts +121 -0
- package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
- package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
- package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
- package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
- package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
- package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
- package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
- package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
- package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
- package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
- package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
- package/src/pantheon/v2-decision-points.ts +242 -0
- package/src/pantheon/v2-decision-policy.ts +166 -0
- package/src/pantheon/v2-decision-premises.ts +146 -0
- package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
- package/src/pantheon/v2-decision-rank.ts +91 -0
- package/src/pantheon/v2-decision-registry.ts +391 -0
- package/src/pantheon/v2-decision-resource-ids.ts +127 -0
- package/src/pantheon/v2-decision-shadow.ts +123 -0
- package/src/pantheon/v2-decision-telemetry.ts +214 -0
- package/src/pantheon/v2-decision-verify.ts +51 -0
- package/src/pantheon/v2-hook-engine.ts +307 -0
- package/src/pantheon/v2-native-decisions.ts +365 -0
- package/src/pantheon/v2-shell-hooks.ts +66 -2
- package/src/pantheon/v2-tools.ts +38 -15
- package/src/plugin-v2.ts +419 -26
- package/src/plugin.ts +4 -0
- package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
- package/src/plugins/tui/dist/server-v2.d.ts +19 -11
- package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/server-v2.js +19 -666
- package/src/plugins/tui/dist/server-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +187 -1917
- package/src/plugins/tui/dist/tui-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +17 -2
- package/src/plugins/tui/package.json +4 -2
- package/src/plugins/tui/src/cost-data.ts +607 -0
- package/src/plugins/tui/src/index-v2.tsx +213 -54
- package/src/plugins/tui/src/model-pricing.ts +536 -0
- package/src/plugins/tui/src/server-v2.ts +18 -838
- package/src/plugins/tui/tsdown.config.ts +28 -6
- package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
- package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
- package/src/plugins/tui/dist/quota-adapters.js +0 -1142
- package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
- package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
- package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
- package/src/plugins/tui/dist/quota-cli.js +0 -184
- package/src/plugins/tui/dist/quota-cli.js.map +0 -1
- package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
- package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
- package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
- package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
- package/src/plugins/tui/src/quota-adapters.ts +0 -1598
- package/src/plugins/tui/src/quota-cli.ts +0 -237
- package/src/plugins/tui/src/quota-rpc.ts +0 -209
- package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
- package/src/plugins/tui/src/quota-v2.tsx +0 -986
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only cost and usage data shared by the CLI and the TUI package.
|
|
3
|
+
*
|
|
4
|
+
* This module lives inside the TUI package so its worker and bundled server do
|
|
5
|
+
* not import source files outside the package boundary. The CLI imports these
|
|
6
|
+
* same helpers, preserving a single implementation.
|
|
7
|
+
*/
|
|
8
|
+
import { homedir } from 'node:os'
|
|
9
|
+
import { join } from 'node:path'
|
|
10
|
+
import {
|
|
11
|
+
computeModelCost,
|
|
12
|
+
loadPricing,
|
|
13
|
+
lookupModelPrice,
|
|
14
|
+
type PricingOptions,
|
|
15
|
+
type PricingSnapshot,
|
|
16
|
+
type UnpricedReason,
|
|
17
|
+
} from './model-pricing.ts'
|
|
18
|
+
|
|
19
|
+
export interface SqliteDatabase {
|
|
20
|
+
prepare(sql: string): {
|
|
21
|
+
get(...args: unknown[]): unknown
|
|
22
|
+
all(...args: unknown[]): unknown[]
|
|
23
|
+
}
|
|
24
|
+
close(): void
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SqliteModule {
|
|
28
|
+
DatabaseSync: new (path: string, options: { readOnly: boolean }) => SqliteDatabase
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type OpenCodeVersion = 'v1' | 'v2'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Host table families that can carry a token ledger. A migrated database
|
|
35
|
+
* carries both at once.
|
|
36
|
+
*/
|
|
37
|
+
export type CostSource = 'message' | 'session_message'
|
|
38
|
+
|
|
39
|
+
const COST_SOURCES: readonly CostSource[] = ['message', 'session_message']
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Which table family each host generation stores its ledger in.
|
|
43
|
+
*
|
|
44
|
+
* Spelled out rather than comparing the literals: `'message' === 'v1'` is
|
|
45
|
+
* false, so a filter written as `source === requested` narrows to nothing and
|
|
46
|
+
* every version-pinned read fails.
|
|
47
|
+
*/
|
|
48
|
+
const VERSION_SOURCES: Record<OpenCodeVersion, CostSource> = {
|
|
49
|
+
v1: 'message',
|
|
50
|
+
v2: 'session_message',
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The XDG state directory every real host installation writes its ledger to. */
|
|
54
|
+
function defaultDbPath(): string {
|
|
55
|
+
const xdg = process.env.XDG_DATA_HOME
|
|
56
|
+
const dataHome = xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.local', 'share')
|
|
57
|
+
return join(dataHome, 'opencode', 'opencode.db')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Read and validate the optional host-generation selector. */
|
|
61
|
+
export function requestedVersion(): OpenCodeVersion | undefined {
|
|
62
|
+
const configured = process.env.PANTHEON_OPENCODE_VERSION
|
|
63
|
+
if (configured === undefined) return undefined
|
|
64
|
+
if (configured !== 'v1' && configured !== 'v2') {
|
|
65
|
+
throw new Error(`invalid PANTHEON_OPENCODE_VERSION "${configured}"; expected "v1" or "v2"`)
|
|
66
|
+
}
|
|
67
|
+
return configured
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Resolve the database.
|
|
72
|
+
*
|
|
73
|
+
* Precedence: explicit option → PANTHEON_COST_DB → OPENCODE_DB → the XDG
|
|
74
|
+
* default `opencode.db`. An invalid PANTHEON_OPENCODE_VERSION fails fast rather
|
|
75
|
+
* than being silently ignored.
|
|
76
|
+
*
|
|
77
|
+
* There is deliberately NO per-version filename. Deriving one from the host
|
|
78
|
+
* generation pointed the V2 report at `opencode-v2.db`, which exists only
|
|
79
|
+
* because a sandbox sets OPENCODE_DB — hence OPENCODE_DB's place in this chain.
|
|
80
|
+
*/
|
|
81
|
+
export function resolveCostDbPath(options?: { dbPath?: string }): string {
|
|
82
|
+
const explicit = options?.dbPath || process.env.PANTHEON_COST_DB || process.env.OPENCODE_DB
|
|
83
|
+
if (explicit) return explicit
|
|
84
|
+
requestedVersion()
|
|
85
|
+
return defaultDbPath()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Detect the ledger families by TABLE PRESENCE.
|
|
90
|
+
*
|
|
91
|
+
* Presence is the only reliable discriminator: a migrated database carries both
|
|
92
|
+
* families, so pinning a schema-version constant would break whichever
|
|
93
|
+
* population it excluded, and no manifest declares a supported host range.
|
|
94
|
+
* PANTHEON_OPENCODE_VERSION only NARROWS an already-detected set — it never
|
|
95
|
+
* chooses a file and never invents a family that is not there.
|
|
96
|
+
*/
|
|
97
|
+
export function resolveSources(
|
|
98
|
+
db: SqliteDatabase,
|
|
99
|
+
requested: OpenCodeVersion | undefined,
|
|
100
|
+
): CostSource[] {
|
|
101
|
+
const present = new Set(
|
|
102
|
+
(
|
|
103
|
+
db
|
|
104
|
+
.prepare(
|
|
105
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('message', 'session_message')",
|
|
106
|
+
)
|
|
107
|
+
.all() as Array<{ name?: unknown }>
|
|
108
|
+
).map((row) => String(row.name)),
|
|
109
|
+
)
|
|
110
|
+
const detected = COST_SOURCES.filter((source) => present.has(source))
|
|
111
|
+
if (detected.length === 0) {
|
|
112
|
+
throw new Error(
|
|
113
|
+
'incompatible opencode.db schema: neither the "message" nor the "session_message" table exists, so there is no token ledger to read',
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
if (requested === undefined) return detected
|
|
117
|
+
const wanted = VERSION_SOURCES[requested]
|
|
118
|
+
const narrowed = detected.filter((source) => source === wanted)
|
|
119
|
+
if (narrowed.length === 0) {
|
|
120
|
+
throw new Error(
|
|
121
|
+
`incompatible opencode.db schema: PANTHEON_OPENCODE_VERSION=${requested} selected no table family, but this database contains ${detected.join(' and ')}`,
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
return narrowed
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* UTC day + provider/model aggregation used by the TUI charts.
|
|
129
|
+
*
|
|
130
|
+
* The only interpolated fragments are fixed module constants (family table,
|
|
131
|
+
* discriminator, and time predicates). JSON is validated in the CTE before
|
|
132
|
+
* extraction, and all time bounds remain bound SQL parameters.
|
|
133
|
+
*/
|
|
134
|
+
function assistantLedgerPredicate(source: CostSource): string {
|
|
135
|
+
return source === 'message'
|
|
136
|
+
? "CASE WHEN json_valid(data) THEN json_extract(data, '$.role') = 'assistant' ELSE 0 END"
|
|
137
|
+
: "type = 'assistant'"
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function usageHistorySql(source: CostSource, rolling: boolean): string {
|
|
141
|
+
const table = source
|
|
142
|
+
const assistantPredicate = assistantLedgerPredicate(source)
|
|
143
|
+
const timeRange = rolling
|
|
144
|
+
? 'AND time_created >= ? AND time_created <= ?'
|
|
145
|
+
: 'AND time_created <= ?'
|
|
146
|
+
return `
|
|
147
|
+
WITH valid AS (
|
|
148
|
+
SELECT strftime('%Y-%m-%d', time_created / 1000, 'unixepoch') AS day,
|
|
149
|
+
COALESCE(NULLIF(TRIM(json_extract(data, '$.model.providerID')), ''),
|
|
150
|
+
NULLIF(TRIM(json_extract(data, '$.providerID')), '')) AS provider,
|
|
151
|
+
COALESCE(NULLIF(TRIM(json_extract(data, '$.model.id')), ''),
|
|
152
|
+
NULLIF(TRIM(json_extract(data, '$.modelID')), '')) AS model,
|
|
153
|
+
CASE WHEN json_type(data, '$.agent') IS NULL
|
|
154
|
+
OR json_extract(data, '$.agent') IS NULL
|
|
155
|
+
OR TRIM(json_extract(data, '$.agent')) = ''
|
|
156
|
+
THEN 1 ELSE 0 END AS agentless,
|
|
157
|
+
CASE WHEN json_type(data, '$.tokens.input') IN ('integer', 'real')
|
|
158
|
+
AND json_extract(data, '$.tokens.input') >= 0
|
|
159
|
+
THEN CAST(json_extract(data, '$.tokens.input') AS INTEGER) ELSE 0 END AS inTok,
|
|
160
|
+
CASE WHEN json_type(data, '$.tokens.output') IN ('integer', 'real')
|
|
161
|
+
AND json_extract(data, '$.tokens.output') >= 0
|
|
162
|
+
THEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) ELSE 0 END AS outTok,
|
|
163
|
+
CASE WHEN json_type(data, '$.tokens.cache.read') IN ('integer', 'real')
|
|
164
|
+
AND json_extract(data, '$.tokens.cache.read') >= 0
|
|
165
|
+
THEN CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER) ELSE 0 END AS cacheReadTok,
|
|
166
|
+
CASE WHEN json_type(data, '$.tokens.cache.write') IN ('integer', 'real')
|
|
167
|
+
AND json_extract(data, '$.tokens.cache.write') >= 0
|
|
168
|
+
THEN CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER) ELSE 0 END AS cacheWriteTok
|
|
169
|
+
FROM ${table}
|
|
170
|
+
WHERE json_valid(data) AND ${assistantPredicate} ${timeRange}
|
|
171
|
+
)
|
|
172
|
+
SELECT day,
|
|
173
|
+
provider,
|
|
174
|
+
model,
|
|
175
|
+
COUNT(*) AS rows,
|
|
176
|
+
SUM(agentless) AS agentlessRows,
|
|
177
|
+
COALESCE(SUM(inTok), 0) AS tokensInput,
|
|
178
|
+
COALESCE(SUM(outTok), 0) AS tokensOutput,
|
|
179
|
+
COALESCE(SUM(cacheReadTok), 0) AS tokensCacheRead,
|
|
180
|
+
COALESCE(SUM(cacheWriteTok), 0) AS tokensCacheWrite
|
|
181
|
+
FROM valid
|
|
182
|
+
GROUP BY day, provider, model
|
|
183
|
+
ORDER BY day, provider, model`
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function usageCoverageSql(source: CostSource): string {
|
|
187
|
+
const table = source
|
|
188
|
+
const assistantPredicate = assistantLedgerPredicate(source)
|
|
189
|
+
return `SELECT MIN(time_created) AS coverageStartAt
|
|
190
|
+
FROM ${table}
|
|
191
|
+
WHERE json_valid(data) AND ${assistantPredicate} AND time_created <= ?`
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function numberOf(value: unknown): number | undefined {
|
|
195
|
+
if (value === null || value === undefined) return undefined
|
|
196
|
+
const parsed = Number(value)
|
|
197
|
+
return Number.isFinite(parsed) ? parsed : undefined
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** A ledger label the catalog cannot know; never an empty string. */
|
|
201
|
+
export function ledgerLabel(value: unknown): string {
|
|
202
|
+
if (value === undefined || value === null) return 'unknown'
|
|
203
|
+
const text = String(value).trim()
|
|
204
|
+
return text === '' ? 'unknown' : text
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Price one group, or explain why it cannot be priced. */
|
|
208
|
+
export function priceTokens(
|
|
209
|
+
pricing: PricingSnapshot | undefined,
|
|
210
|
+
provider: string,
|
|
211
|
+
model: string,
|
|
212
|
+
tokens: { input: number; output: number; cacheRead: number; cacheWrite: number },
|
|
213
|
+
): { usd: number } | { reason: UnpricedReason } {
|
|
214
|
+
if (pricing === undefined) return { reason: 'no-pricing' }
|
|
215
|
+
const lookup = lookupModelPrice(pricing, provider, model)
|
|
216
|
+
if (!lookup.ok) return { reason: lookup.reason }
|
|
217
|
+
const cost = computeModelCost(lookup.price, tokens)
|
|
218
|
+
if (!cost.ok) return { reason: cost.reason }
|
|
219
|
+
return { usd: cost.usd }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Available chart windows. Rolling windows are exact 24-hour ranges ending now. */
|
|
223
|
+
export type UsageHistoryPeriod = '7d' | '15d' | '30d' | 'total'
|
|
224
|
+
|
|
225
|
+
/** Token quantities; `total` follows the cost report convention: input + output. */
|
|
226
|
+
export interface UsageTokenTotals {
|
|
227
|
+
input: number
|
|
228
|
+
output: number
|
|
229
|
+
cacheRead: number
|
|
230
|
+
cacheWrite: number
|
|
231
|
+
total: number
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** One UTC calendar-day bucket, with catalog estimate omitted when unpriceable. */
|
|
235
|
+
export interface UsageHistoryBucket extends UsageTokenTotals {
|
|
236
|
+
date: string
|
|
237
|
+
estimatedUsd?: number
|
|
238
|
+
pricingComplete: boolean
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** One provider/model's date series and totals. */
|
|
242
|
+
export interface UsageHistoryModel {
|
|
243
|
+
providerID: string
|
|
244
|
+
modelID: string
|
|
245
|
+
rows: number
|
|
246
|
+
agentlessRows: number
|
|
247
|
+
buckets: UsageHistoryBucket[]
|
|
248
|
+
totals: UsageTokenTotals
|
|
249
|
+
estimatedUsd?: number
|
|
250
|
+
pricingComplete: boolean
|
|
251
|
+
unpricedReason?: UnpricedReason
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export type UsagePricingStatus = 'empty' | 'unavailable' | 'partial' | 'complete'
|
|
255
|
+
|
|
256
|
+
/** Catalog-derived USD is an estimate, not a provider invoice. */
|
|
257
|
+
export interface UsageHistoryPricing {
|
|
258
|
+
status: UsagePricingStatus
|
|
259
|
+
complete: boolean
|
|
260
|
+
estimatedUsd?: number
|
|
261
|
+
unpricedModels: number
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Read-only chart data for the rows present in the current opencode.db. */
|
|
265
|
+
export interface UsageHistoryResult {
|
|
266
|
+
period: UsageHistoryPeriod
|
|
267
|
+
/** Earliest ledger record actually present in the database, as UTC date. */
|
|
268
|
+
coverageStart: string | null
|
|
269
|
+
/** Exact epoch-ms start of the earliest ledger record. */
|
|
270
|
+
coverageStartAt: number | null
|
|
271
|
+
/** True only when a rolling window begins before this database's earliest ledger record. */
|
|
272
|
+
partial: boolean
|
|
273
|
+
rows: number
|
|
274
|
+
buckets: UsageHistoryBucket[]
|
|
275
|
+
totals: UsageTokenTotals
|
|
276
|
+
models: UsageHistoryModel[]
|
|
277
|
+
pricing: UsageHistoryPricing
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export interface UsageHistoryOptions {
|
|
281
|
+
/** Injectable clock for deterministic rolling-window boundaries. */
|
|
282
|
+
now?: number
|
|
283
|
+
/** Explicit price snapshot; otherwise only the on-disk cache is read. */
|
|
284
|
+
pricing?: PricingSnapshot
|
|
285
|
+
/** Cache path/environment injection; all network refreshes are disabled. */
|
|
286
|
+
pricingOptions?: PricingOptions
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Current context estimate input; cache metrics are intentionally not accepted. */
|
|
290
|
+
export interface ActiveContextCostInput {
|
|
291
|
+
providerID: string | null
|
|
292
|
+
modelID: string | null
|
|
293
|
+
contextTokens: number | null
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export interface ActiveContextCostEstimate {
|
|
297
|
+
status: 'estimated' | 'unavailable'
|
|
298
|
+
/** Catalog estimate from context tokens × input price; never a billed amount. */
|
|
299
|
+
estimatedUsd?: number
|
|
300
|
+
billed: false
|
|
301
|
+
basis: 'pre-cache-context-tokens-times-input-price'
|
|
302
|
+
cacheDiscountApplied: false
|
|
303
|
+
reason?: 'invalid-context-token-count' | 'missing-model-identity' | UnpricedReason
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface UsageHistoryLedgerGroup {
|
|
307
|
+
day?: unknown
|
|
308
|
+
provider?: unknown
|
|
309
|
+
model?: unknown
|
|
310
|
+
rows?: unknown
|
|
311
|
+
agentlessRows?: unknown
|
|
312
|
+
tokensInput?: unknown
|
|
313
|
+
tokensOutput?: unknown
|
|
314
|
+
tokensCacheRead?: unknown
|
|
315
|
+
tokensCacheWrite?: unknown
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
interface MutableUsageTokens {
|
|
319
|
+
input: number
|
|
320
|
+
output: number
|
|
321
|
+
cacheRead: number
|
|
322
|
+
cacheWrite: number
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
interface MutableUsageDay {
|
|
326
|
+
tokens: MutableUsageTokens
|
|
327
|
+
rows: number
|
|
328
|
+
agentlessRows: number
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
interface MutableUsageModel {
|
|
332
|
+
providerID: string
|
|
333
|
+
modelID: string
|
|
334
|
+
tokens: MutableUsageTokens
|
|
335
|
+
rows: number
|
|
336
|
+
agentlessRows: number
|
|
337
|
+
days: Map<string, MutableUsageDay>
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function emptyUsageTokens(): MutableUsageTokens {
|
|
341
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function addUsageTokens(target: MutableUsageTokens, source: MutableUsageTokens): void {
|
|
345
|
+
target.input += source.input
|
|
346
|
+
target.output += source.output
|
|
347
|
+
target.cacheRead += source.cacheRead
|
|
348
|
+
target.cacheWrite += source.cacheWrite
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function toUsageTokenTotals(tokens: MutableUsageTokens): UsageTokenTotals {
|
|
352
|
+
return {
|
|
353
|
+
input: tokens.input,
|
|
354
|
+
output: tokens.output,
|
|
355
|
+
cacheRead: tokens.cacheRead,
|
|
356
|
+
cacheWrite: tokens.cacheWrite,
|
|
357
|
+
// Cache channels are shown independently and are not folded into total.
|
|
358
|
+
total: tokens.input + tokens.output,
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function offlinePricing(options?: UsageHistoryOptions): PricingSnapshot {
|
|
363
|
+
return options?.pricing ?? loadPricing({ ...options?.pricingOptions, offline: true }).snapshot
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Read daily token history for the Usage charts.
|
|
368
|
+
*
|
|
369
|
+
* Rolling periods are exact N×24-hour windows ending at `now`; daily buckets
|
|
370
|
+
* are UTC dates. Future-dated rows are excluded from every period, including
|
|
371
|
+
* `total`, while `total` has no lower age cap. Both V1 and V2 tables are read
|
|
372
|
+
* when a migrated database contains both. The database is opened read-only and
|
|
373
|
+
* model pricing comes only from a cached snapshot: this path never fetches pricing.
|
|
374
|
+
*/
|
|
375
|
+
export async function queryUsageHistory(
|
|
376
|
+
dbPath: string,
|
|
377
|
+
period: UsageHistoryPeriod,
|
|
378
|
+
options?: UsageHistoryOptions,
|
|
379
|
+
): Promise<UsageHistoryResult> {
|
|
380
|
+
const dayCounts: Record<Exclude<UsageHistoryPeriod, 'total'>, number> = {
|
|
381
|
+
'7d': 7,
|
|
382
|
+
'15d': 15,
|
|
383
|
+
'30d': 30,
|
|
384
|
+
}
|
|
385
|
+
if (period !== 'total' && !Object.hasOwn(dayCounts, period)) {
|
|
386
|
+
throw new Error(`unsupported usage history period: ${String(period)}`)
|
|
387
|
+
}
|
|
388
|
+
const now = options?.now ?? Date.now()
|
|
389
|
+
if (!Number.isFinite(now)) throw new Error('usage history clock must be finite')
|
|
390
|
+
const rolling = period !== 'total'
|
|
391
|
+
const since = rolling ? now - dayCounts[period] * 86_400_000 : undefined
|
|
392
|
+
const sqlite = (await import('node:sqlite')) as SqliteModule
|
|
393
|
+
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true })
|
|
394
|
+
try {
|
|
395
|
+
// Historical charts always mean all known ledger families in this file.
|
|
396
|
+
// The host-version override is a diagnostic narrowing for pantheon_cost,
|
|
397
|
+
// not a reason to hide rows from a database-wide history view.
|
|
398
|
+
const sources = resolveSources(db, undefined)
|
|
399
|
+
const models = new Map<string, MutableUsageModel>()
|
|
400
|
+
let rows = 0
|
|
401
|
+
let coverageStartAt: number | null = null
|
|
402
|
+
|
|
403
|
+
for (const source of sources) {
|
|
404
|
+
const coverage = db.prepare(usageCoverageSql(source)).get(now) as {
|
|
405
|
+
coverageStartAt?: unknown
|
|
406
|
+
}
|
|
407
|
+
const sourceStart = numberOf(coverage?.coverageStartAt)
|
|
408
|
+
if (sourceStart !== undefined) {
|
|
409
|
+
coverageStartAt =
|
|
410
|
+
coverageStartAt === null ? sourceStart : Math.min(coverageStartAt, sourceStart)
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const groups = db
|
|
414
|
+
.prepare(usageHistorySql(source, rolling))
|
|
415
|
+
.all(...(since === undefined ? [now] : [since, now])) as UsageHistoryLedgerGroup[]
|
|
416
|
+
for (const group of groups) {
|
|
417
|
+
if (typeof group.day !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(group.day)) continue
|
|
418
|
+
const providerID = ledgerLabel(group.provider)
|
|
419
|
+
const modelID = ledgerLabel(group.model)
|
|
420
|
+
const key = `${providerID}\u0000${modelID}`
|
|
421
|
+
const model = models.get(key) ?? {
|
|
422
|
+
providerID,
|
|
423
|
+
modelID,
|
|
424
|
+
tokens: emptyUsageTokens(),
|
|
425
|
+
rows: 0,
|
|
426
|
+
agentlessRows: 0,
|
|
427
|
+
days: new Map<string, MutableUsageDay>(),
|
|
428
|
+
}
|
|
429
|
+
const tokens: MutableUsageTokens = {
|
|
430
|
+
input: numberOf(group.tokensInput) ?? 0,
|
|
431
|
+
output: numberOf(group.tokensOutput) ?? 0,
|
|
432
|
+
cacheRead: numberOf(group.tokensCacheRead) ?? 0,
|
|
433
|
+
cacheWrite: numberOf(group.tokensCacheWrite) ?? 0,
|
|
434
|
+
}
|
|
435
|
+
const groupRows = numberOf(group.rows) ?? 0
|
|
436
|
+
const agentlessRows = numberOf(group.agentlessRows) ?? 0
|
|
437
|
+
rows += groupRows
|
|
438
|
+
addUsageTokens(model.tokens, tokens)
|
|
439
|
+
model.rows += groupRows
|
|
440
|
+
model.agentlessRows += agentlessRows
|
|
441
|
+
const day = model.days.get(group.day) ?? {
|
|
442
|
+
tokens: emptyUsageTokens(),
|
|
443
|
+
rows: 0,
|
|
444
|
+
agentlessRows: 0,
|
|
445
|
+
}
|
|
446
|
+
addUsageTokens(day.tokens, tokens)
|
|
447
|
+
day.rows += groupRows
|
|
448
|
+
day.agentlessRows += agentlessRows
|
|
449
|
+
model.days.set(group.day, day)
|
|
450
|
+
models.set(key, model)
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const priceSnapshot = offlinePricing(options)
|
|
455
|
+
const daily = new Map<
|
|
456
|
+
string,
|
|
457
|
+
{ tokens: MutableUsageTokens; usd: number; pricedModels: number; unpricedModels: number }
|
|
458
|
+
>()
|
|
459
|
+
let pricedModels = 0
|
|
460
|
+
let unpricedModels = 0
|
|
461
|
+
let estimatedUsd = 0
|
|
462
|
+
const modelRows: UsageHistoryModel[] = []
|
|
463
|
+
|
|
464
|
+
for (const model of models.values()) {
|
|
465
|
+
const totalsPrice = priceTokens(priceSnapshot, model.providerID, model.modelID, {
|
|
466
|
+
input: model.tokens.input,
|
|
467
|
+
output: model.tokens.output,
|
|
468
|
+
cacheRead: model.tokens.cacheRead,
|
|
469
|
+
cacheWrite: model.tokens.cacheWrite,
|
|
470
|
+
})
|
|
471
|
+
const modelPriced = 'usd' in totalsPrice
|
|
472
|
+
if ('usd' in totalsPrice) {
|
|
473
|
+
pricedModels += 1
|
|
474
|
+
estimatedUsd += totalsPrice.usd
|
|
475
|
+
} else {
|
|
476
|
+
unpricedModels += 1
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const buckets: UsageHistoryBucket[] = [...model.days.entries()]
|
|
480
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
481
|
+
.map(([date, value]) => {
|
|
482
|
+
const bucketPrice = priceTokens(priceSnapshot, model.providerID, model.modelID, {
|
|
483
|
+
input: value.tokens.input,
|
|
484
|
+
output: value.tokens.output,
|
|
485
|
+
cacheRead: value.tokens.cacheRead,
|
|
486
|
+
cacheWrite: value.tokens.cacheWrite,
|
|
487
|
+
})
|
|
488
|
+
const dailyTotal = daily.get(date) ?? {
|
|
489
|
+
tokens: emptyUsageTokens(),
|
|
490
|
+
usd: 0,
|
|
491
|
+
pricedModels: 0,
|
|
492
|
+
unpricedModels: 0,
|
|
493
|
+
}
|
|
494
|
+
addUsageTokens(dailyTotal.tokens, value.tokens)
|
|
495
|
+
if ('usd' in bucketPrice) {
|
|
496
|
+
dailyTotal.usd += bucketPrice.usd
|
|
497
|
+
dailyTotal.pricedModels += 1
|
|
498
|
+
} else {
|
|
499
|
+
dailyTotal.unpricedModels += 1
|
|
500
|
+
}
|
|
501
|
+
daily.set(date, dailyTotal)
|
|
502
|
+
return {
|
|
503
|
+
date,
|
|
504
|
+
...toUsageTokenTotals(value.tokens),
|
|
505
|
+
...('usd' in bucketPrice ? { estimatedUsd: bucketPrice.usd } : {}),
|
|
506
|
+
pricingComplete: 'usd' in bucketPrice,
|
|
507
|
+
}
|
|
508
|
+
})
|
|
509
|
+
|
|
510
|
+
modelRows.push({
|
|
511
|
+
providerID: model.providerID,
|
|
512
|
+
modelID: model.modelID,
|
|
513
|
+
rows: model.rows,
|
|
514
|
+
agentlessRows: model.agentlessRows,
|
|
515
|
+
buckets,
|
|
516
|
+
totals: toUsageTokenTotals(model.tokens),
|
|
517
|
+
...('usd' in totalsPrice ? { estimatedUsd: totalsPrice.usd } : {}),
|
|
518
|
+
pricingComplete: modelPriced,
|
|
519
|
+
...(!modelPriced && 'reason' in totalsPrice ? { unpricedReason: totalsPrice.reason } : {}),
|
|
520
|
+
})
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
modelRows.sort(
|
|
524
|
+
(left, right) =>
|
|
525
|
+
left.providerID.localeCompare(right.providerID) ||
|
|
526
|
+
left.modelID.localeCompare(right.modelID),
|
|
527
|
+
)
|
|
528
|
+
const buckets: UsageHistoryBucket[] = [...daily.entries()]
|
|
529
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
530
|
+
.map(([date, value]) => ({
|
|
531
|
+
date,
|
|
532
|
+
...toUsageTokenTotals(value.tokens),
|
|
533
|
+
...(value.pricedModels > 0 ? { estimatedUsd: value.usd } : {}),
|
|
534
|
+
pricingComplete: value.unpricedModels === 0,
|
|
535
|
+
}))
|
|
536
|
+
|
|
537
|
+
const empty = rows === 0
|
|
538
|
+
const pricingStatus: UsagePricingStatus = empty
|
|
539
|
+
? 'empty'
|
|
540
|
+
: pricedModels === 0
|
|
541
|
+
? 'unavailable'
|
|
542
|
+
: unpricedModels > 0
|
|
543
|
+
? 'partial'
|
|
544
|
+
: 'complete'
|
|
545
|
+
const totals = emptyUsageTokens()
|
|
546
|
+
for (const model of models.values()) addUsageTokens(totals, model.tokens)
|
|
547
|
+
const requestedStart = since
|
|
548
|
+
return {
|
|
549
|
+
period,
|
|
550
|
+
coverageStart:
|
|
551
|
+
coverageStartAt === null ? null : new Date(coverageStartAt).toISOString().slice(0, 10),
|
|
552
|
+
coverageStartAt,
|
|
553
|
+
partial:
|
|
554
|
+
requestedStart !== undefined &&
|
|
555
|
+
coverageStartAt !== null &&
|
|
556
|
+
coverageStartAt > requestedStart,
|
|
557
|
+
rows,
|
|
558
|
+
buckets,
|
|
559
|
+
totals: toUsageTokenTotals(totals),
|
|
560
|
+
models: modelRows,
|
|
561
|
+
pricing: {
|
|
562
|
+
status: pricingStatus,
|
|
563
|
+
complete: pricingStatus === 'complete',
|
|
564
|
+
...(pricedModels > 0 ? { estimatedUsd } : {}),
|
|
565
|
+
unpricedModels,
|
|
566
|
+
},
|
|
567
|
+
}
|
|
568
|
+
} finally {
|
|
569
|
+
db.close()
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Estimate current context cost using only its token count and cached input rate.
|
|
575
|
+
* This is a pre-cache estimate, applies no cache discount, and is not billed or
|
|
576
|
+
* used to alter host-reported session spend.
|
|
577
|
+
*/
|
|
578
|
+
export function estimateActiveContextCost(
|
|
579
|
+
input: ActiveContextCostInput,
|
|
580
|
+
options?: UsageHistoryOptions,
|
|
581
|
+
): ActiveContextCostEstimate {
|
|
582
|
+
const metadata = {
|
|
583
|
+
billed: false as const,
|
|
584
|
+
basis: 'pre-cache-context-tokens-times-input-price' as const,
|
|
585
|
+
cacheDiscountApplied: false as const,
|
|
586
|
+
}
|
|
587
|
+
if (
|
|
588
|
+
typeof input.contextTokens !== 'number' ||
|
|
589
|
+
!Number.isSafeInteger(input.contextTokens) ||
|
|
590
|
+
input.contextTokens < 0
|
|
591
|
+
) {
|
|
592
|
+
return { status: 'unavailable', ...metadata, reason: 'invalid-context-token-count' }
|
|
593
|
+
}
|
|
594
|
+
if (!input.providerID?.trim() || !input.modelID?.trim()) {
|
|
595
|
+
return { status: 'unavailable', ...metadata, reason: 'missing-model-identity' }
|
|
596
|
+
}
|
|
597
|
+
const pricing = offlinePricing(options)
|
|
598
|
+
const lookup = lookupModelPrice(pricing, input.providerID, input.modelID)
|
|
599
|
+
if (!lookup.ok) {
|
|
600
|
+
return { status: 'unavailable', ...metadata, reason: lookup.reason }
|
|
601
|
+
}
|
|
602
|
+
return {
|
|
603
|
+
status: 'estimated',
|
|
604
|
+
...metadata,
|
|
605
|
+
estimatedUsd: (input.contextTokens / 1_000_000) * lookup.price.inputPerMTok,
|
|
606
|
+
}
|
|
607
|
+
}
|