pantheon-opencode 1.6.2-beta.8 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +121 -3
  2. package/README.md +34 -60
  3. package/README.pt-BR.md +10 -12
  4. package/bin/pantheon-init.mjs +30 -32
  5. package/package.json +3 -3
  6. package/plugin.json +1 -1
  7. package/pyproject.toml +1 -1
  8. package/scripts/decision-router.mjs +41 -56
  9. package/scripts/install/decision-router-config.mjs +67 -1
  10. package/scripts/install/npx-cache-sweep.mjs +103 -0
  11. package/scripts/install/opencode.mjs +7 -7
  12. package/scripts/install/plugin.mjs +4 -3
  13. package/scripts/install/strings.mjs +4 -0
  14. package/scripts/release-gates.mjs +6 -82
  15. package/scripts/sync-tui.mjs +3 -3
  16. package/src/agents/aphrodite.md +1 -1
  17. package/src/agents/apollo.md +1 -0
  18. package/src/agents/athena.md +1 -0
  19. package/src/agents/demeter.md +1 -1
  20. package/src/agents/gaia.md +1 -0
  21. package/src/agents/hephaestus.md +1 -1
  22. package/src/agents/hermes.md +1 -1
  23. package/src/agents/iris.md +1 -1
  24. package/src/agents/mnemosyne.md +1 -0
  25. package/src/agents/nyx.md +1 -1
  26. package/src/agents/prometheus.md +1 -1
  27. package/src/agents/talos.md +1 -1
  28. package/src/agents/themis.md +1 -1
  29. package/src/agents/zeus.md +5 -2
  30. package/src/pantheon/jev-decision-tool.ts +366 -114
  31. package/src/pantheon/jev-decisions.ts +11 -13
  32. package/src/pantheon/jev-escalation.ts +639 -0
  33. package/src/pantheon/jev-quality-score.ts +432 -0
  34. package/src/pantheon/jev-risk-gate.ts +479 -0
  35. package/src/pantheon/local-decision-prompt.ts +12 -18
  36. package/src/pantheon/v2-decision-telemetry.ts +14 -4
  37. package/src/pantheon/v2-native-decisions.ts +1 -1
  38. package/src/plugin-v2.ts +201 -24
  39. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  40. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  41. package/src/plugins/tui/dist/server-v2.js +19 -789
  42. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  43. package/src/plugins/tui/dist/tui-v2.d.ts +12 -331
  44. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  45. package/src/plugins/tui/dist/tui-v2.js +257 -5370
  46. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  47. package/src/plugins/tui/dist/tui.js +1 -1
  48. package/src/plugins/tui/package-lock.json +2 -2
  49. package/src/plugins/tui/package.json +1 -1
  50. package/src/plugins/tui/src/index-v2.tsx +213 -86
  51. package/src/plugins/tui/src/server-v2.ts +18 -982
  52. package/src/plugins/tui/tsconfig.typecheck.json +1 -6
  53. package/src/plugins/tui/tsdown.config.ts +1 -11
  54. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +0 -749
  55. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +0 -1
  56. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  57. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  58. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  59. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  60. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  61. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  62. package/src/plugins/tui/dist/quota-cli.js +0 -184
  63. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  64. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +0 -684
  65. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +0 -1
  66. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +0 -118
  67. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +0 -1
  68. package/src/plugins/tui/dist/usage-history-worker.js +0 -25
  69. package/src/plugins/tui/dist/usage-history-worker.js.map +0 -1
  70. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  71. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  72. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  73. package/src/plugins/tui/src/quota-cli.ts +0 -237
  74. package/src/plugins/tui/src/quota-rpc.ts +0 -373
  75. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  76. package/src/plugins/tui/src/quota-v2.tsx +0 -1238
  77. package/src/plugins/tui/src/usage-history-contract.ts +0 -217
  78. package/src/plugins/tui/src/usage-history-validation.ts +0 -104
  79. package/src/plugins/tui/src/usage-history-view.tsx +0 -236
  80. package/src/plugins/tui/src/usage-history-worker.ts +0 -25
  81. package/src/plugins/tui/src/usage-view-model.ts +0 -272
@@ -1,749 +0,0 @@
1
- import { homedir } from "node:os";
2
- import { dirname, join } from "node:path";
3
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
- //#region src/model-pricing.ts
5
- /**
6
- * Model pricing — money for `pantheon_cost`.
7
- *
8
- * Prices come from the public catalog the OpenCode ecosystem already uses,
9
- * `https://models.dev/api.json` (USD per 1M tokens). The rule that shapes this
10
- * module is that a tool call must NEVER block on the network:
11
- *
12
- * - every call reads a normalized on-disk cache synchronously;
13
- * - an explicit `refreshPricing` is the only AWAITED fetch (bounded timeout);
14
- * - a missing or stale cache is refreshed in the BACKGROUND, with a short
15
- * timeout, so the next call benefits without this one waiting;
16
- * - every network/parse failure degrades to "pricing unavailable" and the
17
- * token report keeps working.
18
- *
19
- * An unknown model is never priced at zero. `0` is a real catalog price (a free
20
- * model), and conflating it with "no price" would report free usage for every
21
- * model the catalog has never heard of — which is precisely the number a tier
22
- * decision would be made on.
23
- *
24
- * Cache location follows the repository's existing config-dir convention
25
- * (`PANTHEON_HOME` → `$XDG_CONFIG_HOME/opencode` → `~/.config/opencode`), so no
26
- * new root is invented: `<configDir>/cache/models-dev.json`.
27
- *
28
- * @module model-pricing
29
- */
30
- /** The catalog URL every OpenCode-adjacent tool prices against. */
31
- const MODELS_DEV_URL = "https://models.dev/api.json";
32
- /** Cache payload version; a mismatch is treated as "no cache". */
33
- const PRICING_CACHE_VERSION = 1;
34
- /** Cached prices are considered fresh for one day. */
35
- const PRICING_TTL_MS = 864e5;
36
- /** Upper bound for any catalog fetch, so no request can outlive a tool call. */
37
- const PRICING_TIMEOUT_MS = 3e3;
38
- /** Resolve the OpenCode config dir, mirroring `_pantheon_paths.py`. */
39
- function resolvePricingCacheDir(env = process.env) {
40
- const explicit = env.PANTHEON_HOME?.trim();
41
- if (explicit !== void 0 && explicit !== "") return explicit;
42
- const xdg = env.XDG_CONFIG_HOME?.trim();
43
- const base = xdg !== void 0 && xdg !== "" ? xdg : join(homedir(), ".config");
44
- return join(base, "opencode");
45
- }
46
- /** Cache file for the normalized catalog. */
47
- function resolvePricingCachePath(env = process.env) {
48
- return join(resolvePricingCacheDir(env), "cache", "models-dev.json");
49
- }
50
- function isRecord(value) {
51
- return typeof value === "object" && value !== null && !Array.isArray(value);
52
- }
53
- function finiteNumber(value) {
54
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
55
- }
56
- /** Reject nonsense prices rather than reporting a $2B session. */
57
- const MAX_SANE_PER_MTOK = 1e5;
58
- function nonNegativePrice(value) {
59
- const parsed = finiteNumber(value);
60
- if (parsed === void 0 || parsed < 0 || parsed > MAX_SANE_PER_MTOK) return void 0;
61
- return parsed;
62
- }
63
- /** Validate one already-normalized price from the cache file. */
64
- function buildPrice(input, output, cacheRead, cacheWrite) {
65
- if (input === void 0 || output === void 0) return void 0;
66
- return {
67
- inputPerMTok: input,
68
- outputPerMTok: output,
69
- ...cacheRead === void 0 ? {} : { cacheReadPerMTok: cacheRead },
70
- ...cacheWrite === void 0 ? {} : { cacheWritePerMTok: cacheWrite }
71
- };
72
- }
73
- function parseNormalizedPrice(value) {
74
- if (!isRecord(value)) return void 0;
75
- return buildPrice(nonNegativePrice(value.inputPerMTok), nonNegativePrice(value.outputPerMTok), nonNegativePrice(value.cacheReadPerMTok), nonNegativePrice(value.cacheWritePerMTok));
76
- }
77
- /**
78
- * Validate the normalized `provider → model → price` shape.
79
- *
80
- * The cache stores the RESULT of {@link parseCatalogPayload}, not the raw
81
- * models.dev payload, so it must not be re-parsed as one: a normalized entry has
82
- * no `models` key, and treating it as a payload would silently read a valid
83
- * cache as empty.
84
- */
85
- function parseNormalizedProviders(value) {
86
- if (!isRecord(value)) return void 0;
87
- const providers = {};
88
- for (const [providerId, models] of Object.entries(value)) {
89
- if (!isRecord(models)) continue;
90
- const priced = {};
91
- for (const [modelId, price] of Object.entries(models)) {
92
- const parsed = parseNormalizedPrice(price);
93
- if (parsed !== void 0) priced[modelId.toLowerCase()] = parsed;
94
- }
95
- if (Object.keys(priced).length > 0) providers[providerId.toLowerCase()] = priced;
96
- }
97
- return Object.keys(providers).length === 0 ? void 0 : providers;
98
- }
99
- /** Parse one catalog model entry. Missing input/output cost ⇒ unpriced. */
100
- function parseModelPrice(model) {
101
- if (!isRecord(model)) return void 0;
102
- const cost = model.cost;
103
- if (!isRecord(cost)) return void 0;
104
- return buildPrice(nonNegativePrice(cost.input), nonNegativePrice(cost.output), nonNegativePrice(cost.cache_read), nonNegativePrice(cost.cache_write));
105
- }
106
- /**
107
- * Normalize a models.dev payload into `provider → model → price`.
108
- *
109
- * Provider and model ids are lowercased because the ledger stores whatever the
110
- * host wrote (`opencode-go`) and the catalog keys are not case-normalized.
111
- */
112
- function parseCatalogPayload(payload) {
113
- if (!isRecord(payload)) return void 0;
114
- const providers = {};
115
- for (const [providerId, provider] of Object.entries(payload)) {
116
- if (!isRecord(provider)) continue;
117
- const models = provider.models;
118
- if (!isRecord(models)) continue;
119
- const priced = {};
120
- for (const [modelId, model] of Object.entries(models)) {
121
- const price = parseModelPrice(model);
122
- if (price !== void 0) priced[modelId.toLowerCase()] = price;
123
- }
124
- if (Object.keys(priced).length > 0) providers[providerId.toLowerCase()] = priced;
125
- }
126
- return Object.keys(providers).length === 0 ? void 0 : providers;
127
- }
128
- function priceKey(price) {
129
- return [
130
- price.inputPerMTok,
131
- price.outputPerMTok,
132
- price.cacheReadPerMTok ?? "-",
133
- price.cacheWritePerMTok ?? "-"
134
- ].join("/");
135
- }
136
- function indexCatalog(providers) {
137
- const index = /* @__PURE__ */ new Map();
138
- const modelIndex = /* @__PURE__ */ new Map();
139
- const seen = /* @__PURE__ */ new Map();
140
- for (const [providerId, models] of Object.entries(providers)) for (const [modelId, price] of Object.entries(models)) {
141
- index.set(`${providerId}/${modelId}`, price);
142
- const bucket = modelIndex.get(modelId) ?? [];
143
- const keys = seen.get(modelId) ?? /* @__PURE__ */ new Set();
144
- const key = priceKey(price);
145
- if (!keys.has(key)) {
146
- keys.add(key);
147
- bucket.push(price);
148
- seen.set(modelId, keys);
149
- modelIndex.set(modelId, bucket);
150
- }
151
- }
152
- return {
153
- index,
154
- modelIndex
155
- };
156
- }
157
- function snapshotFromCatalog(catalog, now, ttlMs, refreshing) {
158
- const { index, modelIndex } = indexCatalog(catalog.providers);
159
- return {
160
- index,
161
- modelIndex,
162
- fetchedAt: catalog.fetchedAt,
163
- stale: Math.max(0, now - catalog.fetchedAt) > ttlMs,
164
- refreshing
165
- };
166
- }
167
- function unavailableSnapshot(reason) {
168
- return {
169
- index: /* @__PURE__ */ new Map(),
170
- modelIndex: /* @__PURE__ */ new Map(),
171
- stale: false,
172
- refreshing: false,
173
- unavailableReason: reason
174
- };
175
- }
176
- function parseCachedCatalog(raw) {
177
- if (!isRecord(raw)) return void 0;
178
- if (raw.version !== PRICING_CACHE_VERSION) return void 0;
179
- const fetchedAt = finiteNumber(raw.fetchedAt);
180
- if (fetchedAt === void 0) return void 0;
181
- const providers = parseNormalizedProviders(raw.providers);
182
- if (providers === void 0) return void 0;
183
- return {
184
- version: PRICING_CACHE_VERSION,
185
- fetchedAt,
186
- providers
187
- };
188
- }
189
- /** Read the normalized cache. Any problem reads as "no cache", never as zero. */
190
- function readPricingCache(cachePath) {
191
- try {
192
- if (!existsSync(cachePath)) return void 0;
193
- return parseCachedCatalog(JSON.parse(readFileSync(cachePath, "utf8")));
194
- } catch {
195
- return;
196
- }
197
- }
198
- /** Write atomically; a cache that cannot be written must not break a report. */
199
- function writePricingCache(cachePath, catalog) {
200
- const temp = `${cachePath}.tmp-${process.pid}`;
201
- try {
202
- mkdirSync(dirname(cachePath), { recursive: true });
203
- writeFileSync(temp, `${JSON.stringify(catalog)}\n`, "utf8");
204
- renameSync(temp, cachePath);
205
- return true;
206
- } catch {
207
- return false;
208
- }
209
- }
210
- const inFlight = /* @__PURE__ */ new Map();
211
- /**
212
- * Offline is a HOST-wide guarantee, not a hint.
213
- *
214
- * Both switches are honoured on every path that could open a socket, so the
215
- * env var cannot be defeated by a caller that passes `refreshPricing` (or by a
216
- * future code path that forgets to check). The reason names both switches,
217
- * because a user reading the report needs to know which one to change.
218
- */
219
- const OFFLINE_REFUSAL = "refreshPricing cannot run: PANTHEON_COST_OFFLINE=1 (or the offline option) forbids every network request";
220
- function isPricingOffline(options) {
221
- const env = options?.env ?? process.env;
222
- return options?.offline === true || env.PANTHEON_COST_OFFLINE === "1";
223
- }
224
- /**
225
- * Fetch the catalog once per cache path at a time, bounded by a timeout.
226
- *
227
- * Failures are values, not throws: the caller reports "pricing unavailable" and
228
- * keeps the token ledger it already read.
229
- */
230
- function refreshPricingCatalog(options) {
231
- if (isPricingOffline(options)) return Promise.resolve({
232
- ...unavailableSnapshot(OFFLINE_REFUSAL),
233
- refused: true,
234
- offline: true
235
- });
236
- const env = options?.env ?? process.env;
237
- const cachePath = options?.cachePath ?? resolvePricingCachePath(env);
238
- const existing = inFlight.get(cachePath);
239
- if (existing !== void 0) return existing;
240
- const now = (options?.now ?? Date.now)();
241
- const ttlMs = options?.ttlMs ?? PRICING_TTL_MS;
242
- const doFetch = options?.fetchImpl ?? ((url, init) => fetch(url, {
243
- ...init.signal === void 0 ? {} : { signal: init.signal },
244
- ...init.headers === void 0 ? {} : { headers: init.headers }
245
- }));
246
- const task = (async () => {
247
- try {
248
- const response = await doFetch(MODELS_DEV_URL, {
249
- signal: AbortSignal.timeout(PRICING_TIMEOUT_MS),
250
- headers: { accept: "application/json" }
251
- });
252
- if (!response.ok) return unavailableSnapshot(`models.dev returned HTTP ${response.status}`);
253
- const providers = parseCatalogPayload(await response.json());
254
- if (providers === void 0) return unavailableSnapshot("models.dev payload carried no usable prices");
255
- const catalog = {
256
- version: PRICING_CACHE_VERSION,
257
- fetchedAt: now,
258
- providers
259
- };
260
- const cached = writePricingCache(cachePath, catalog);
261
- const snapshot = snapshotFromCatalog(catalog, now, ttlMs, false);
262
- return cached ? snapshot : {
263
- ...snapshot,
264
- unavailableReason: "price cache is not writable"
265
- };
266
- } catch (error) {
267
- return unavailableSnapshot(`models.dev fetch failed: ${error instanceof Error ? error.message : String(error)}`);
268
- } finally {
269
- inFlight.delete(cachePath);
270
- }
271
- })();
272
- inFlight.set(cachePath, task);
273
- return task;
274
- }
275
- /**
276
- * Load prices without blocking on the network.
277
- *
278
- * A stale cache is served immediately and refreshed in the background; with no
279
- * cache there is nothing to serve, so the snapshot is explicitly unavailable
280
- * and `pending` carries the opportunistic refresh for callers that want it.
281
- */
282
- function loadPricing(options) {
283
- const env = options?.env ?? process.env;
284
- const cachePath = options?.cachePath ?? resolvePricingCachePath(env);
285
- const now = (options?.now ?? Date.now)();
286
- const ttlMs = options?.ttlMs ?? PRICING_TTL_MS;
287
- const catalog = readPricingCache(cachePath);
288
- const offline = isPricingOffline(options);
289
- if (catalog === void 0) {
290
- if (offline) return { snapshot: {
291
- ...unavailableSnapshot("no price cache, and pricing is offline (PANTHEON_COST_OFFLINE=1 or the offline option)"),
292
- offline: true
293
- } };
294
- const pending = refreshPricingCatalog(options);
295
- return {
296
- snapshot: unavailableSnapshot("no cached models.dev catalog yet; fetching one in the background"),
297
- pending: pending.then(() => void 0)
298
- };
299
- }
300
- const snapshot = snapshotFromCatalog(catalog, now, ttlMs, false);
301
- if (!snapshot.stale || offline) return { snapshot: offline ? {
302
- ...snapshot,
303
- offline: true
304
- } : snapshot };
305
- const pending = refreshPricingCatalog(options);
306
- return {
307
- snapshot: {
308
- ...snapshot,
309
- refreshing: true
310
- },
311
- pending: pending.then(() => void 0)
312
- };
313
- }
314
- /**
315
- * Resolve a price for one ledger model.
316
- *
317
- * Exact `provider/model` wins. A model that exists under exactly one provider
318
- * price is accepted when the ledger's provider id is unknown to the catalog
319
- * (real hosts name their own gateways, e.g. `opencode-go` serving a model the
320
- * catalog lists under `opencode`). Two DIFFERENT prices for the same model id
321
- * are ambiguous and stay unpriced rather than guessing a provider.
322
- */
323
- function lookupModelPrice(snapshot, providerId, modelId) {
324
- if (snapshot.index.size === 0) return {
325
- ok: false,
326
- reason: "no-pricing"
327
- };
328
- const model = (modelId ?? "").trim().toLowerCase();
329
- if (model === "") return {
330
- ok: false,
331
- reason: "unknown-model"
332
- };
333
- const provider = (providerId ?? "").trim().toLowerCase();
334
- if (provider !== "") {
335
- const exact = snapshot.index.get(`${provider}/${model}`);
336
- if (exact !== void 0) return {
337
- ok: true,
338
- price: exact
339
- };
340
- }
341
- const candidates = snapshot.modelIndex.get(model) ?? [];
342
- const only = candidates.length === 1 ? candidates[0] : void 0;
343
- if (only !== void 0) return {
344
- ok: true,
345
- price: only
346
- };
347
- if (candidates.length === 0) return {
348
- ok: false,
349
- reason: "unknown-model"
350
- };
351
- return {
352
- ok: false,
353
- reason: "ambiguous-model"
354
- };
355
- }
356
- /**
357
- * Cost of one model's token counts.
358
- *
359
- * Cache tokens are billed at their own rate; when the catalog has no cache rate
360
- * the row is unpriced instead of being charged at the input rate or at zero.
361
- */
362
- function computeModelCost(price, tokens) {
363
- let usd = (tokens.input * price.inputPerMTok + tokens.output * price.outputPerMTok) / 1e6;
364
- if (tokens.cacheRead > 0) {
365
- const rate = price.cacheReadPerMTok;
366
- if (rate === void 0) return {
367
- ok: false,
368
- reason: "missing-cache-price"
369
- };
370
- usd += tokens.cacheRead * rate / 1e6;
371
- }
372
- if (tokens.cacheWrite > 0) {
373
- const rate = price.cacheWritePerMTok;
374
- if (rate === void 0) return {
375
- ok: false,
376
- reason: "missing-cache-price"
377
- };
378
- usd += tokens.cacheWrite * rate / 1e6;
379
- }
380
- return {
381
- ok: true,
382
- usd
383
- };
384
- }
385
- //#endregion
386
- //#region src/cost-data.ts
387
- /**
388
- * Read-only cost and usage data shared by the CLI and the TUI package.
389
- *
390
- * This module lives inside the TUI package so its worker and bundled server do
391
- * not import source files outside the package boundary. The CLI imports these
392
- * same helpers, preserving a single implementation.
393
- */
394
- const COST_SOURCES = ["message", "session_message"];
395
- /**
396
- * Which table family each host generation stores its ledger in.
397
- *
398
- * Spelled out rather than comparing the literals: `'message' === 'v1'` is
399
- * false, so a filter written as `source === requested` narrows to nothing and
400
- * every version-pinned read fails.
401
- */
402
- const VERSION_SOURCES = {
403
- v1: "message",
404
- v2: "session_message"
405
- };
406
- /** The XDG state directory every real host installation writes its ledger to. */
407
- function defaultDbPath() {
408
- const xdg = process.env.XDG_DATA_HOME;
409
- const dataHome = xdg !== void 0 && xdg !== "" ? xdg : join(homedir(), ".local", "share");
410
- return join(dataHome, "opencode", "opencode.db");
411
- }
412
- /** Read and validate the optional host-generation selector. */
413
- function requestedVersion() {
414
- const configured = process.env.PANTHEON_OPENCODE_VERSION;
415
- if (configured === void 0) return void 0;
416
- if (configured !== "v1" && configured !== "v2") throw new Error(`invalid PANTHEON_OPENCODE_VERSION "${configured}"; expected "v1" or "v2"`);
417
- return configured;
418
- }
419
- /**
420
- * Resolve the database.
421
- *
422
- * Precedence: explicit option → PANTHEON_COST_DB → OPENCODE_DB → the XDG
423
- * default `opencode.db`. An invalid PANTHEON_OPENCODE_VERSION fails fast rather
424
- * than being silently ignored.
425
- *
426
- * There is deliberately NO per-version filename. Deriving one from the host
427
- * generation pointed the V2 report at `opencode-v2.db`, which exists only
428
- * because a sandbox sets OPENCODE_DB — hence OPENCODE_DB's place in this chain.
429
- */
430
- function resolveCostDbPath(options) {
431
- const explicit = options?.dbPath || process.env.PANTHEON_COST_DB || process.env.OPENCODE_DB;
432
- if (explicit) return explicit;
433
- requestedVersion();
434
- return defaultDbPath();
435
- }
436
- /**
437
- * Detect the ledger families by TABLE PRESENCE.
438
- *
439
- * Presence is the only reliable discriminator: a migrated database carries both
440
- * families, so pinning a schema-version constant would break whichever
441
- * population it excluded, and no manifest declares a supported host range.
442
- * PANTHEON_OPENCODE_VERSION only NARROWS an already-detected set — it never
443
- * chooses a file and never invents a family that is not there.
444
- */
445
- function resolveSources(db, requested) {
446
- const present = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('message', 'session_message')").all().map((row) => String(row.name)));
447
- const detected = COST_SOURCES.filter((source) => present.has(source));
448
- if (detected.length === 0) throw new Error("incompatible opencode.db schema: neither the \"message\" nor the \"session_message\" table exists, so there is no token ledger to read");
449
- if (requested === void 0) return detected;
450
- const wanted = VERSION_SOURCES[requested];
451
- const narrowed = detected.filter((source) => source === wanted);
452
- if (narrowed.length === 0) throw new Error(`incompatible opencode.db schema: PANTHEON_OPENCODE_VERSION=${requested} selected no table family, but this database contains ${detected.join(" and ")}`);
453
- return narrowed;
454
- }
455
- /**
456
- * UTC day + provider/model aggregation used by the TUI charts.
457
- *
458
- * The only interpolated fragments are fixed module constants (family table,
459
- * discriminator, and time predicates). JSON is validated in the CTE before
460
- * extraction, and all time bounds remain bound SQL parameters.
461
- */
462
- function assistantLedgerPredicate(source) {
463
- return source === "message" ? "CASE WHEN json_valid(data) THEN json_extract(data, '$.role') = 'assistant' ELSE 0 END" : "type = 'assistant'";
464
- }
465
- function usageHistorySql(source, rolling) {
466
- return `
467
- WITH valid AS (
468
- SELECT strftime('%Y-%m-%d', time_created / 1000, 'unixepoch') AS day,
469
- COALESCE(NULLIF(TRIM(json_extract(data, '$.model.providerID')), ''),
470
- NULLIF(TRIM(json_extract(data, '$.providerID')), '')) AS provider,
471
- COALESCE(NULLIF(TRIM(json_extract(data, '$.model.id')), ''),
472
- NULLIF(TRIM(json_extract(data, '$.modelID')), '')) AS model,
473
- CASE WHEN json_type(data, '$.agent') IS NULL
474
- OR json_extract(data, '$.agent') IS NULL
475
- OR TRIM(json_extract(data, '$.agent')) = ''
476
- THEN 1 ELSE 0 END AS agentless,
477
- CASE WHEN json_type(data, '$.tokens.input') IN ('integer', 'real')
478
- AND json_extract(data, '$.tokens.input') >= 0
479
- THEN CAST(json_extract(data, '$.tokens.input') AS INTEGER) ELSE 0 END AS inTok,
480
- CASE WHEN json_type(data, '$.tokens.output') IN ('integer', 'real')
481
- AND json_extract(data, '$.tokens.output') >= 0
482
- THEN CAST(json_extract(data, '$.tokens.output') AS INTEGER) ELSE 0 END AS outTok,
483
- CASE WHEN json_type(data, '$.tokens.cache.read') IN ('integer', 'real')
484
- AND json_extract(data, '$.tokens.cache.read') >= 0
485
- THEN CAST(json_extract(data, '$.tokens.cache.read') AS INTEGER) ELSE 0 END AS cacheReadTok,
486
- CASE WHEN json_type(data, '$.tokens.cache.write') IN ('integer', 'real')
487
- AND json_extract(data, '$.tokens.cache.write') >= 0
488
- THEN CAST(json_extract(data, '$.tokens.cache.write') AS INTEGER) ELSE 0 END AS cacheWriteTok
489
- FROM ${source}
490
- WHERE json_valid(data) AND ${assistantLedgerPredicate(source)} ${rolling ? "AND time_created >= ? AND time_created <= ?" : "AND time_created <= ?"}
491
- )
492
- SELECT day,
493
- provider,
494
- model,
495
- COUNT(*) AS rows,
496
- SUM(agentless) AS agentlessRows,
497
- COALESCE(SUM(inTok), 0) AS tokensInput,
498
- COALESCE(SUM(outTok), 0) AS tokensOutput,
499
- COALESCE(SUM(cacheReadTok), 0) AS tokensCacheRead,
500
- COALESCE(SUM(cacheWriteTok), 0) AS tokensCacheWrite
501
- FROM valid
502
- GROUP BY day, provider, model
503
- ORDER BY day, provider, model`;
504
- }
505
- function usageCoverageSql(source) {
506
- return `SELECT MIN(time_created) AS coverageStartAt
507
- FROM ${source}
508
- WHERE json_valid(data) AND ${assistantLedgerPredicate(source)} AND time_created <= ?`;
509
- }
510
- function numberOf(value) {
511
- if (value === null || value === void 0) return void 0;
512
- const parsed = Number(value);
513
- return Number.isFinite(parsed) ? parsed : void 0;
514
- }
515
- /** A ledger label the catalog cannot know; never an empty string. */
516
- function ledgerLabel(value) {
517
- if (value === void 0 || value === null) return "unknown";
518
- const text = String(value).trim();
519
- return text === "" ? "unknown" : text;
520
- }
521
- /** Price one group, or explain why it cannot be priced. */
522
- function priceTokens(pricing, provider, model, tokens) {
523
- if (pricing === void 0) return { reason: "no-pricing" };
524
- const lookup = lookupModelPrice(pricing, provider, model);
525
- if (!lookup.ok) return { reason: lookup.reason };
526
- const cost = computeModelCost(lookup.price, tokens);
527
- if (!cost.ok) return { reason: cost.reason };
528
- return { usd: cost.usd };
529
- }
530
- function emptyUsageTokens() {
531
- return {
532
- input: 0,
533
- output: 0,
534
- cacheRead: 0,
535
- cacheWrite: 0
536
- };
537
- }
538
- function addUsageTokens(target, source) {
539
- target.input += source.input;
540
- target.output += source.output;
541
- target.cacheRead += source.cacheRead;
542
- target.cacheWrite += source.cacheWrite;
543
- }
544
- function toUsageTokenTotals(tokens) {
545
- return {
546
- input: tokens.input,
547
- output: tokens.output,
548
- cacheRead: tokens.cacheRead,
549
- cacheWrite: tokens.cacheWrite,
550
- total: tokens.input + tokens.output
551
- };
552
- }
553
- function offlinePricing(options) {
554
- return options?.pricing ?? loadPricing({
555
- ...options?.pricingOptions,
556
- offline: true
557
- }).snapshot;
558
- }
559
- /**
560
- * Read daily token history for the Usage charts.
561
- *
562
- * Rolling periods are exact N×24-hour windows ending at `now`; daily buckets
563
- * are UTC dates. Future-dated rows are excluded from every period, including
564
- * `total`, while `total` has no lower age cap. Both V1 and V2 tables are read
565
- * when a migrated database contains both. The database is opened read-only and
566
- * model pricing comes only from a cached snapshot: this path never fetches pricing.
567
- */
568
- async function queryUsageHistory(dbPath, period, options) {
569
- const dayCounts = {
570
- "7d": 7,
571
- "15d": 15,
572
- "30d": 30
573
- };
574
- if (period !== "total" && !Object.hasOwn(dayCounts, period)) throw new Error(`unsupported usage history period: ${String(period)}`);
575
- const now = options?.now ?? Date.now();
576
- if (!Number.isFinite(now)) throw new Error("usage history clock must be finite");
577
- const rolling = period !== "total";
578
- const since = rolling ? now - dayCounts[period] * 864e5 : void 0;
579
- const db = new (await (import("node:sqlite"))).DatabaseSync(dbPath, { readOnly: true });
580
- try {
581
- const sources = resolveSources(db, void 0);
582
- const models = /* @__PURE__ */ new Map();
583
- let rows = 0;
584
- let coverageStartAt = null;
585
- for (const source of sources) {
586
- const sourceStart = numberOf(db.prepare(usageCoverageSql(source)).get(now)?.coverageStartAt);
587
- if (sourceStart !== void 0) coverageStartAt = coverageStartAt === null ? sourceStart : Math.min(coverageStartAt, sourceStart);
588
- const groups = db.prepare(usageHistorySql(source, rolling)).all(...since === void 0 ? [now] : [since, now]);
589
- for (const group of groups) {
590
- if (typeof group.day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(group.day)) continue;
591
- const providerID = ledgerLabel(group.provider);
592
- const modelID = ledgerLabel(group.model);
593
- const key = `${providerID}\u0000${modelID}`;
594
- const model = models.get(key) ?? {
595
- providerID,
596
- modelID,
597
- tokens: emptyUsageTokens(),
598
- rows: 0,
599
- agentlessRows: 0,
600
- days: /* @__PURE__ */ new Map()
601
- };
602
- const tokens = {
603
- input: numberOf(group.tokensInput) ?? 0,
604
- output: numberOf(group.tokensOutput) ?? 0,
605
- cacheRead: numberOf(group.tokensCacheRead) ?? 0,
606
- cacheWrite: numberOf(group.tokensCacheWrite) ?? 0
607
- };
608
- const groupRows = numberOf(group.rows) ?? 0;
609
- const agentlessRows = numberOf(group.agentlessRows) ?? 0;
610
- rows += groupRows;
611
- addUsageTokens(model.tokens, tokens);
612
- model.rows += groupRows;
613
- model.agentlessRows += agentlessRows;
614
- const day = model.days.get(group.day) ?? {
615
- tokens: emptyUsageTokens(),
616
- rows: 0,
617
- agentlessRows: 0
618
- };
619
- addUsageTokens(day.tokens, tokens);
620
- day.rows += groupRows;
621
- day.agentlessRows += agentlessRows;
622
- model.days.set(group.day, day);
623
- models.set(key, model);
624
- }
625
- }
626
- const priceSnapshot = offlinePricing(options);
627
- const daily = /* @__PURE__ */ new Map();
628
- let pricedModels = 0;
629
- let unpricedModels = 0;
630
- let estimatedUsd = 0;
631
- const modelRows = [];
632
- for (const model of models.values()) {
633
- const totalsPrice = priceTokens(priceSnapshot, model.providerID, model.modelID, {
634
- input: model.tokens.input,
635
- output: model.tokens.output,
636
- cacheRead: model.tokens.cacheRead,
637
- cacheWrite: model.tokens.cacheWrite
638
- });
639
- const modelPriced = "usd" in totalsPrice;
640
- if ("usd" in totalsPrice) {
641
- pricedModels += 1;
642
- estimatedUsd += totalsPrice.usd;
643
- } else unpricedModels += 1;
644
- const buckets = [...model.days.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([date, value]) => {
645
- const bucketPrice = priceTokens(priceSnapshot, model.providerID, model.modelID, {
646
- input: value.tokens.input,
647
- output: value.tokens.output,
648
- cacheRead: value.tokens.cacheRead,
649
- cacheWrite: value.tokens.cacheWrite
650
- });
651
- const dailyTotal = daily.get(date) ?? {
652
- tokens: emptyUsageTokens(),
653
- usd: 0,
654
- pricedModels: 0,
655
- unpricedModels: 0
656
- };
657
- addUsageTokens(dailyTotal.tokens, value.tokens);
658
- if ("usd" in bucketPrice) {
659
- dailyTotal.usd += bucketPrice.usd;
660
- dailyTotal.pricedModels += 1;
661
- } else dailyTotal.unpricedModels += 1;
662
- daily.set(date, dailyTotal);
663
- return {
664
- date,
665
- ...toUsageTokenTotals(value.tokens),
666
- ..."usd" in bucketPrice ? { estimatedUsd: bucketPrice.usd } : {},
667
- pricingComplete: "usd" in bucketPrice
668
- };
669
- });
670
- modelRows.push({
671
- providerID: model.providerID,
672
- modelID: model.modelID,
673
- rows: model.rows,
674
- agentlessRows: model.agentlessRows,
675
- buckets,
676
- totals: toUsageTokenTotals(model.tokens),
677
- ..."usd" in totalsPrice ? { estimatedUsd: totalsPrice.usd } : {},
678
- pricingComplete: modelPriced,
679
- ...!modelPriced && "reason" in totalsPrice ? { unpricedReason: totalsPrice.reason } : {}
680
- });
681
- }
682
- modelRows.sort((left, right) => left.providerID.localeCompare(right.providerID) || left.modelID.localeCompare(right.modelID));
683
- const buckets = [...daily.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([date, value]) => ({
684
- date,
685
- ...toUsageTokenTotals(value.tokens),
686
- ...value.pricedModels > 0 ? { estimatedUsd: value.usd } : {},
687
- pricingComplete: value.unpricedModels === 0
688
- }));
689
- const pricingStatus = rows === 0 ? "empty" : pricedModels === 0 ? "unavailable" : unpricedModels > 0 ? "partial" : "complete";
690
- const totals = emptyUsageTokens();
691
- for (const model of models.values()) addUsageTokens(totals, model.tokens);
692
- const requestedStart = since;
693
- return {
694
- period,
695
- coverageStart: coverageStartAt === null ? null : new Date(coverageStartAt).toISOString().slice(0, 10),
696
- coverageStartAt,
697
- partial: requestedStart !== void 0 && coverageStartAt !== null && coverageStartAt > requestedStart,
698
- rows,
699
- buckets,
700
- totals: toUsageTokenTotals(totals),
701
- models: modelRows,
702
- pricing: {
703
- status: pricingStatus,
704
- complete: pricingStatus === "complete",
705
- ...pricedModels > 0 ? { estimatedUsd } : {},
706
- unpricedModels
707
- }
708
- };
709
- } finally {
710
- db.close();
711
- }
712
- }
713
- /**
714
- * Estimate current context cost using only its token count and cached input rate.
715
- * This is a pre-cache estimate, applies no cache discount, and is not billed or
716
- * used to alter host-reported session spend.
717
- */
718
- function estimateActiveContextCost(input, options) {
719
- const metadata = {
720
- billed: false,
721
- basis: "pre-cache-context-tokens-times-input-price",
722
- cacheDiscountApplied: false
723
- };
724
- if (typeof input.contextTokens !== "number" || !Number.isSafeInteger(input.contextTokens) || input.contextTokens < 0) return {
725
- status: "unavailable",
726
- ...metadata,
727
- reason: "invalid-context-token-count"
728
- };
729
- if (!input.providerID?.trim() || !input.modelID?.trim()) return {
730
- status: "unavailable",
731
- ...metadata,
732
- reason: "missing-model-identity"
733
- };
734
- const lookup = lookupModelPrice(offlinePricing(options), input.providerID, input.modelID);
735
- if (!lookup.ok) return {
736
- status: "unavailable",
737
- ...metadata,
738
- reason: lookup.reason
739
- };
740
- return {
741
- status: "estimated",
742
- ...metadata,
743
- estimatedUsd: input.contextTokens / 1e6 * lookup.price.inputPerMTok
744
- };
745
- }
746
- //#endregion
747
- export { queryUsageHistory as n, resolveCostDbPath as r, estimateActiveContextCost as t };
748
-
749
- //# sourceMappingURL=cost-data-CCZUs1aJ.js.map