pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.11

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 (145) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-gates.mjs +6 -82
  42. package/scripts/release-notes.mjs +30 -7
  43. package/scripts/restore.mjs +22 -10
  44. package/scripts/sync-tui.mjs +3 -3
  45. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  46. package/scripts/versioning.mjs +41 -5
  47. package/src/agents/aphrodite.md +6 -1
  48. package/src/agents/apollo.md +1 -0
  49. package/src/agents/athena.md +1 -0
  50. package/src/agents/demeter.md +1 -1
  51. package/src/agents/gaia.md +1 -0
  52. package/src/agents/hephaestus.md +1 -1
  53. package/src/agents/hermes.md +8 -10
  54. package/src/agents/iris.md +1 -1
  55. package/src/agents/mnemosyne.md +1 -0
  56. package/src/agents/nyx.md +1 -1
  57. package/src/agents/prometheus.md +1 -1
  58. package/src/agents/talos.md +6 -1
  59. package/src/agents/themis.md +1 -1
  60. package/src/agents/zeus.md +52 -62
  61. package/src/mcp/eval_store.py +11 -4
  62. package/src/mcp/mcp_resources.py +11 -9
  63. package/src/mcp/memory_mcp.py +293 -150
  64. package/src/pantheon/cost-command.ts +30 -133
  65. package/src/pantheon/jev-decision-tool.ts +359 -0
  66. package/src/pantheon/jev-decisions.ts +625 -0
  67. package/src/pantheon/local-decision-agents.ts +170 -0
  68. package/src/pantheon/local-decision-budget.ts +1046 -0
  69. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  70. package/src/pantheon/local-decision-prompt.ts +256 -0
  71. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  72. package/src/pantheon/local-decision-router.ts +225 -0
  73. package/src/pantheon/local-decision-skills.ts +281 -0
  74. package/src/pantheon/local-decision-tool.ts +160 -0
  75. package/src/pantheon/local-decision-turn.ts +101 -0
  76. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  77. package/src/pantheon/local-orchestration.ts +322 -0
  78. package/src/pantheon/model-pricing.ts +1 -536
  79. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  80. package/src/pantheon/v2-decision-budget.ts +456 -0
  81. package/src/pantheon/v2-decision-contracts.ts +300 -0
  82. package/src/pantheon/v2-decision-egress.ts +203 -0
  83. package/src/pantheon/v2-decision-events.ts +180 -0
  84. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  85. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  86. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  87. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  88. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  89. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  90. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  91. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  92. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  93. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  94. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  95. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  96. package/src/pantheon/v2-decision-points.ts +242 -0
  97. package/src/pantheon/v2-decision-policy.ts +166 -0
  98. package/src/pantheon/v2-decision-premises.ts +146 -0
  99. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  100. package/src/pantheon/v2-decision-rank.ts +91 -0
  101. package/src/pantheon/v2-decision-registry.ts +391 -0
  102. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  103. package/src/pantheon/v2-decision-shadow.ts +123 -0
  104. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  105. package/src/pantheon/v2-decision-verify.ts +51 -0
  106. package/src/pantheon/v2-hook-engine.ts +307 -0
  107. package/src/pantheon/v2-native-decisions.ts +365 -0
  108. package/src/pantheon/v2-shell-hooks.ts +66 -2
  109. package/src/pantheon/v2-tools.ts +38 -15
  110. package/src/plugin-v2.ts +419 -26
  111. package/src/plugin.ts +4 -0
  112. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  113. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  114. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  115. package/src/plugins/tui/dist/server-v2.js +19 -666
  116. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  117. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  119. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  121. package/src/plugins/tui/dist/tui.js +1 -1
  122. package/src/plugins/tui/package-lock.json +17 -2
  123. package/src/plugins/tui/package.json +4 -2
  124. package/src/plugins/tui/src/cost-data.ts +607 -0
  125. package/src/plugins/tui/src/index-v2.tsx +213 -54
  126. package/src/plugins/tui/src/model-pricing.ts +536 -0
  127. package/src/plugins/tui/src/server-v2.ts +18 -838
  128. package/src/plugins/tui/tsdown.config.ts +28 -6
  129. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  130. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  131. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  132. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  133. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  134. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  135. package/src/plugins/tui/dist/quota-cli.js +0 -184
  136. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  138. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  139. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  140. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  141. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  142. package/src/plugins/tui/src/quota-cli.ts +0 -237
  143. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  144. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  145. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -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
  *
@@ -0,0 +1,359 @@
1
+ /**
2
+ * The explicit V2 tool surface for native Jev Decisions.
3
+ *
4
+ * This is the one production call site for the native Decisions scaffold. The
5
+ * surface is an explicit tool invocation, which resolves the hook path's
6
+ * correlation problem by construction: the model calls the tool during its own
7
+ * turn, so there is no queued/steer ambiguity to prove. Egress still passes the
8
+ * full gate chain before the host's `experimental.generate.decisions` is ever
9
+ * invoked — user-level config (`enabled`, `egress_consent`), exactly one
10
+ * cap-valid native candidate from the budget ledger, the host permission
11
+ * kill-switch on the `decision.egress` action, and the bounded request
12
+ * preparer. Transport is the host's own provider layer: this module never
13
+ * touches fetch, endpoints, or credentials.
14
+ *
15
+ * Settlement follows the fetch runner's fail-closed contract: reserve before
16
+ * the call, reconcile from the host-reported cost after it, and leave the
17
+ * reservation pending (budget held for the period) when no evidence can be
18
+ * minted. A failed or unreconciled call is a refusal, never a retry.
19
+ */
20
+ import { readUserDecisionRouterConfig } from '../../scripts/install/decision-router-config.mjs'
21
+ import {
22
+ consumeJevDecisionResult,
23
+ isJevDecisionPreset,
24
+ type JevDecisionCatalogEntry,
25
+ type JevHostSkill,
26
+ type NativeJevRouteFailure,
27
+ prepareJevDecisionRequest,
28
+ prepareJevPresetRequest,
29
+ resolveNativeJevRoute,
30
+ } from './jev-decisions.ts'
31
+ import {
32
+ openLocalDecisionBudgetLedger,
33
+ resolveLocalDecisionBudgetDbPath,
34
+ } from './local-decision-budget.ts'
35
+ import {
36
+ assertDecisionEgressPermission,
37
+ buildDecisionEgressRequest,
38
+ } from './local-decision-egress-gate.ts'
39
+ import { verifyNativeUsageForReservation } from './local-decision-usage-evidence.internal.ts'
40
+ import type { NativeDecisionRequest } from './v2-native-decisions.ts'
41
+ import type { V2ToolDef } from './v2-tools.ts'
42
+
43
+ export interface V2JevDecisionRuntime {
44
+ /** Raw host model catalog (`ctx.model.list`); may resolve to anything. */
45
+ readonly listModels: () => Promise<unknown>
46
+ /** The host's native Decisions API (`ctx.experimental.generate.decisions`). */
47
+ readonly decide: (request: NativeDecisionRequest) => Promise<unknown>
48
+ /**
49
+ * Raw host skill registry (`ctx.skill.list()`); optional. Its entries extend
50
+ * the skills preset so installed Agent Skills become decidable.
51
+ */
52
+ readonly listSkills?: () => Promise<unknown>
53
+ /** Host permission kill-switch (`ctx.permission.assert`), when present. */
54
+ readonly permissionAssert?: (input: Record<string, unknown>) => Promise<unknown>
55
+ }
56
+
57
+ /** Logical permission resource: no endpoint URL exists on the native route. */
58
+ export function nativeJevPermissionResource(providerID: string, id: string): string {
59
+ return `pantheon-native-decisions://${providerID}/${id}`
60
+ }
61
+
62
+ export type JevDecisionRunFailure =
63
+ | 'CALLER_NOT_ZEUS'
64
+ | 'CONTEXT_UNAVAILABLE'
65
+ | 'CONFIG_UNAVAILABLE'
66
+ | 'DISABLED'
67
+ | 'CONSENT_MISSING'
68
+ | 'CATALOG_UNAVAILABLE'
69
+ | 'CAP_OR_PERIOD_DENIED'
70
+ | NativeJevRouteFailure
71
+ | 'PERMISSION_UNAVAILABLE'
72
+ | 'PERMISSION_DENIED'
73
+ | 'STATE_INVALID'
74
+ | 'QUESTIONS_INVALID'
75
+ | 'PRESET_INVALID'
76
+ | 'RESERVATION_DENIED'
77
+ | 'DECISION_CALL_FAILED'
78
+ | 'USAGE_UNRECONCILED'
79
+
80
+ interface JevToolContext {
81
+ sessionID?: unknown
82
+ messageID?: unknown
83
+ agent?: unknown
84
+ }
85
+
86
+ function refusal(reasonCode: JevDecisionRunFailure): string {
87
+ return JSON.stringify({ advisory: false, effect: 'none', reasonCode })
88
+ }
89
+
90
+ /**
91
+ * Refusal with the error CLASS only (`TypeError`, `RangeError`, …). The
92
+ * message never crosses into the chat: it can carry paths, config or provider
93
+ * detail, and the class alone already separates a detached-call failure from
94
+ * a host-side data failure.
95
+ */
96
+ function refusalDetail(reasonCode: JevDecisionRunFailure, err: unknown): string {
97
+ const detail = err instanceof Error ? err.name : 'UnknownFailure'
98
+ return JSON.stringify({ advisory: false, effect: 'none', reasonCode, detail })
99
+ }
100
+
101
+ function isNonBlankString(value: unknown): value is string {
102
+ return typeof value === 'string' && value.trim().length > 0
103
+ }
104
+
105
+ /**
106
+ * Read the host's installed skills for the stacking preset. Anything that is
107
+ * not a plain {id, description?} record is skipped; a missing or hostile
108
+ * registry degrades to the catalog-only preset. Reading the registry applies
109
+ * no trust: installation already was the user's manual, reviewed act.
110
+ */
111
+ async function readHostSkills(runtime: V2JevDecisionRuntime): Promise<JevHostSkill[] | undefined> {
112
+ if (typeof runtime.listSkills !== 'function') return undefined
113
+ let raw: unknown
114
+ try {
115
+ raw = await runtime.listSkills()
116
+ } catch {
117
+ return undefined
118
+ }
119
+ if (!Array.isArray(raw)) return undefined
120
+ const skills: JevHostSkill[] = []
121
+ for (const entry of raw) {
122
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue
123
+ const record = entry as { id?: unknown; description?: unknown }
124
+ if (typeof record.id !== 'string' || record.id.length === 0) continue
125
+ skills.push({
126
+ id: record.id,
127
+ ...(typeof record.description === 'string' && record.description.length > 0
128
+ ? { description: record.description }
129
+ : {}),
130
+ })
131
+ }
132
+ return skills
133
+ }
134
+
135
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
136
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
137
+ ? (value as Record<string, unknown>)
138
+ : undefined
139
+ }
140
+
141
+ async function readCatalog(runtime: V2JevDecisionRuntime): Promise<JevDecisionCatalogEntry[]> {
142
+ // The 2.2.5 host wraps the catalog in a page object ({ data: [...] }); the
143
+ // vision surface already tolerates both shapes (modelList in v2-vision.ts).
144
+ // Requiring a bare array here turned every real session into
145
+ // CATALOG_UNAVAILABLE (field evidence: detail TypeError under beta.10 with
146
+ // the receiver binding already in place).
147
+ const raw = await runtime.listModels()
148
+ const candidates = Array.isArray(raw) ? raw : (asRecord(raw)?.data ?? asRecord(raw)?.models)
149
+ if (!Array.isArray(candidates)) throw new TypeError('Model catalog is not a list')
150
+ const entries: JevDecisionCatalogEntry[] = []
151
+ for (const model of candidates) {
152
+ if (model === null || typeof model !== 'object' || Array.isArray(model)) continue
153
+ const record = model as Record<string, unknown>
154
+ if (!isNonBlankString(record.providerID) || !isNonBlankString(record.id)) continue
155
+ if (typeof record.type !== 'string') continue
156
+ entries.push({
157
+ providerID: record.providerID,
158
+ id: record.id,
159
+ type: record.type,
160
+ } as JevDecisionCatalogEntry)
161
+ }
162
+ return entries
163
+ }
164
+
165
+ /**
166
+ * Run one explicit, gate-checked native Jev decision. Every failure path
167
+ * returns a bounded refusal JSON; the only caller-visible success output is
168
+ * the validated advice with `effect: 'none'`.
169
+ */
170
+ export async function runJevDecision(
171
+ input: unknown,
172
+ toolContext: unknown,
173
+ runtime: V2JevDecisionRuntime,
174
+ ): Promise<string> {
175
+ const context =
176
+ toolContext !== null && typeof toolContext === 'object' && !Array.isArray(toolContext)
177
+ ? (toolContext as JevToolContext)
178
+ : undefined
179
+ if (context?.agent !== 'zeus') return refusal('CALLER_NOT_ZEUS')
180
+ const sessionID = context?.sessionID
181
+ const messageID = context?.messageID
182
+ if (!isNonBlankString(sessionID) || !isNonBlankString(messageID)) {
183
+ return refusal('CONTEXT_UNAVAILABLE')
184
+ }
185
+
186
+ let config: ReturnType<typeof readUserDecisionRouterConfig>
187
+ try {
188
+ config = readUserDecisionRouterConfig()
189
+ } catch {
190
+ return refusal('CONFIG_UNAVAILABLE')
191
+ }
192
+ if (!config.enabled) return refusal('DISABLED')
193
+ if (!config.egress_consent) return refusal('CONSENT_MISSING')
194
+
195
+ let catalog: JevDecisionCatalogEntry[]
196
+ try {
197
+ catalog = await readCatalog(runtime)
198
+ } catch (err) {
199
+ return refusalDetail('CATALOG_UNAVAILABLE', err)
200
+ }
201
+
202
+ const ledger = openLocalDecisionBudgetLedger({ dbPath: resolveLocalDecisionBudgetDbPath() })
203
+ try {
204
+ const selection = resolveNativeJevRoute(
205
+ config,
206
+ catalog,
207
+ (provider, model) => ledger.canReserve(provider, model).status === 'eligible',
208
+ )
209
+ if (!selection.ok) return refusal(selection.reasonCode)
210
+
211
+ if (typeof runtime.permissionAssert !== 'function') return refusal('PERMISSION_UNAVAILABLE')
212
+ const assertion = await assertDecisionEgressPermission(
213
+ runtime.permissionAssert,
214
+ buildDecisionEgressRequest({
215
+ sessionID,
216
+ messageID,
217
+ endpoint: nativeJevPermissionResource(
218
+ selection.selection.route.model.providerID,
219
+ selection.selection.route.model.id,
220
+ ),
221
+ agent: 'zeus',
222
+ }),
223
+ )
224
+ if (assertion === 'deny') return refusal('PERMISSION_DENIED')
225
+
226
+ const requested = (input ?? {}) as { mode?: unknown; questions?: unknown }
227
+ const prepared =
228
+ requested.mode === undefined
229
+ ? prepareJevDecisionRequest(selection.selection.route, input ?? {})
230
+ : isJevDecisionPreset(requested.mode)
231
+ ? prepareJevPresetRequest(
232
+ selection.selection.route,
233
+ requested.mode,
234
+ input ?? {},
235
+ requested.mode === 'skills' ? await readHostSkills(runtime) : undefined,
236
+ )
237
+ : { ok: false as const, reasonCode: 'PRESET_INVALID' as const }
238
+ if (!prepared.ok) return refusal(prepared.reasonCode)
239
+
240
+ const reservation = ledger.reserve(
241
+ selection.selection.accountingProvider,
242
+ selection.selection.model,
243
+ )
244
+ if (reservation.status !== 'reserved') return refusal('RESERVATION_DENIED')
245
+
246
+ let response: unknown
247
+ try {
248
+ response = await runtime.decide(prepared.request)
249
+ } catch (err) {
250
+ return refusalDetail('DECISION_CALL_FAILED', err)
251
+ }
252
+
253
+ const evidence = verifyNativeUsageForReservation(
254
+ {
255
+ reservationId: reservation.reservationId,
256
+ provider: selection.selection.accountingProvider,
257
+ model: selection.selection.model,
258
+ period: reservation.period,
259
+ },
260
+ response,
261
+ )
262
+ if (evidence === null) return refusal('USAGE_UNRECONCILED')
263
+ const reconciliation = ledger.reconcileVerified(reservation.reservationId, evidence)
264
+ if (reconciliation.status !== 'reconciled') return refusal('USAGE_UNRECONCILED')
265
+
266
+ const advice = consumeJevDecisionResult(response, prepared.request)
267
+ return JSON.stringify({
268
+ advisory: true,
269
+ effect: 'none',
270
+ reason: 'JEV_DECISION',
271
+ route: {
272
+ providerID: selection.selection.route.model.providerID,
273
+ id: selection.selection.route.model.id,
274
+ billing: selection.selection.route.billing,
275
+ },
276
+ ...(requested.mode === undefined ? {} : { preset: requested.mode }),
277
+ answers: advice.answers,
278
+ missing: advice.missing,
279
+ usage: { costUsd: advice.costUsd, tokens: advice.tokens },
280
+ frozen: reconciliation.frozen,
281
+ })
282
+ } finally {
283
+ ledger.close()
284
+ }
285
+ }
286
+
287
+ const TOOL_DESCRIPTION =
288
+ 'Zeus-only advisory typed decisions via the host native Jev route (OpenCode Console or a ' +
289
+ 'configured decision model). Two ways to ask: pass `mode: "skills"` to stack skills for the ' +
290
+ 'state text (local prefilter shortlist, catalog fallback, plus every skill installed in the ' +
291
+ 'host), `mode: "delegation"` to pick ' +
292
+ 'a specialist, or pass explicit typed `questions` (choice, score, predicate). Returns ' +
293
+ 'probabilistic answers with confidence. Requires decision-router egress consent and budget ' +
294
+ 'caps; asks host permission first. It never dispatches agents, runs skills, executes tools, ' +
295
+ 'or alters permissions — results are advisory only.'
296
+
297
+ const questionSchema = {
298
+ type: 'object',
299
+ additionalProperties: false,
300
+ required: ['type', 'name', 'instructions'],
301
+ properties: {
302
+ type: { type: 'string', enum: ['choice', 'score', 'predicate'] },
303
+ name: { type: 'string', minLength: 1, maxLength: 64 },
304
+ instructions: { type: 'string', minLength: 1, maxLength: 2000 },
305
+ choices: {
306
+ type: 'array',
307
+ minItems: 2,
308
+ maxItems: 16,
309
+ items: {
310
+ type: 'object',
311
+ additionalProperties: false,
312
+ required: ['value'],
313
+ properties: {
314
+ value: { type: 'string', minLength: 1, maxLength: 64 },
315
+ description: { type: 'string', minLength: 1, maxLength: 500 },
316
+ },
317
+ },
318
+ },
319
+ levels: {
320
+ type: 'array',
321
+ minItems: 2,
322
+ maxItems: 10,
323
+ items: {
324
+ type: 'object',
325
+ additionalProperties: false,
326
+ required: ['label'],
327
+ properties: {
328
+ label: { type: 'string', minLength: 1, maxLength: 64 },
329
+ description: { type: 'string', minLength: 1, maxLength: 500 },
330
+ },
331
+ },
332
+ },
333
+ },
334
+ }
335
+
336
+ const JEV_INPUT_SCHEMA: Record<string, unknown> = {
337
+ type: 'object',
338
+ additionalProperties: false,
339
+ required: ['schemaVersion', 'state'],
340
+ properties: {
341
+ schemaVersion: { type: 'integer', const: 1 },
342
+ state: { type: 'string', minLength: 1, maxLength: 12_000 },
343
+ mode: { type: 'string', enum: ['skills', 'delegation'] },
344
+ questions: { type: 'array', minItems: 1, maxItems: 4, items: questionSchema },
345
+ },
346
+ }
347
+
348
+ /** Create the V2 tool definition; registration is the caller's decision. */
349
+ export function createV2JevDecisionDefinition(runtime: V2JevDecisionRuntime): V2ToolDef {
350
+ return {
351
+ name: 'pantheon_jev_decide',
352
+ description: TOOL_DESCRIPTION,
353
+ input: JEV_INPUT_SCHEMA,
354
+ output: {},
355
+ execute: async (input: Record<string, unknown>, context: unknown) => ({
356
+ output: await runJevDecision(input, context, runtime),
357
+ }),
358
+ }
359
+ }