pantheon-opencode 1.6.2-beta.14 → 1.6.2-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -10,6 +10,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
10
10
  <!-- Add new changes here. Running `node scripts/versioning.mjs apply` will
11
11
  move this section to a versioned entry and reset the template below. -->
12
12
 
13
+ ## [v1.6.2-beta.16] - 2026-11-03
14
+
15
+ ### Added
16
+
17
+ - **hooks** — J1 risk-score advisory gate (shadow): when `PANTHEON_J1_RISK_SCORE` is on, exfil-capable tool calls get one Jev risk-score + intent-predicate observation through the same gate chain as `pantheon_jev_decide` (consent, budget caps, `decision.egress` permission). Shadow only — the verdict is always observed, never enforced; nothing blocks or delays (2s abandon, fail-open on every failure mode). The request carries zero user content: tool name token, scope class, input hash only. Default off.
18
+
19
+ ## [v1.6.2-beta.15] - 2026-11-03
20
+
21
+ ### Added
22
+
23
+ - **routing** — `decision-router setup-model typesafe-jev/...` now provisions the TypeSafe host provider entry itself (the same additive `providers.typesafe-ai` merge the installer's `--decision-model` path performs), so the TypeSafe direct route is one command plus your own sign-in.
24
+ - **routing** — `doctor` checks are route-aware: the Console routes pass as host-native without any catalog probe (decision models are not chat models and never appear in `opencode models`), and the TypeSafe route is verified against the provider entry with a provisioning fix hint.
25
+
13
26
  ## [v1.6.2-beta.14] - 2026-11-03
14
27
 
15
28
  ### Fixed
package/README.md CHANGED
@@ -212,7 +212,13 @@ credentials cannot activate it. Native child-session dispatch remains separate.
212
212
  The one native egress surface is the Zeus-only `pantheon_jev_decide` tool,
213
213
  available on hosts that expose the V2.2.5 native Decisions API; its full gate
214
214
  chain, routes, and settlement rules are documented once in
215
- [V2 native Decisions](docs/reference/native-decisions.md).
215
+ [V2 native Decisions](docs/reference/native-decisions.md). An opt-in second
216
+ consumer of that chain, the J1 risk-score shadow gate, fires one bounded
217
+ native decision per write/execute tool call behind `PANTHEON_J1_RISK_SCORE`
218
+ (off by default, zero overhead when off): the request carries no user content
219
+ (tool name token, scope class, input sha256 only), every failure mode skips
220
+ silently with a reason token, and the shadow record is the whole effect — it
221
+ never blocks, asks, or narrows a permission.
216
222
 
217
223
  The installer may retain a legacy target-specific preference; it does not control
218
224
  runtime routing. `npx pantheon-opencode decision-router ...` manages stored
@@ -26,6 +26,7 @@ import { fileURLToPath } from 'node:url'
26
26
  import { configure as configureUi, endGaugeLine, tag } from '../scripts/install/cli-ui.mjs'
27
27
  import { resolveComponentSelection } from '../scripts/install/component-selection.mjs'
28
28
  import { resolveGlobalConfigDirectory } from '../scripts/install/config-paths.mjs'
29
+ import { provisionTypesafeHostProvider } from '../scripts/install/decision-router-config.mjs'
29
30
  import { resolveInstallExitCode } from '../scripts/install/exit-codes.mjs'
30
31
  import { createInterruptHandler } from '../scripts/install/interrupt.mjs'
31
32
  import { parseOpenCodeVersion } from '../scripts/install/opencode-version.mjs'
@@ -68,40 +69,13 @@ function readVersion() {
68
69
  /**
69
70
  * Merge (never overwrite) the TypeSafe decision-model entry into the user's
70
71
  * OpenCode config, so choosing the TypeSafe route in the wizard needs only the
71
- * user's own sign-in afterwards. The merge is additive: existing provider
72
- * entries and an existing jev-1.14.0 model are preserved. Returns true, or a
73
- * short failure reason for the installer to print.
72
+ * user's own sign-in afterwards. Delegates to the shared installer module —
73
+ * the same provisioner `decision-router setup-model typesafe-jev/...` uses.
74
+ * Returns true, or a short failure reason for the installer to print.
74
75
  */
75
76
  function provisionTypesafeProvider() {
76
- const xdg = process.env.XDG_CONFIG_HOME
77
- const home = process.env.HOME
78
- const base = xdg && xdg.startsWith('/') ? xdg : `${home ?? '~'}/.config`
79
- const candidates = [`${base}/opencode/opencode.json`]
80
- if (home) candidates.push(`${home}/.config/opencode/opencode.json`)
81
- const configPath = candidates.find((candidate) => fs.existsSync(candidate))
82
- if (configPath === undefined) return 'opencode.json not found'
83
- let data
84
- try {
85
- data = JSON.parse(fs.readFileSync(configPath, 'utf8'))
86
- } catch {
87
- return 'opencode.json is not plain JSON (comments?)'
88
- }
89
- data.providers ??= {}
90
- data.providers['typesafe-ai'] ??= {}
91
- data.providers['typesafe-ai'].models ??= {}
92
- if (data.providers['typesafe-ai'].models['jev-1.14.0'] === undefined) {
93
- data.providers['typesafe-ai'].models['jev-1.14.0'] = {
94
- name: 'Jev (TypeSafe direct)',
95
- modelID: 'jev-latest',
96
- type: 'decision',
97
- }
98
- }
99
- try {
100
- fs.writeFileSync(configPath, `${JSON.stringify(data, null, 2)}\n`)
101
- return true
102
- } catch (error) {
103
- return String(error instanceof Error ? error.message : error)
104
- }
77
+ const result = provisionTypesafeHostProvider({ env: process.env })
78
+ return result.ok ? true : result.reason
105
79
  }
106
80
 
107
81
  /** Value of a repeatable installer flag from the raw argv, or undefined. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pantheon-opencode",
3
- "version": "1.6.2-beta.14",
3
+ "version": "1.6.2-beta.16",
4
4
  "description": "Multi-agent orchestration for OpenCode — 14 specialized agents, TDD, Themis review gates.",
5
5
  "type": "module",
6
6
  "workspaces": [
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pantheon",
3
3
  "publisher": "ils15",
4
- "version": "1.6.2-beta.14",
4
+ "version": "1.6.2-beta.16",
5
5
  "displayName": "Pantheon",
6
6
  "description": "Conductor-Delegate orchestration platform with 14 specialized agents, 20 skills, and OpenCode support.",
7
7
  "agents": "./src/agents",
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.backends._legacy:_Backend"
4
4
 
5
5
  [project]
6
6
  name = "pantheon"
7
- version = "1.6.2-beta.14"
7
+ version = "1.6.2-beta.16"
8
8
  description = "Multi-agent orchestration framework"
9
9
  requires-python = ">=3.11"
10
10
  # Python sources under src/mcp/ import fastmcp/pydantic at runtime, but those
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { spawnSync } from 'node:child_process'
3
2
  import { existsSync } from 'node:fs'
4
3
  import { pathToFileURL } from 'node:url'
5
4
  // Prebuilt bundles: Node refuses to strip TypeScript types under node_modules,
@@ -32,6 +31,8 @@ import {
32
31
  DECISION_PROVIDER_BUDGET_MAPPING,
33
32
  DECISION_ROUTER_MODELS,
34
33
  diffDecisionRouterSurfaces,
34
+ inspectTypesafeHostProvider,
35
+ provisionTypesafeHostProvider,
35
36
  readUserDecisionRouterConfig,
36
37
  resolveUserDecisionRouterConfigPath,
37
38
  updateUserDecisionRouterConfig,
@@ -336,6 +337,23 @@ export async function runDecisionRouterCommand(
336
337
  noConsent ? 'Egress consent NOT recorded (--no-consent).' : 'Egress consent recorded: yes.',
337
338
  )
338
339
 
340
+ // The TypeSafe route needs a host-side provider entry the decisions API
341
+ // can resolve; the Console routes are host-native and need none. The
342
+ // merge is additive and idempotent; a failure is a printed warning (the
343
+ // decision config stays valid — the call fails at the host until the
344
+ // entry exists).
345
+ if (provider === 'typesafe-jev') {
346
+ const provision = provisionTypesafeHostProvider({ env })
347
+ if (provision.ok) {
348
+ stdout(
349
+ `TypeSafe provider entry merged into ${provision.path} (models.typesafe-ai, type "decision"). ` +
350
+ 'Sign in with `opencode auth login` (TypeSafe) or /connect.',
351
+ )
352
+ } else {
353
+ stdout(`⚠ TypeSafe provider entry NOT merged: ${provision.reason}`)
354
+ }
355
+ }
356
+
339
357
  const ledger = openLedger(env)
340
358
  try {
341
359
  ledger.configureUserCaps({
@@ -468,25 +486,27 @@ export async function runDecisionRouterCommand(
468
486
  ? { provider: egress.provider, model: egress.candidate.model }
469
487
  : null
470
488
  if (target !== null) {
471
- const probe = probeHostCatalog(env)
472
- const hostProvider = target.provider === 'typesafe-jev' ? 'typesafe-ai' : 'opencode'
473
- if (probe.ok) {
474
- const exact = probe.models.has(`${hostProvider}/${target.model}`)
475
- const loose = probe.models.has(target.model)
476
- if (exact || loose) {
477
- pass('host-catalog', `${hostProvider}/${target.model} listed by \`opencode models\``)
489
+ // Route-aware checks, not a catalog probe: decision models are not chat
490
+ // models and never appear in `opencode models` (field evidence 2.2.5:
491
+ // 561 entries, 0 jev, while the decisions API answers the same ref).
492
+ if (target.provider === 'typesafe-jev') {
493
+ const hostProvider = inspectTypesafeHostProvider({ env })
494
+ if (hostProvider.present) {
495
+ pass(
496
+ 'native-route',
497
+ `typesafe-ai provider entry present (${hostProvider.path}); credential via \`opencode auth login\` (TypeSafe) or /connect`,
498
+ )
478
499
  } else {
479
- warn(
480
- 'host-catalog',
481
- `${hostProvider}/${target.model} not in the flat models list`,
482
- 'the flat list can omit decision-typed models; if a call refuses with ROUTE_UNRESOLVED, add a custom provider entry with type: "decision" (see docs/reference/native-decisions.md) or pick a listed decision model',
500
+ fail(
501
+ 'native-route',
502
+ `opencode.json has no providers.typesafe-ai entry (${hostProvider.path})`,
503
+ 'decision-router setup-model typesafe-jev/jev-1.14.0 merges it (type: "decision")',
483
504
  )
484
505
  }
485
506
  } else {
486
- warn(
487
- 'host-catalog',
488
- `could not probe: ${probe.reason}`,
489
- 'run `opencode models` manually; slow plugin activation is the usual cause',
507
+ pass(
508
+ 'native-route',
509
+ 'host-native opencode route; decision models are not listed in the chat catalog by design',
490
510
  )
491
511
  }
492
512
  }
@@ -503,41 +523,6 @@ export async function runDecisionRouterCommand(
503
523
  throw new DecisionRouterUsageError(USAGE)
504
524
  }
505
525
 
506
- /** Spawn-sync timeout floor so a wedged host cannot stall the doctor. */
507
- const HOST_PROBE_TIMEOUT_MS = 30_000
508
-
509
- /**
510
- * Best-effort host catalog probe for the doctor. Returns the set of
511
- * `provider/model` (and bare model ids, for exact-id matching) the host
512
- * reports, or the reason the probe failed. Never writes anything.
513
- */
514
- function probeHostCatalog(env) {
515
- let result
516
- try {
517
- result = spawnSync('opencode', ['models'], {
518
- encoding: 'utf8',
519
- timeout: HOST_PROBE_TIMEOUT_MS,
520
- env,
521
- })
522
- } catch (error) {
523
- return { ok: false, reason: String(error?.message ?? error) }
524
- }
525
- if (result.error) return { ok: false, reason: String(result.error.message ?? result.error) }
526
- if (result.status !== 0) {
527
- const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim()
528
- return { ok: false, reason: output.slice(0, 120) || `exit ${result.status}` }
529
- }
530
- const models = new Set()
531
- for (const line of `${result.stdout ?? ''}`.split(/\r?\n/)) {
532
- const id = line.trim()
533
- if (!id) continue
534
- models.add(id)
535
- const slash = id.indexOf('/')
536
- if (slash > 0) models.add(id.slice(slash + 1))
537
- }
538
- return { ok: true, models }
539
- }
540
-
541
526
  /** Cap- and period-eligible candidates, read-only, from the separated surfaces. */
542
527
  function capEligibleCandidates(config, inspection, wallPeriod) {
543
528
  if (inspection.caps === null) return []
@@ -1,4 +1,4 @@
1
- import { chmodSync, lstatSync, mkdirSync, readFileSync } from 'node:fs'
1
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
2
  import { homedir } from 'node:os'
3
3
  import { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
4
4
  import { assertNoSymlinkAncestors, writeFileAtomically } from './verify.mjs'
@@ -558,3 +558,69 @@ function assertTrustedDirectoryChain(directory) {
558
558
  }
559
559
  }
560
560
  }
561
+
562
+ /** Host config file the TypeSafe provisioner merges into. */
563
+ function resolveHostOpenCodeConfigPath(env) {
564
+ const xdg = env.XDG_CONFIG_HOME
565
+ const home = env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir()
566
+ const root = xdg && isAbsolute(xdg) ? xdg : join(home, '.config')
567
+ return resolve(root, 'opencode', 'opencode.json')
568
+ }
569
+
570
+ /**
571
+ * Additively merge the TypeSafe decision provider entry into the user's host
572
+ * `opencode.json` (`providers.typesafe-ai.models["jev-1.14.0"]`, type
573
+ * "decision"). Existing provider entries and an existing model entry are
574
+ * preserved. Read-only on the decision-router config; the merge is the one
575
+ * write.
576
+ * @param {{ env?: Record<string, string | undefined> }} [options]
577
+ * @returns {{ ok: true, path: string } | { ok: false, reason: string }}
578
+ */
579
+ export function provisionTypesafeHostProvider({ env = process.env } = {}) {
580
+ const configPath = resolveHostOpenCodeConfigPath(env)
581
+ if (!existsSync(configPath)) return { ok: false, reason: 'opencode.json not found' }
582
+ let data
583
+ try {
584
+ const parsed = JSON.parse(readFileSync(configPath, 'utf8'))
585
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
586
+ return { ok: false, reason: 'opencode.json is not a JSON object' }
587
+ }
588
+ data = parsed
589
+ } catch {
590
+ return { ok: false, reason: 'opencode.json is not plain JSON (comments?)' }
591
+ }
592
+ data.providers ??= {}
593
+ data.providers['typesafe-ai'] ??= {}
594
+ data.providers['typesafe-ai'].models ??= {}
595
+ if (data.providers['typesafe-ai'].models['jev-1.14.0'] === undefined) {
596
+ data.providers['typesafe-ai'].models['jev-1.14.0'] = {
597
+ name: 'Jev (TypeSafe direct)',
598
+ modelID: 'jev-latest',
599
+ type: 'decision',
600
+ }
601
+ }
602
+ try {
603
+ writeFileSync(configPath, `${JSON.stringify(data, null, 2)}\n`)
604
+ return { ok: true, path: configPath }
605
+ } catch (error) {
606
+ return { ok: false, reason: String(error instanceof Error ? error.message : error) }
607
+ }
608
+ }
609
+
610
+ /**
611
+ * Read-only check that the TypeSafe provider entry exists in the host config.
612
+ * Never writes; an unreadable config reports present:false with the path for
613
+ * the doctor's fix hint.
614
+ * @param {{ env?: Record<string, string | undefined> }} [options]
615
+ * @returns {{ present: boolean, path: string }}
616
+ */
617
+ export function inspectTypesafeHostProvider({ env = process.env } = {}) {
618
+ const configPath = resolveHostOpenCodeConfigPath(env)
619
+ try {
620
+ const parsed = JSON.parse(readFileSync(configPath, 'utf8'))
621
+ const model = parsed?.providers?.['typesafe-ai']?.models?.['jev-1.14.0']
622
+ return { present: model !== undefined && model !== null, path: configPath }
623
+ } catch {
624
+ return { present: false, path: configPath }
625
+ }
626
+ }
@@ -12,6 +12,11 @@
12
12
  * preparer. Transport is the host's own provider layer: this module never
13
13
  * touches fetch, endpoints, or credentials.
14
14
  *
15
+ * The gate chain lives in {@link runGatedNativeJevCall} so a second caller (the
16
+ * J1 risk-score shadow gate in `jev-risk-gate.ts`) reuses the exact same
17
+ * config → route → permission → reserve → decide → reconcile sequence instead
18
+ * of duplicating it; only the request preparer is caller-supplied.
19
+ *
15
20
  * Settlement follows the fetch runner's fail-closed contract: reserve before
16
21
  * the call, reconcile from the host-reported cost after it, and leave the
17
22
  * reservation pending (budget held for the period) when no evidence can be
@@ -21,14 +26,17 @@ import { readUserDecisionRouterConfig } from '../../scripts/install/decision-rou
21
26
  import {
22
27
  consumeJevDecisionResult,
23
28
  isJevDecisionPreset,
29
+ type JevDecisionPreparation,
24
30
  type JevHostSkill,
25
31
  type NativeJevRouteFailure,
32
+ type NativeJevRouteSelection,
26
33
  prepareJevDecisionRequest,
27
34
  prepareJevPresetRequest,
28
35
  resolveNativeJevRoute,
29
36
  } from './jev-decisions.ts'
30
37
  import {
31
38
  openLocalDecisionBudgetLedger,
39
+ type ReservationResult,
32
40
  resolveLocalDecisionBudgetDbPath,
33
41
  } from './local-decision-budget.ts'
34
42
  import {
@@ -36,7 +44,7 @@ import {
36
44
  buildDecisionEgressRequest,
37
45
  } from './local-decision-egress-gate.ts'
38
46
  import { verifyNativeUsageForReservation } from './local-decision-usage-evidence.internal.ts'
39
- import type { NativeDecisionRequest } from './v2-native-decisions.ts'
47
+ import type { NativeDecisionRequest, ResolvedNativeDecisionRoute } from './v2-native-decisions.ts'
40
48
  import type { V2ToolDef } from './v2-tools.ts'
41
49
 
42
50
  export interface V2JevDecisionRuntime {
@@ -90,19 +98,166 @@ function refusal(reasonCode: JevDecisionRunFailure): string {
90
98
  return JSON.stringify({ advisory: false, effect: 'none', reasonCode })
91
99
  }
92
100
 
101
+ function isNonBlankString(value: unknown): value is string {
102
+ return typeof value === 'string' && value.trim().length > 0
103
+ }
104
+
105
+ // ─── Shared gate chain ───────────────────────────────────────────────────
106
+
93
107
  /**
94
- * Refusal with the error CLASS only (`TypeError`, `RangeError`, …). The
95
- * message never crosses into the chat: it can carry paths, config or provider
96
- * detail, and the class alone already separates a detached-call failure from
97
- * a host-side data failure.
108
+ * Every gate-chain failure the shared runner can produce. It is
109
+ * {@link JevDecisionRunFailure} minus `CALLER_NOT_ZEUS`: the caller check is a
110
+ * property of the explicit tool surface, not of the gate chain, so the J1
111
+ * shadow observer can run the same chain for any agent.
98
112
  */
99
- function refusalDetail(reasonCode: JevDecisionRunFailure, err: unknown): string {
100
- const detail = err instanceof Error ? err.name : 'UnknownFailure'
101
- return JSON.stringify({ advisory: false, effect: 'none', reasonCode, detail })
113
+ export type GatedNativeJevFailure = Exclude<JevDecisionRunFailure, 'CALLER_NOT_ZEUS'>
114
+
115
+ /** The minimal runtime slice the gate chain needs. */
116
+ export type GatedNativeJevRuntime = Pick<V2JevDecisionRuntime, 'decide'> & {
117
+ /** Host permission kill-switch (`ctx.permission.assert`), when present. */
118
+ readonly permissionAssert?: (input: Record<string, unknown>) => Promise<unknown>
102
119
  }
103
120
 
104
- function isNonBlankString(value: unknown): value is string {
105
- return typeof value === 'string' && value.trim().length > 0
121
+ /** One completed, settled native Jev call: gates passed, usage reconciled. */
122
+ export interface GatedNativeJevCall {
123
+ /** The route the config + ledger gates selected. */
124
+ readonly selection: NativeJevRouteSelection
125
+ /** The prepared, bounded request this call ran. */
126
+ readonly request: NativeDecisionRequest
127
+ /** The raw host response; consume it through `consumeJevDecisionResult`. */
128
+ readonly response: unknown
129
+ /** The frozen ledger reconciliation state. */
130
+ readonly frozen: boolean
131
+ }
132
+
133
+ export type GatedNativeJevCallResult =
134
+ | { readonly ok: true; readonly call: GatedNativeJevCall }
135
+ | {
136
+ readonly ok: false
137
+ readonly reasonCode: GatedNativeJevFailure
138
+ /** Sanitized error CLASS only (`TypeError`, …); set for call failures. */
139
+ readonly detail?: string
140
+ }
141
+
142
+ /**
143
+ * Run ONE native Jev decision through the full gate chain — the exact chain
144
+ * `runJevDecision` has always run, extracted so a second caller (the J1
145
+ * risk-score shadow gate) reuses it instead of duplicating it:
146
+ * user-level config (`enabled`, `egress_consent`) → route via
147
+ * `resolveNativeJevRoute` with the ledger's admission check → host permission
148
+ * kill-switch on `decision.egress` → caller-supplied request preparation →
149
+ * reservation → the single host call → usage verification and reconciliation.
150
+ *
151
+ * The request preparer is injected because the two callers prepare differently
152
+ * (the tool from model input, J1 from a prebuilt bounded request); everything
153
+ * before and after it is shared. Settlement keeps the fetch runner's
154
+ * fail-closed contract: reserve before the call, reconcile from the
155
+ * host-reported cost after it, leave the reservation pending when no evidence
156
+ * can be minted.
157
+ *
158
+ * Rejects only when the budget ledger itself cannot be opened (the explicit
159
+ * tool surface propagates that as a tool error, unchanged); every gate failure
160
+ * is a structured `{ ok: false }` result, never a throw.
161
+ */
162
+ export async function runGatedNativeJevCall(params: {
163
+ readonly sessionID: unknown
164
+ readonly messageID: unknown
165
+ /** Current agent, only when the caller actually knows it. */
166
+ readonly agent?: unknown
167
+ readonly runtime: GatedNativeJevRuntime
168
+ readonly prepare: (
169
+ route: ResolvedNativeDecisionRoute,
170
+ ) => JevDecisionPreparation | Promise<JevDecisionPreparation>
171
+ }): Promise<GatedNativeJevCallResult> {
172
+ if (!isNonBlankString(params.sessionID) || !isNonBlankString(params.messageID)) {
173
+ return { ok: false, reasonCode: 'CONTEXT_UNAVAILABLE' }
174
+ }
175
+ const sessionID = params.sessionID
176
+ const messageID = params.messageID
177
+ const agent =
178
+ typeof params.agent === 'string' && params.agent.trim().length > 0 ? params.agent : undefined
179
+
180
+ let config: ReturnType<typeof readUserDecisionRouterConfig>
181
+ try {
182
+ config = readUserDecisionRouterConfig()
183
+ } catch {
184
+ return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE' }
185
+ }
186
+ if (!config.enabled) return { ok: false, reasonCode: 'DISABLED' }
187
+ if (!config.egress_consent) return { ok: false, reasonCode: 'CONSENT_MISSING' }
188
+
189
+ const ledger = openLocalDecisionBudgetLedger({ dbPath: resolveLocalDecisionBudgetDbPath() })
190
+ try {
191
+ const selection = resolveNativeJevRoute(
192
+ config,
193
+ (provider, model) => ledger.canReserve(provider, model).status === 'eligible',
194
+ )
195
+ if (!selection.ok) return { ok: false, reasonCode: selection.reasonCode }
196
+
197
+ if (typeof params.runtime.permissionAssert !== 'function') {
198
+ return { ok: false, reasonCode: 'PERMISSION_UNAVAILABLE' }
199
+ }
200
+ const assertion = await assertDecisionEgressPermission(
201
+ params.runtime.permissionAssert,
202
+ buildDecisionEgressRequest({
203
+ sessionID,
204
+ messageID,
205
+ endpoint: nativeJevPermissionResource(
206
+ selection.selection.route.model.providerID,
207
+ selection.selection.route.model.id,
208
+ ),
209
+ ...(agent === undefined ? {} : { agent }),
210
+ }),
211
+ )
212
+ if (assertion === 'deny') return { ok: false, reasonCode: 'PERMISSION_DENIED' }
213
+
214
+ const prepared = await params.prepare(selection.selection.route)
215
+ if (!prepared.ok) return { ok: false, reasonCode: prepared.reasonCode }
216
+
217
+ const reservation: ReservationResult = ledger.reserve(
218
+ selection.selection.accountingProvider,
219
+ selection.selection.model,
220
+ )
221
+ if (reservation.status !== 'reserved') return { ok: false, reasonCode: 'RESERVATION_DENIED' }
222
+
223
+ let response: unknown
224
+ try {
225
+ response = await params.runtime.decide(prepared.request)
226
+ } catch (err) {
227
+ return {
228
+ ok: false,
229
+ reasonCode: 'DECISION_CALL_FAILED',
230
+ detail: err instanceof Error ? err.name : 'UnknownFailure',
231
+ }
232
+ }
233
+
234
+ const evidence = verifyNativeUsageForReservation(
235
+ {
236
+ reservationId: reservation.reservationId,
237
+ provider: selection.selection.accountingProvider,
238
+ model: selection.selection.model,
239
+ period: reservation.period,
240
+ },
241
+ response,
242
+ )
243
+ if (evidence === null) return { ok: false, reasonCode: 'USAGE_UNRECONCILED' }
244
+ const reconciliation = ledger.reconcileVerified(reservation.reservationId, evidence)
245
+ if (reconciliation.status !== 'reconciled') {
246
+ return { ok: false, reasonCode: 'USAGE_UNRECONCILED' }
247
+ }
248
+
249
+ return {
250
+ ok: true,
251
+ call: {
252
+ selection: selection.selection,
253
+ request: prepared.request,
254
+ response,
255
+ frozen: reconciliation.frozen,
256
+ },
257
+ }
258
+ } finally {
259
+ ledger.close()
260
+ }
106
261
  }
107
262
 
108
263
  /**
@@ -150,103 +305,54 @@ export async function runJevDecision(
150
305
  ? (toolContext as JevToolContext)
151
306
  : undefined
152
307
  if (context?.agent !== 'zeus') return refusal('CALLER_NOT_ZEUS')
153
- const sessionID = context?.sessionID
154
- const messageID = context?.messageID
155
- if (!isNonBlankString(sessionID) || !isNonBlankString(messageID)) {
156
- return refusal('CONTEXT_UNAVAILABLE')
157
- }
158
-
159
- let config: ReturnType<typeof readUserDecisionRouterConfig>
160
- try {
161
- config = readUserDecisionRouterConfig()
162
- } catch {
163
- return refusal('CONFIG_UNAVAILABLE')
164
- }
165
- if (!config.enabled) return refusal('DISABLED')
166
- if (!config.egress_consent) return refusal('CONSENT_MISSING')
167
-
168
- const ledger = openLocalDecisionBudgetLedger({ dbPath: resolveLocalDecisionBudgetDbPath() })
169
- try {
170
- const selection = resolveNativeJevRoute(
171
- config,
172
- (provider, model) => ledger.canReserve(provider, model).status === 'eligible',
173
- )
174
- if (!selection.ok) return refusal(selection.reasonCode)
175
-
176
- if (typeof runtime.permissionAssert !== 'function') return refusal('PERMISSION_UNAVAILABLE')
177
- const assertion = await assertDecisionEgressPermission(
178
- runtime.permissionAssert,
179
- buildDecisionEgressRequest({
180
- sessionID,
181
- messageID,
182
- endpoint: nativeJevPermissionResource(
183
- selection.selection.route.model.providerID,
184
- selection.selection.route.model.id,
185
- ),
186
- agent: 'zeus',
187
- }),
188
- )
189
- if (assertion === 'deny') return refusal('PERMISSION_DENIED')
190
308
 
191
- const requested = (input ?? {}) as { mode?: unknown; questions?: unknown }
192
- const prepared =
309
+ const requested = (input ?? {}) as { mode?: unknown; questions?: unknown }
310
+ const result = await runGatedNativeJevCall({
311
+ sessionID: context?.sessionID,
312
+ messageID: context?.messageID,
313
+ agent: 'zeus',
314
+ runtime,
315
+ prepare: async (route) =>
193
316
  requested.mode === undefined
194
- ? prepareJevDecisionRequest(selection.selection.route, input ?? {})
317
+ ? prepareJevDecisionRequest(route, input ?? {})
195
318
  : isJevDecisionPreset(requested.mode)
196
319
  ? prepareJevPresetRequest(
197
- selection.selection.route,
320
+ route,
198
321
  requested.mode,
199
322
  input ?? {},
200
323
  requested.mode === 'skills' ? await readHostSkills(runtime) : undefined,
201
324
  )
202
- : { ok: false as const, reasonCode: 'PRESET_INVALID' as const }
203
- if (!prepared.ok) return refusal(prepared.reasonCode)
204
-
205
- const reservation = ledger.reserve(
206
- selection.selection.accountingProvider,
207
- selection.selection.model,
208
- )
209
- if (reservation.status !== 'reserved') return refusal('RESERVATION_DENIED')
210
-
211
- let response: unknown
212
- try {
213
- response = await runtime.decide(prepared.request)
214
- } catch (err) {
215
- return refusalDetail('DECISION_CALL_FAILED', err)
216
- }
217
-
218
- const evidence = verifyNativeUsageForReservation(
219
- {
220
- reservationId: reservation.reservationId,
221
- provider: selection.selection.accountingProvider,
222
- model: selection.selection.model,
223
- period: reservation.period,
224
- },
225
- response,
226
- )
227
- if (evidence === null) return refusal('USAGE_UNRECONCILED')
228
- const reconciliation = ledger.reconcileVerified(reservation.reservationId, evidence)
229
- if (reconciliation.status !== 'reconciled') return refusal('USAGE_UNRECONCILED')
230
-
231
- const advice = consumeJevDecisionResult(response, prepared.request)
325
+ : { ok: false as const, reasonCode: 'PRESET_INVALID' as const },
326
+ })
327
+ if (!result.ok) {
328
+ if (result.detail === undefined) return refusal(result.reasonCode)
329
+ // Refusal with the error CLASS only (`TypeError`, `RangeError`, …): the
330
+ // message can carry paths, config or provider detail and never crosses
331
+ // into the chat.
232
332
  return JSON.stringify({
233
- advisory: true,
333
+ advisory: false,
234
334
  effect: 'none',
235
- reason: 'JEV_DECISION',
236
- route: {
237
- providerID: selection.selection.route.model.providerID,
238
- id: selection.selection.route.model.id,
239
- billing: selection.selection.route.billing,
240
- },
241
- ...(requested.mode === undefined ? {} : { preset: requested.mode }),
242
- answers: advice.answers,
243
- missing: advice.missing,
244
- usage: { costUsd: advice.costUsd, tokens: advice.tokens },
245
- frozen: reconciliation.frozen,
335
+ reasonCode: result.reasonCode,
336
+ detail: result.detail,
246
337
  })
247
- } finally {
248
- ledger.close()
249
338
  }
339
+
340
+ const advice = consumeJevDecisionResult(result.call.response, result.call.request)
341
+ return JSON.stringify({
342
+ advisory: true,
343
+ effect: 'none',
344
+ reason: 'JEV_DECISION',
345
+ route: {
346
+ providerID: result.call.selection.route.model.providerID,
347
+ id: result.call.selection.route.model.id,
348
+ billing: result.call.selection.route.billing,
349
+ },
350
+ ...(requested.mode === undefined ? {} : { preset: requested.mode }),
351
+ answers: advice.answers,
352
+ missing: advice.missing,
353
+ usage: { costUsd: advice.costUsd, tokens: advice.tokens },
354
+ frozen: result.call.frozen,
355
+ })
250
356
  }
251
357
 
252
358
  const TOOL_DESCRIPTION =