pantheon-opencode 1.6.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.
Files changed (169) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +268 -20
  5. package/README.pt-BR.md +34 -11
  6. package/bin/pantheon-init.mjs +301 -32
  7. package/package.json +13 -4
  8. package/plugin.json +1 -1
  9. package/prompts/README.md +58 -0
  10. package/prompts/debug-issue.prompt.md +46 -0
  11. package/prompts/dynamic/agora-generated.txt +38 -0
  12. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  13. package/prompts/focus.prompt.md +42 -0
  14. package/prompts/implement-feature.prompt.md +39 -0
  15. package/prompts/optimize-database.prompt.md +58 -0
  16. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  17. package/prompts/plan-architecture.prompt.md +59 -0
  18. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  19. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  20. package/prompts/semantic-summarize.md +50 -0
  21. package/prompts/sketch.prompt.md +91 -0
  22. package/prompts/subtask.prompt.md +131 -0
  23. package/pyproject.toml +1 -1
  24. package/scripts/build-agents-md.mjs +1 -1
  25. package/scripts/decision-router-budget.mjs +780 -0
  26. package/scripts/decision-router-v2-budget.mjs +218 -0
  27. package/scripts/decision-router-v2-egress.mjs +272 -0
  28. package/scripts/decision-router.mjs +758 -0
  29. package/scripts/docs-check-changelog.mjs +5 -3
  30. package/scripts/doctor.mjs +213 -45
  31. package/scripts/install/agents-md.mjs +2 -1
  32. package/scripts/install/component-selection.mjs +9 -4
  33. package/scripts/install/config-migration.mjs +344 -393
  34. package/scripts/install/config-paths.mjs +15 -0
  35. package/scripts/install/decision-layer-preview.mjs +376 -0
  36. package/scripts/install/decision-router-config.mjs +560 -0
  37. package/scripts/install/health-check.mjs +20 -11
  38. package/scripts/install/interactive.mjs +103 -14
  39. package/scripts/install/interrupt.mjs +4 -3
  40. package/scripts/install/mcp-permissions.mjs +164 -0
  41. package/scripts/install/migrate.mjs +123 -72
  42. package/scripts/install/opencode-version.mjs +31 -13
  43. package/scripts/install/opencode-wildcard.mjs +106 -0
  44. package/scripts/install/opencode.mjs +411 -184
  45. package/scripts/install/plan-artifact.mjs +12 -1
  46. package/scripts/install/plan.mjs +8 -1
  47. package/scripts/install/plugin.mjs +18 -1
  48. package/scripts/install/state.mjs +12 -0
  49. package/scripts/install/strings.mjs +22 -0
  50. package/scripts/install/v2-capabilities.mjs +5 -6
  51. package/scripts/install/venv.mjs +34 -17
  52. package/scripts/mcp_resources.py +11 -9
  53. package/scripts/package-evidence.mjs +1 -0
  54. package/scripts/release-notes.mjs +30 -7
  55. package/scripts/restore.mjs +22 -10
  56. package/scripts/sandbox-env.sh +174 -0
  57. package/scripts/setup-v2-config.mjs +1703 -0
  58. package/scripts/setup.mjs +415 -0
  59. package/scripts/sync-tui.mjs +9 -1
  60. package/scripts/test-opencode-v2-sandbox.sh +448 -157
  61. package/scripts/update-skills-lock.mjs +30 -0
  62. package/scripts/versioning.mjs +41 -5
  63. package/skills-lock.json +10 -10
  64. package/src/agents/aphrodite.md +11 -3
  65. package/src/agents/apollo.md +6 -0
  66. package/src/agents/athena.md +7 -1
  67. package/src/agents/demeter.md +6 -2
  68. package/src/agents/gaia.md +5 -0
  69. package/src/agents/hephaestus.md +7 -2
  70. package/src/agents/hermes.md +14 -13
  71. package/src/agents/iris.md +6 -2
  72. package/src/agents/mnemosyne.md +21 -50
  73. package/src/agents/nyx.md +6 -2
  74. package/src/agents/prometheus.md +5 -1
  75. package/src/agents/talos.md +10 -1
  76. package/src/agents/themis.md +5 -1
  77. package/src/agents/zeus.md +61 -65
  78. package/src/instructions/agent-return-format.instructions.md +1 -1
  79. package/src/instructions/memory-protocol.instructions.md +3 -3
  80. package/src/instructions/test-economy.instructions.md +6 -6
  81. package/src/mcp/eval_store.py +11 -4
  82. package/src/mcp/mcp_resources.py +11 -9
  83. package/src/mcp/memory_mcp.py +293 -150
  84. package/src/mcp/pantheon_vision.py +37 -36
  85. package/src/pantheon/cost-command.ts +30 -133
  86. package/src/pantheon/jev-decision-tool.ts +347 -0
  87. package/src/pantheon/jev-decisions.ts +625 -0
  88. package/src/pantheon/local-decision-agents.ts +170 -0
  89. package/src/pantheon/local-decision-budget.ts +1046 -0
  90. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  91. package/src/pantheon/local-decision-prompt.ts +256 -0
  92. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  93. package/src/pantheon/local-decision-router.ts +225 -0
  94. package/src/pantheon/local-decision-skills.ts +281 -0
  95. package/src/pantheon/local-decision-tool.ts +160 -0
  96. package/src/pantheon/local-decision-turn.ts +101 -0
  97. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  98. package/src/pantheon/local-orchestration.ts +322 -0
  99. package/src/pantheon/model-pricing.ts +1 -536
  100. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  101. package/src/pantheon/v2-decision-budget.ts +456 -0
  102. package/src/pantheon/v2-decision-contracts.ts +300 -0
  103. package/src/pantheon/v2-decision-egress.ts +203 -0
  104. package/src/pantheon/v2-decision-events.ts +180 -0
  105. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  106. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  107. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  108. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  109. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  110. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  111. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  112. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  113. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  114. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  115. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  116. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  117. package/src/pantheon/v2-decision-points.ts +242 -0
  118. package/src/pantheon/v2-decision-policy.ts +166 -0
  119. package/src/pantheon/v2-decision-premises.ts +146 -0
  120. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  121. package/src/pantheon/v2-decision-rank.ts +91 -0
  122. package/src/pantheon/v2-decision-registry.ts +391 -0
  123. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  124. package/src/pantheon/v2-decision-shadow.ts +123 -0
  125. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  126. package/src/pantheon/v2-decision-verify.ts +51 -0
  127. package/src/pantheon/v2-hook-engine.ts +307 -0
  128. package/src/pantheon/v2-native-decisions.ts +365 -0
  129. package/src/pantheon/v2-shell-hooks.ts +66 -2
  130. package/src/pantheon/v2-tools.ts +38 -15
  131. package/src/pantheon/v2-vision.ts +34 -29
  132. package/src/pantheon/vision.ts +43 -10
  133. package/src/plugin-v2.ts +449 -79
  134. package/src/plugin.ts +4 -0
  135. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  136. package/src/plugins/tui/dist/server-v2.d.ts +22 -0
  137. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  138. package/src/plugins/tui/dist/server-v2.js +26 -0
  139. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  140. package/src/plugins/tui/dist/tui-v2.d.ts +54 -51
  141. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  142. package/src/plugins/tui/dist/tui-v2.js +762 -529
  143. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  144. package/src/plugins/tui/dist/tui.js +1 -1
  145. package/src/plugins/tui/index-v2.ts +3 -6
  146. package/src/plugins/tui/package-lock.json +17 -2
  147. package/src/plugins/tui/package.json +6 -3
  148. package/src/plugins/tui/src/context-gauge.ts +59 -0
  149. package/src/plugins/tui/src/cost-data.ts +607 -0
  150. package/src/plugins/tui/src/index-v2.tsx +360 -242
  151. package/src/plugins/tui/src/model-pricing.ts +536 -0
  152. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  153. package/src/plugins/tui/src/server-v2.ts +21 -0
  154. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  155. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  156. package/src/plugins/tui/tsdown.config.ts +34 -5
  157. package/src/routing.yml +72 -13
  158. package/src/skills/README.md +4 -0
  159. package/src/skills/agent-coordination/SKILL.md +0 -3
  160. package/src/skills/artifact-management/SKILL.md +0 -3
  161. package/src/skills/auto-continue/SKILL.md +0 -3
  162. package/src/skills/code-review-checklist/SKILL.md +0 -3
  163. package/src/skills/context-compression/SKILL.md +0 -3
  164. package/src/skills/memory-bank/SKILL.md +6 -28
  165. package/src/skills/session-goal/SKILL.md +0 -3
  166. package/src/skills/simplify/SKILL.md +5 -4
  167. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  168. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  169. package/src/pantheon/memory-context.ts +0 -1017
@@ -15,7 +15,6 @@ import json
15
15
  import logging
16
16
  import mimetypes
17
17
  import os
18
- import re
19
18
  import sqlite3
20
19
  import struct
21
20
  import sys
@@ -71,13 +70,8 @@ OPENCODE_ENDPOINT = "https://opencode.ai/zen/v1/chat/completions"
71
70
  # elsewhere.
72
71
  SESSION_HEADER = "x-opencode-session"
73
72
  _ZEN_ENDPOINT_PREFIX = "https://opencode.ai/zen/"
74
- # A session id is an opaque OpenCode token. Only the characters real ids use
75
- # (`ses_...`) plus the separators existing callers already pass are accepted;
76
- # the length is bounded. Anything else — empty, whitespace, control characters,
77
- # quotes, CR/LF — is rejected instead of being copied into the header, where a
78
- # CRLF would split it and let a caller inject extra headers/requests.
79
- _SESSION_ID_MAX_LENGTH = 128
80
- _SESSION_ID_PATTERN = re.compile(r"[A-Za-z0-9._:-]+")
73
+ # Keep in sync with src/pantheon/session-guard.ts: OpenCode accepts IDs that
74
+ # start with "ses". Do not add a narrower local format or length constraint.
81
75
  _ALLOWED_MIME_TYPES = {"image/png", "image/jpeg", "image/webp", "image/gif"}
82
76
  _EXTENSION_MIME_TYPES = {
83
77
  ".png": "image/png",
@@ -297,22 +291,19 @@ def _is_zen_endpoint(endpoint: str) -> bool:
297
291
 
298
292
 
299
293
  def _validated_session_id(value: object) -> str | None:
300
- """Return a session id safe to send in the Zen header, or None.
294
+ """Return a host-valid session id, following the shared ``ses`` contract."""
295
+ return value if isinstance(value, str) and value.startswith("ses") else None
301
296
 
302
- The value arrives from a tool parameter the plugin forwards (a local MCP
303
- process is not handed a session id by the host), so it is untrusted input:
304
- only a trimmed, bounded, token-shaped value is accepted. An empty or
305
- whitespace-only string, a control character, a quote, or an embedded
306
- CR/LF yields None so the header is simply omitted — never copied verbatim.
307
- """
308
- if not isinstance(value, str):
309
- return None
310
- candidate = value.strip()
311
- if not candidate or len(candidate) > _SESSION_ID_MAX_LENGTH:
312
- return None
313
- if _SESSION_ID_PATTERN.fullmatch(candidate) is None:
314
- return None
315
- return candidate
297
+
298
+ def _require_session_id(value: object) -> str:
299
+ """Return a valid session id or fail before any Zen-bound work."""
300
+ session_id = _validated_session_id(value)
301
+ if session_id is None:
302
+ raise VisionError(
303
+ "A valid OpenCode session id is required for Zen Vision; "
304
+ "retry from an active OpenCode session."
305
+ )
306
+ return session_id
316
307
 
317
308
 
318
309
  def _strip_provider_prefix(model: str) -> str:
@@ -637,13 +628,11 @@ async def _gateway(
637
628
  ) -> str:
638
629
  """Send one multimodal request to the selected OpenCode gateway.
639
630
 
640
- ``session_id`` (when present and valid — see ``_validated_session_id``) is
641
- sent as the ``x-opencode-session`` header — and ONLY for a Zen endpoint,
642
- which rejects the request with HTTP 400 ``MissingSessionID`` otherwise. An
643
- unusable value (empty, whitespace, control characters, CR/LF, quotes) is
644
- dropped rather than copied into the header. It is never logged and never
645
- sent to a non-Zen host.
631
+ A valid ``session_id`` is required before auth lookup or POST. It is sent as
632
+ ``x-opencode-session`` only for a Zen endpoint, and is never logged or sent
633
+ to a non-Zen host.
646
634
  """
635
+ safe_session_id = _require_session_id(session_id)
647
636
  key, endpoint = _resolve_auth()
648
637
  if not key:
649
638
  # Missing credential is FATAL here (unlike the graceful describe/ocr
@@ -680,8 +669,7 @@ async def _gateway(
680
669
  "Authorization": f"Bearer {key}",
681
670
  "Content-Type": "application/json",
682
671
  }
683
- safe_session_id = _validated_session_id(session_id)
684
- if safe_session_id is not None and _is_zen_endpoint(endpoint):
672
+ if _is_zen_endpoint(endpoint):
685
673
  headers[SESSION_HEADER] = safe_session_id
686
674
  try:
687
675
  async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT_SECONDS) as client:
@@ -786,15 +774,21 @@ async def vision_describe(
786
774
  through the tool call because a local MCP process is not handed one by the
787
775
  host. It is sent only to a Zen endpoint and never logged.
788
776
  """
777
+ key, _endpoint = _resolve_auth()
778
+ session = None
779
+ if key:
780
+ try:
781
+ session = _require_session_id(session_id)
782
+ except Exception as exc:
783
+ return _error_message(exc)
789
784
  try:
790
785
  image = await _prepare_input(path)
791
786
  except Exception as exc:
792
787
  return _error_message(exc)
793
- key, _endpoint = _resolve_auth()
794
788
  if not key:
795
789
  return _local_vision_text(image)
796
790
  try:
797
- return await _gateway(image, prompt or _DESCRIBE_PROMPT, session_id=session_id)
791
+ return await _gateway(image, prompt or _DESCRIBE_PROMPT, session_id=session)
798
792
  except Exception as exc:
799
793
  return _error_message(exc)
800
794
 
@@ -807,15 +801,21 @@ async def vision_ocr(path: str, session_id: str | None = None) -> str:
807
801
  when no gateway credential is configured. ``session_id`` reaches the Zen
808
802
  gateway as the ``x-opencode-session`` header (see ``vision_describe``).
809
803
  """
804
+ key, _endpoint = _resolve_auth()
805
+ session = None
806
+ if key:
807
+ try:
808
+ session = _require_session_id(session_id)
809
+ except Exception as exc:
810
+ return _error_message(exc)
810
811
  try:
811
812
  image = await _prepare_input(path)
812
813
  except Exception as exc:
813
814
  return _error_message(exc)
814
- key, _endpoint = _resolve_auth()
815
815
  if not key:
816
816
  return _local_vision_text(image)
817
817
  try:
818
- return await _gateway(image, _OCR_PROMPT, session_id=session_id)
818
+ return await _gateway(image, _OCR_PROMPT, session_id=session)
819
819
  except Exception as exc:
820
820
  return _error_message(exc)
821
821
 
@@ -830,9 +830,10 @@ async def vision_analyze(path: str, session_id: str | None = None) -> str:
830
830
  (see ``vision_describe``).
831
831
  """
832
832
  try:
833
+ session = _require_session_id(session_id)
833
834
  image = await _prepare_input(path)
834
835
  content = await _gateway(
835
- image, _ANALYZE_PROMPT, structured=True, session_id=session_id
836
+ image, _ANALYZE_PROMPT, structured=True, session_id=session
836
837
  )
837
838
  parsed = _parse_json_object(content)
838
839
  if parsed is None:
@@ -37,15 +37,21 @@
37
37
  */
38
38
  import { execFile } from 'node:child_process'
39
39
  import { accessSync, constants, existsSync, statSync } from 'node:fs'
40
- import { homedir } from 'node:os'
41
40
  import { delimiter, dirname, join } from 'node:path'
42
41
  import { fileURLToPath } from 'node:url'
43
42
  import { z } from 'zod'
43
+ import type { CostSource, SqliteDatabase, SqliteModule } from '../plugins/tui/src/cost-data.ts'
44
+ import {
45
+ ledgerLabel,
46
+ numberOf,
47
+ priceTokens,
48
+ requestedVersion,
49
+ resolveCostDbPath,
50
+ resolveSources,
51
+ } from '../plugins/tui/src/cost-data.ts'
44
52
  import {
45
- computeModelCost,
46
53
  forceRefreshPricing,
47
54
  loadPricing,
48
- lookupModelPrice,
49
55
  type PricingOptions,
50
56
  type PricingSnapshot,
51
57
  type UnpricedReason,
@@ -53,6 +59,27 @@ import {
53
59
  import type { NativeTaskStatus } from './native-task-status.ts'
54
60
  import type { ToolContextLike } from './tool-context.ts'
55
61
 
62
+ export type {
63
+ ActiveContextCostEstimate,
64
+ ActiveContextCostInput,
65
+ CostSource,
66
+ OpenCodeVersion,
67
+ SqliteModule,
68
+ UsageHistoryBucket,
69
+ UsageHistoryModel,
70
+ UsageHistoryOptions,
71
+ UsageHistoryPeriod,
72
+ UsageHistoryPricing,
73
+ UsageHistoryResult,
74
+ UsagePricingStatus,
75
+ UsageTokenTotals,
76
+ } from '../plugins/tui/src/cost-data.ts'
77
+ export {
78
+ estimateActiveContextCost,
79
+ queryUsageHistory,
80
+ resolveCostDbPath,
81
+ } from '../plugins/tui/src/cost-data.ts'
82
+
56
83
  const __filename = fileURLToPath(import.meta.url)
57
84
  const __dirname = dirname(__filename)
58
85
 
@@ -120,26 +147,6 @@ export interface CostSessionScope {
120
147
  hierarchy: boolean
121
148
  }
122
149
 
123
- /**
124
- * Host table families that can carry a token ledger. A migrated database
125
- * carries both at once.
126
- */
127
- export type CostSource = 'message' | 'session_message'
128
-
129
- const COST_SOURCES: readonly CostSource[] = ['message', 'session_message']
130
-
131
- /**
132
- * Which table family each host generation stores its ledger in.
133
- *
134
- * Spelled out rather than comparing the literals: `'message' === 'v1'` is
135
- * false, so a filter written as `source === requested` narrows to nothing and
136
- * every version-pinned read fails.
137
- */
138
- const VERSION_SOURCES: Record<OpenCodeVersion, CostSource> = {
139
- v1: 'message',
140
- v2: 'session_message',
141
- }
142
-
143
150
  /** What the query actually found, so the report can describe its own coverage. */
144
151
  export interface CostCoverage {
145
152
  /** Table families that contributed rows. */
@@ -176,17 +183,6 @@ export interface CostCommandOptions {
176
183
  pricing?: PricingOptions
177
184
  }
178
185
 
179
- export type OpenCodeVersion = 'v1' | 'v2'
180
-
181
- interface SqliteDatabase {
182
- prepare(sql: string): { get(): unknown; all(...args: unknown[]): unknown[] }
183
- close(): void
184
- }
185
-
186
- export interface SqliteModule {
187
- DatabaseSync: new (path: string, options: { readOnly: boolean }) => SqliteDatabase
188
- }
189
-
190
186
  /** One cost tool: description + zod args shape + execute (delegation.ts shape). */
191
187
  export interface CostTool<Args extends z.ZodRawShape = typeof costArgs> {
192
188
  description: string
@@ -224,41 +220,6 @@ const costArgs = {
224
220
  /** Parsed arguments of the cost tool. */
225
221
  type CostArgs = z.infer<z.ZodObject<typeof costArgs>>
226
222
 
227
- /** The XDG state directory every real host installation writes its ledger to. */
228
- function defaultDbPath(): string {
229
- const xdg = process.env.XDG_DATA_HOME
230
- const dataHome = xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.local', 'share')
231
- return join(dataHome, 'opencode', 'opencode.db')
232
- }
233
-
234
- /** Read and validate the optional host-generation selector. */
235
- function requestedVersion(): OpenCodeVersion | undefined {
236
- const configured = process.env.PANTHEON_OPENCODE_VERSION
237
- if (configured === undefined) return undefined
238
- if (configured !== 'v1' && configured !== 'v2') {
239
- throw new Error(`invalid PANTHEON_OPENCODE_VERSION "${configured}"; expected "v1" or "v2"`)
240
- }
241
- return configured
242
- }
243
-
244
- /**
245
- * Resolve the database.
246
- *
247
- * Precedence: explicit option → PANTHEON_COST_DB → OPENCODE_DB → the XDG
248
- * default `opencode.db`. An invalid PANTHEON_OPENCODE_VERSION fails fast rather
249
- * than being silently ignored.
250
- *
251
- * There is deliberately NO per-version filename. Deriving one from the host
252
- * generation pointed the V2 report at `opencode-v2.db`, which exists only
253
- * because a sandbox sets OPENCODE_DB — hence OPENCODE_DB's place in this chain.
254
- */
255
- export function resolveCostDbPath(options?: CostCommandOptions): string {
256
- const explicit = options?.dbPath || process.env.PANTHEON_COST_DB || process.env.OPENCODE_DB
257
- if (explicit) return explicit
258
- requestedVersion()
259
- return defaultDbPath()
260
- }
261
-
262
223
  /**
263
224
  * First existing db path, or undefined. An EXPLICIT override shadows the
264
225
  * candidate list entirely (testability: a fake path must not fall through
@@ -270,42 +231,6 @@ function findExistingDb(override?: string): string | undefined {
270
231
  return existsSync(candidate) ? candidate : undefined
271
232
  }
272
233
 
273
- /**
274
- * Detect the ledger families by TABLE PRESENCE.
275
- *
276
- * Presence is the only reliable discriminator: a migrated database carries both
277
- * families, so pinning a schema-version constant would break whichever
278
- * population it excluded, and no manifest declares a supported host range.
279
- * PANTHEON_OPENCODE_VERSION only NARROWS an already-detected set — it never
280
- * chooses a file and never invents a family that is not there.
281
- */
282
- function resolveSources(db: SqliteDatabase, requested: OpenCodeVersion | undefined): CostSource[] {
283
- const present = new Set(
284
- (
285
- db
286
- .prepare(
287
- "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('message', 'session_message')",
288
- )
289
- .all() as Array<{ name?: unknown }>
290
- ).map((row) => String(row.name)),
291
- )
292
- const detected = COST_SOURCES.filter((source) => present.has(source))
293
- if (detected.length === 0) {
294
- throw new Error(
295
- 'incompatible opencode.db schema: neither the "message" nor the "session_message" table exists, so there is no token ledger to read',
296
- )
297
- }
298
- if (requested === undefined) return detected
299
- const wanted = VERSION_SOURCES[requested]
300
- const narrowed = detected.filter((source) => source === wanted)
301
- if (narrowed.length === 0) {
302
- throw new Error(
303
- `incompatible opencode.db schema: PANTHEON_OPENCODE_VERSION=${requested} selected no table family, but this database contains ${detected.join(' and ')}`,
304
- )
305
- }
306
- return narrowed
307
- }
308
-
309
234
  /**
310
235
  * Per-family aggregation, grouped finely enough to price and to attribute.
311
236
  *
@@ -538,12 +463,6 @@ const DATABASE_START_SQL: Record<CostSource, string> = {
538
463
 
539
464
  type Counters = { scanned?: unknown; windowStart?: unknown; assistantRows?: unknown }
540
465
 
541
- function numberOf(value: unknown): number | undefined {
542
- if (value === null || value === undefined) return undefined
543
- const parsed = Number(value)
544
- return Number.isFinite(parsed) ? parsed : undefined
545
- }
546
-
547
466
  function emptyCoverage(sources: CostSource[]): CostCoverage {
548
467
  return { sources, scanned: 0, assistantRows: 0 }
549
468
  }
@@ -588,28 +507,6 @@ interface SessionAccumulator {
588
507
  reason: UnpricedReason | undefined
589
508
  }
590
509
 
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
-
613
510
  /**
614
511
  * Read the token ledger of one database, read-only.
615
512
  *