pantheon-opencode 1.6.2-beta.15 → 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,12 @@ 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
+
13
19
  ## [v1.6.2-beta.15] - 2026-11-03
14
20
 
15
21
  ### Added
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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pantheon-opencode",
3
- "version": "1.6.2-beta.15",
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.15",
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.15"
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
@@ -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 =
@@ -0,0 +1,479 @@
1
+ /**
2
+ * J1 risk-score advisory gate — shadow-only observation of write/execute tool
3
+ * calls through the native Jev route.
4
+ *
5
+ * When `PANTHEON_J1_RISK_SCORE` is enabled, the plugin's `execute.before` hook
6
+ * fires ONE bounded native Jev decision per write/execute tool call through
7
+ * {@link runGatedNativeJevCall} — the SAME gate chain `pantheon_jev_decide`
8
+ * runs (user-level config, egress consent, budget-ledger reservation, the host
9
+ * permission kill-switch on `decision.egress`) — and records the outcome as a
10
+ * shadow record into the decision telemetry sink. The record is the whole
11
+ * effect: this gate never denies, never asks, never narrows a permission, and
12
+ * never delays the tool call. The 'flag' verdict
13
+ * ({@link RISK_GATE_FLAG_VERDICT}) is reserved for a future active phase and
14
+ * is unreachable while the gate is shadow-only.
15
+ *
16
+ * ## Sanitization contract
17
+ *
18
+ * The decision request carries NO user content: no task text, no file paths,
19
+ * no tool input values. The state text is the exact bounded template over
20
+ * three fields — the tool name (accepted only as a bounded
21
+ * `[A-Za-z0-9._:-]` token; anything else is `INPUT_INVALID`), the scope class
22
+ * (`write` | `execute` | `read`), and the sha256 of the serialized tool input
23
+ * (an opaque, bounded correlation value). Hostile names — paths, traversal,
24
+ * shell metacharacters, injection prose, oversize strings — are rejected
25
+ * outright, so no content slot exists in the first place. This mirrors the
26
+ * redaction discipline of the decision telemetry: an allowlist of bounded
27
+ * shapes, never a scrub of known-bad patterns.
28
+ *
29
+ * ## Fail-open
30
+ *
31
+ * Every failure mode — flag off, config disabled, consent missing, route or
32
+ * ledger denied, permission denied, decide throwing, the 2s deadline — skips
33
+ * the observation and records one `skip-…` reason token. The hook registers
34
+ * the observer only when the flag is on AND the host runtime exposes the
35
+ * native Decisions API, so a flag-off process pays zero overhead and a
36
+ * capability-less host behaves exactly as before.
37
+ *
38
+ * ## No delay, no retry, no queue
39
+ *
40
+ * The hook fires the observer without awaiting it (fire-and-observe); the
41
+ * observer bounds its own wait at {@link J1_RISK_GATE_TIMEOUT_MS} with an
42
+ * AbortController, records `skip-timeout` at the deadline, and lets the
43
+ * abandoned gate chain settle its own ledger reservation in the background.
44
+ * Exactly one call is ever fired: no retry, no queue.
45
+ *
46
+ * @module jev-risk-gate
47
+ */
48
+
49
+ import { createHash } from 'node:crypto'
50
+ import {
51
+ type GatedNativeJevFailure,
52
+ type GatedNativeJevRuntime,
53
+ runGatedNativeJevCall,
54
+ } from './jev-decision-tool.ts'
55
+ import { consumeJevDecisionResult } from './jev-decisions.ts'
56
+ import { observeShadow, type ShadowSink } from './v2-decision-shadow.ts'
57
+ import { secretScanApplies } from './v2-hook-engine.ts'
58
+ import type { NativeDecisionRequest } from './v2-native-decisions.ts'
59
+
60
+ /** On/off switch read by the plugin wiring. Any other value means off. */
61
+ export const J1_RISK_GATE_FLAG_ENV = 'PANTHEON_J1_RISK_SCORE'
62
+
63
+ /** Telemetry point id for the risk-score gate (J-series: the Jev uplift). */
64
+ export const J1_RISK_GATE_POINT = 'J1'
65
+
66
+ /** Wall-clock bound for one observation. The hook never waits on it. */
67
+ export const J1_RISK_GATE_TIMEOUT_MS = 2_000
68
+
69
+ /**
70
+ * Reserved verdict for a future active phase. NOT reachable: the gate is
71
+ * shadow-only in this release, {@link riskGateVerdict} never returns it, and
72
+ * nothing in the wiring consults it. Kept as a named constant so the active
73
+ * phase cannot invent a second name for the same concept.
74
+ */
75
+ export const RISK_GATE_FLAG_VERDICT = 'flag' as const
76
+
77
+ export type RiskGateScope = 'write' | 'execute' | 'read'
78
+
79
+ /** Question names of the two prepared questions, matched on consumption. */
80
+ export const RISK_QUESTION_NAME = 'risk'
81
+ export const INTENT_QUESTION_NAME = 'intent'
82
+
83
+ /** Score levels offered to the host; within the 2..10 question bound. */
84
+ export const J1_RISK_SCORE_LEVEL_COUNT = 5
85
+
86
+ /** Bound for the composed state text (the template is ~220 chars). */
87
+ export const J1_RISK_GATE_STATE_MAX_LENGTH = 512
88
+
89
+ /** Predicate probability at or above which the intent counts as consistent. */
90
+ export const RISK_GATE_INTENT_THRESHOLD = 0.5
91
+
92
+ const FLAG_ON = new Set(['1', 'on', 'true'])
93
+ const TOOL_NAME_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
94
+ const SHA256_HEX = /^[0-9a-f]{64}$/
95
+ const SCOPES: ReadonlySet<string> = new Set(['write', 'execute', 'read'])
96
+
97
+ /**
98
+ * Tools whose call can run commands or reach the network. A NAME allowlist:
99
+ * an unknown tool is `read` (never observed) — the opposite bias of the
100
+ * secret scan, which must scan unknown names because it blocks; J1 spends
101
+ * budget per observation, so it observes only what it can classify.
102
+ */
103
+ const EXECUTE_TOOLS: ReadonlySet<string> = new Set([
104
+ 'bash',
105
+ 'shell',
106
+ 'sh',
107
+ 'zsh',
108
+ 'fish',
109
+ 'powershell',
110
+ 'cmd',
111
+ 'webfetch',
112
+ ])
113
+ const WRITE_TOOLS: ReadonlySet<string> = new Set([
114
+ 'write',
115
+ 'edit',
116
+ 'multiedit',
117
+ 'notebookedit',
118
+ 'patch',
119
+ 'apply_patch',
120
+ 'hashline_edit',
121
+ ])
122
+
123
+ /** Whether the operator explicitly enabled the flag. Absence means off. */
124
+ export function j1RiskGateEnabledFromEnv(
125
+ env: Record<string, string | undefined> = process.env,
126
+ ): boolean {
127
+ const raw = (env[J1_RISK_GATE_FLAG_ENV] ?? '').trim().toLowerCase()
128
+ return FLAG_ON.has(raw)
129
+ }
130
+
131
+ /**
132
+ * Classify a tool name into the request's scope class. Unknown or non-string
133
+ * names are `read` — never observed, never guessed into write/execute.
134
+ */
135
+ export function classifyRiskGateScope(tool: unknown): RiskGateScope {
136
+ if (typeof tool !== 'string') return 'read'
137
+ const normalized = tool.trim().toLowerCase()
138
+ if (EXECUTE_TOOLS.has(normalized)) return 'execute'
139
+ if (WRITE_TOOLS.has(normalized)) return 'write'
140
+ return 'read'
141
+ }
142
+
143
+ /**
144
+ * Whether one tool call is a J1 observation target: a write/execute scope AND
145
+ * the secret scan's own exfil-capable gate. The second condition reuses the
146
+ * scan's read-only denylist (`v2-hook-engine.secretScanApplies`) so a tool the
147
+ * scan never inspects can never be observed either — one list, two consumers.
148
+ */
149
+ export function isRiskGateTarget(tool: unknown): tool is string {
150
+ if (!secretScanApplies(tool)) return false
151
+ const scope = classifyRiskGateScope(tool)
152
+ return scope === 'write' || scope === 'execute'
153
+ }
154
+
155
+ /**
156
+ * sha256 hex of the serialized tool input — an opaque correlation value, the
157
+ * only content-derived field that ever leaves this process. Unserializable
158
+ * inputs hash a stable marker; this never throws.
159
+ */
160
+ export function hashToolInput(input: unknown): string {
161
+ let serialized: string
162
+ if (typeof input === 'string') {
163
+ serialized = input
164
+ } else {
165
+ try {
166
+ const json = JSON.stringify(input)
167
+ serialized = json === undefined ? String(input) : json
168
+ } catch {
169
+ serialized = 'unserializable-tool-input'
170
+ }
171
+ }
172
+ return createHash('sha256').update(serialized, 'utf8').digest('hex')
173
+ }
174
+
175
+ export type RiskGateRequestFailure = 'INPUT_INVALID'
176
+
177
+ export type RiskGatePreparedRequest =
178
+ | {
179
+ readonly ok: true
180
+ /** The request body; the caller attaches the resolved route's `model`. */
181
+ readonly request: Omit<NativeDecisionRequest, 'model'>
182
+ }
183
+ | { readonly ok: false; readonly reasonCode: RiskGateRequestFailure }
184
+
185
+ const RISK_LEVELS = Object.freeze(
186
+ Array.from({ length: J1_RISK_SCORE_LEVEL_COUNT }, (_, index) => {
187
+ const labels = ['routine', 'low', 'moderate', 'high', 'critical'] as const
188
+ return Object.freeze({ label: labels[index] ?? `level-${index}` })
189
+ }),
190
+ )
191
+
192
+ const RISK_INSTRUCTIONS =
193
+ 'Rate how risky this single tool call is for the current task, judging only the ' +
194
+ 'tool class: routine and reversible at the low end, destructive or exfiltrating ' +
195
+ 'at the high end. Advisory only; nothing is enforced.'
196
+ const INTENT_INSTRUCTIONS =
197
+ 'Is a call of this tool class plausibly consistent with continuing the current ' +
198
+ 'task? Answer as a probability. Advisory only; nothing is enforced.'
199
+
200
+ const QUESTIONS = Object.freeze([
201
+ Object.freeze({
202
+ type: 'score' as const,
203
+ name: RISK_QUESTION_NAME,
204
+ instructions: RISK_INSTRUCTIONS,
205
+ levels: RISK_LEVELS,
206
+ }),
207
+ Object.freeze({
208
+ type: 'predicate' as const,
209
+ name: INTENT_QUESTION_NAME,
210
+ instructions: INTENT_INSTRUCTIONS,
211
+ }),
212
+ ])
213
+
214
+ /**
215
+ * Build the bounded decision request — the sanitization contract made
216
+ * structural. The state is the exact template over the three admitted fields;
217
+ * the tool name must already be a bounded token (paths, metacharacters and
218
+ * prose are `INPUT_INVALID`, never sanitized on the way in); the hash must be
219
+ * lowercase sha256 hex. Two questions only: one score (2–10 levels), one
220
+ * predicate. No file parts, no JSON parts, no extra fields.
221
+ */
222
+ export function buildRiskGateRequest(input: {
223
+ readonly toolName: string
224
+ readonly toolInputHash: string
225
+ readonly scope: RiskGateScope
226
+ }): RiskGatePreparedRequest {
227
+ const toolName = input?.toolName
228
+ const toolInputHash = input?.toolInputHash
229
+ const scope = input?.scope
230
+ if (scope === undefined || typeof scope !== 'string' || !SCOPES.has(scope)) {
231
+ return { ok: false, reasonCode: 'INPUT_INVALID' }
232
+ }
233
+ if (typeof toolName !== 'string' || !TOOL_NAME_TOKEN.test(toolName)) {
234
+ return { ok: false, reasonCode: 'INPUT_INVALID' }
235
+ }
236
+ if (typeof toolInputHash !== 'string' || !SHA256_HEX.test(toolInputHash)) {
237
+ return { ok: false, reasonCode: 'INPUT_INVALID' }
238
+ }
239
+ const state =
240
+ 'Advisory risk probe for one tool call. ' +
241
+ `tool_name: ${toolName}. scope: ${scope}. tool_input_sha256: ${toolInputHash}. ` +
242
+ 'The request carries no file paths, no tool arguments and no task content; ' +
243
+ 'judge from the tool class alone.'
244
+ if (state.length > J1_RISK_GATE_STATE_MAX_LENGTH) {
245
+ return { ok: false, reasonCode: 'INPUT_INVALID' }
246
+ }
247
+ return {
248
+ ok: true,
249
+ request: Object.freeze({
250
+ input: Object.freeze([Object.freeze({ type: 'text' as const, text: state })]),
251
+ questions: QUESTIONS,
252
+ }),
253
+ }
254
+ }
255
+
256
+ export interface RiskGateEvaluation {
257
+ /**
258
+ * The host's score for the `risk` question; `null` when the answer is
259
+ * missing, mistyped, duplicated or an error. An ordinal, not a probability.
260
+ */
261
+ readonly riskScore: number | null
262
+ /**
263
+ * Whether the `intent` predicate holds (probability ≥ 0.5); `null` under the
264
+ * same failures.
265
+ */
266
+ readonly intentConsistent: boolean | null
267
+ }
268
+
269
+ /**
270
+ * Consume a host Decisions response against the prepared request.
271
+ *
272
+ * Validation is strict and borrowed wholesale from the tool's own consumer
273
+ * (`consumeJevDecisionResult`): an answer counts only when its name and type
274
+ * match the prepared questions, score answers carry a non-negative finite
275
+ * score, predicate answers a probability in [0, 1], and duplicates become
276
+ * errors. Anything else — and any unknown response shape — is `null`, never a
277
+ * guess. Extra fields on answers never cross into the evaluation.
278
+ */
279
+ export function evaluateRiskGateDecision(
280
+ response: unknown,
281
+ request: NativeDecisionRequest,
282
+ ): RiskGateEvaluation {
283
+ const advice = consumeJevDecisionResult(response, request)
284
+ let riskScore: number | null = null
285
+ let intentConsistent: boolean | null = null
286
+ for (const answer of advice.answers) {
287
+ if (answer.type === 'error') continue
288
+ if (answer.type === 'score' && answer.name === RISK_QUESTION_NAME) {
289
+ riskScore = answer.score ?? null
290
+ } else if (answer.type === 'predicate' && answer.name === INTENT_QUESTION_NAME) {
291
+ intentConsistent = (answer.probability ?? 0) >= RISK_GATE_INTENT_THRESHOLD
292
+ }
293
+ }
294
+ return { riskScore, intentConsistent }
295
+ }
296
+
297
+ export type RiskGateVerdict = 'observe' | 'flag'
298
+
299
+ /**
300
+ * The policy: in shadow mode the verdict is ALWAYS `observe` — for every risk
301
+ * score, for every intent answer, for nulls. Shadow never denies and never
302
+ * asks; a high score changes the record's reason, nothing else. The `flag`
303
+ * verdict ({@link RISK_GATE_FLAG_VERDICT}) is reserved for a future active
304
+ * phase and is unreachable here by construction: `shadow` admits only `true`
305
+ * and no branch below returns anything but `observe`.
306
+ */
307
+ export function riskGateVerdict(input: {
308
+ readonly riskScore: number | null
309
+ readonly intentConsistent: boolean | null
310
+ readonly shadow: true
311
+ }): RiskGateVerdict {
312
+ void input // every evaluation is admitted while the gate is shadow-only
313
+ return 'observe'
314
+ }
315
+
316
+ function formatScoreToken(value: number): string {
317
+ if (!Number.isFinite(value) || value < 0 || value > 1000) return 'na'
318
+ const text = String(Math.round(value * 100) / 100)
319
+ return TOOL_NAME_TOKEN.test(text) ? text : 'na'
320
+ }
321
+
322
+ /**
323
+ * Encode the evaluation into ONE telemetry reason token (the sink's allowlist
324
+ * has no slot for structured fields, and that is its strength): e.g.
325
+ * `risk-3-intent-yes`, `risk-na-intent-na`. Always a bounded
326
+ * `[A-Za-z0-9._:-]` token; a score outside 0..1000 or not finitely
327
+ * representable encodes as `na`.
328
+ */
329
+ export function encodeRiskGateReason(input: {
330
+ readonly riskScore: number | null
331
+ readonly intentConsistent: boolean | null
332
+ }): string {
333
+ const score = input.riskScore === null ? 'na' : formatScoreToken(input.riskScore)
334
+ const intent = input.intentConsistent === null ? 'na' : input.intentConsistent ? 'yes' : 'no'
335
+ return `risk-${score}-intent-${intent}`
336
+ }
337
+
338
+ const SKIP_REASON_BY_GATE_FAILURE: Readonly<Record<GatedNativeJevFailure, string>> = Object.freeze({
339
+ CONTEXT_UNAVAILABLE: 'skip-context-unavailable',
340
+ CONFIG_UNAVAILABLE: 'skip-config-unavailable',
341
+ DISABLED: 'skip-config-disabled',
342
+ CONSENT_MISSING: 'skip-consent-missing',
343
+ CAP_OR_PERIOD_DENIED: 'skip-reservation-denied',
344
+ NO_ELIGIBLE_CANDIDATE: 'skip-route-unavailable',
345
+ PERMISSION_UNAVAILABLE: 'skip-permission-unavailable',
346
+ PERMISSION_DENIED: 'skip-permission-denied',
347
+ STATE_INVALID: 'skip-request-invalid',
348
+ QUESTIONS_INVALID: 'skip-request-invalid',
349
+ PRESET_INVALID: 'skip-request-invalid',
350
+ RESERVATION_DENIED: 'skip-reservation-denied',
351
+ DECISION_CALL_FAILED: 'skip-decision-call-failed',
352
+ USAGE_UNRECONCILED: 'skip-usage-unreconciled',
353
+ })
354
+
355
+ /** Map a gate failure to its telemetry reason token; unknown → fail-open. */
356
+ export function mapGateFailureToSkipReason(reasonCode: string): string {
357
+ return SKIP_REASON_BY_GATE_FAILURE[reasonCode as GatedNativeJevFailure] ?? 'skip-gate-unavailable'
358
+ }
359
+
360
+ /** The `execute.before` fields the observer reads; `input` is hashed, never read. */
361
+ interface J1ExecuteBeforeEvent {
362
+ tool?: unknown
363
+ sessionID?: unknown
364
+ messageID?: unknown
365
+ agent?: unknown
366
+ input?: unknown
367
+ }
368
+
369
+ export interface J1RiskGateObserverOptions {
370
+ /** The same runtime the `pantheon_jev_decide` tool uses. */
371
+ readonly runtime: GatedNativeJevRuntime
372
+ /** Shadow-record sink (the plugin wraps it with the telemetry mode). */
373
+ readonly sink?: ShadowSink
374
+ readonly timeoutMs?: number
375
+ }
376
+
377
+ function recordSkip(sink: ShadowSink | undefined, skipReason: string): void {
378
+ observeShadow(
379
+ J1_RISK_GATE_POINT,
380
+ skipReason,
381
+ () => ({
382
+ decision: 'unavailable',
383
+ reason: skipReason,
384
+ }),
385
+ sink,
386
+ )
387
+ }
388
+
389
+ function abortDeadline(signal: AbortSignal): Promise<'timeout'> {
390
+ return new Promise((resolve) => {
391
+ if (signal.aborted) {
392
+ resolve('timeout')
393
+ return
394
+ }
395
+ signal.addEventListener('abort', () => resolve('timeout'), { once: true })
396
+ })
397
+ }
398
+
399
+ /**
400
+ * Create the J1 observer: one async, self-bounding observation per
401
+ * `execute.before` event. The returned function NEVER throws and NEVER
402
+ * records more than one shadow record per event; a read-scope or malformed
403
+ * event records nothing at all.
404
+ *
405
+ * The gate chain runs unawaited races against the deadline; on timeout the
406
+ * observer records `skip-timeout` and abandons while the abandoned chain
407
+ * settles its own ledger reservation in the background (settlement of an
408
+ * already-fired call — not a retry, and it writes no record).
409
+ */
410
+ export function createJ1RiskGateObserver(
411
+ options: J1RiskGateObserverOptions,
412
+ ): (event: unknown) => Promise<void> {
413
+ const timeoutMs = options.timeoutMs ?? J1_RISK_GATE_TIMEOUT_MS
414
+ const sink = options.sink
415
+ return async (event: unknown): Promise<void> => {
416
+ try {
417
+ const payload = (event ?? {}) as J1ExecuteBeforeEvent
418
+ if (!isRiskGateTarget(payload.tool)) return
419
+ const tool = payload.tool
420
+ const scope = classifyRiskGateScope(tool)
421
+ const built = buildRiskGateRequest({
422
+ toolName: tool,
423
+ toolInputHash: hashToolInput(payload.input),
424
+ scope,
425
+ })
426
+ if (!built.ok) {
427
+ recordSkip(sink, 'skip-input-invalid')
428
+ return
429
+ }
430
+ const controller = new AbortController()
431
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
432
+ if (typeof timer === 'object' && typeof timer.unref === 'function') timer.unref()
433
+ try {
434
+ const outcome = await Promise.race([
435
+ runGatedNativeJevCall({
436
+ sessionID: payload.sessionID,
437
+ messageID: payload.messageID,
438
+ agent: typeof payload.agent === 'string' ? payload.agent : undefined,
439
+ runtime: options.runtime,
440
+ prepare: (route) => ({
441
+ ok: true as const,
442
+ request: {
443
+ model: route.model,
444
+ input: built.request.input,
445
+ questions: built.request.questions,
446
+ },
447
+ }),
448
+ }),
449
+ abortDeadline(controller.signal),
450
+ ])
451
+ if (outcome === 'timeout') {
452
+ recordSkip(sink, 'skip-timeout')
453
+ return
454
+ }
455
+ if (!outcome.ok) {
456
+ recordSkip(sink, mapGateFailureToSkipReason(outcome.reasonCode))
457
+ return
458
+ }
459
+ const evaluation = evaluateRiskGateDecision(outcome.call.response, outcome.call.request)
460
+ observeShadow(
461
+ J1_RISK_GATE_POINT,
462
+ evaluation,
463
+ (isolated) => ({
464
+ decision: 'observe',
465
+ reason: encodeRiskGateReason(isolated as RiskGateEvaluation),
466
+ }),
467
+ sink,
468
+ )
469
+ } finally {
470
+ clearTimeout(timer)
471
+ }
472
+ } catch {
473
+ // Fail-open: the gate chain rejects only when the budget ledger cannot
474
+ // be opened; any other unexpected failure lands here too. One skip
475
+ // record, no detail, no propagation into the tool call.
476
+ recordSkip(sink, 'skip-gate-unavailable')
477
+ }
478
+ }
479
+ }
@@ -37,9 +37,17 @@ export const TELEMETRY_FIELDS = [
37
37
  export type TelemetryField = (typeof TELEMETRY_FIELDS)[number]
38
38
  export type TelemetryMode = 'shadow' | 'active' | 'off' | 'migration'
39
39
 
40
+ /**
41
+ * Point ids admitted into telemetry: the measured P-series registry points
42
+ * plus the J-series of the Jev uplift (J1 risk-score gate; later J phases
43
+ * extend the series, never the P-series). The two series are disjoint on
44
+ * purpose — a J record is advisory-tool telemetry, not a registry point.
45
+ */
46
+ export type TelemetryPointId = DecisionPointId | 'J1'
47
+
40
48
  export interface DecisionTelemetryEvent {
41
49
  readonly schemaVersion: typeof TELEMETRY_SCHEMA_VERSION
42
- readonly point: DecisionPointId
50
+ readonly point: TelemetryPointId
43
51
  readonly decision: string
44
52
  readonly effect: 'none'
45
53
  readonly reason: string
@@ -63,7 +71,8 @@ export type TelemetryResult =
63
71
  }
64
72
 
65
73
  const TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/
66
- const POINT_ID = /^P(?:[1-9]|1[01])$/
74
+ /** Registry points (`P1`…`P11`) plus the Jev-uplift series (`J0`…`J99`). */
75
+ const POINT_ID = /^(?:P(?:[1-9]|1[01])|J[0-9]{1,2})$/
67
76
  const TELEMETRY_KEYS: ReadonlySet<string> = new Set(TELEMETRY_FIELDS)
68
77
  const MODES: ReadonlySet<string> = new Set(['shadow', 'active', 'off', 'migration'])
69
78
  const DURATION_MAX_MS = 60_000
@@ -76,7 +85,7 @@ function isToken(value: unknown): value is string {
76
85
  return typeof value === 'string' && TOKEN.test(value)
77
86
  }
78
87
 
79
- function isPointId(value: unknown): value is DecisionPointId {
88
+ function isPointId(value: unknown): value is TelemetryPointId {
80
89
  return typeof value === 'string' && POINT_ID.test(value)
81
90
  }
82
91
 
@@ -98,7 +107,7 @@ export function sanitizeTelemetry(input: unknown): TelemetryResult {
98
107
  droppedFieldCount += 1
99
108
  }
100
109
 
101
- let point: DecisionPointId | null = null
110
+ let point: TelemetryPointId | null = null
102
111
  let decision: string | null = null
103
112
  let reason: string | null = null
104
113
  let mode: TelemetryMode | null = null
package/src/plugin-v2.ts CHANGED
@@ -116,6 +116,11 @@ import {
116
116
  import { GOAL_LOOP_DEFAULTS, GoalStore } from './pantheon/goal-loop.ts'
117
117
  import { createGuardPathResolver } from './pantheon/guard-path.ts'
118
118
  import type { V2JevDecisionRuntime } from './pantheon/jev-decision-tool.ts'
119
+ import {
120
+ createJ1RiskGateObserver,
121
+ isRiskGateTarget,
122
+ j1RiskGateEnabledFromEnv,
123
+ } from './pantheon/jev-risk-gate.ts'
119
124
  import { DECISION_EGRESS_ACTION } from './pantheon/local-decision-egress-gate.ts'
120
125
  import { applyDecisionRouterToPrompt } from './pantheon/local-decision-prompt.ts'
121
126
  import { getSharedBoard } from './pantheon/shared-board.ts'
@@ -660,6 +665,45 @@ function transformReferences(draft: ReferenceDraft): void {
660
665
 
661
666
  // ─── V2 Tool Registration ───────────────────────────────────────────────
662
667
 
668
+ /**
669
+ * Construct the ONE Jev runtime the plugin threads everywhere: the explicit
670
+ * `pantheon_jev_decide` tool and the J1 risk-score shadow observer both call
671
+ * through this instance, so `decide` and `permissionAssert` are bound to their
672
+ * owning host domains exactly once. `undefined` when the host lacks either the
673
+ * native Decisions API or the model catalog (the route no longer consults the
674
+ * catalog, but the tool registration contract still feature-detects both).
675
+ */
676
+ function buildV2JevRuntime(host: ReturnType<typeof hostDomains>): V2JevDecisionRuntime | undefined {
677
+ const decisionsFn = host.experimental?.generate?.decisions
678
+ const modelListFn = host.model?.list
679
+ if (typeof decisionsFn !== 'function' || typeof modelListFn !== 'function') return undefined
680
+ const decisionsOwner = host.experimental?.generate
681
+ const decide = decisionsFn
682
+ const listModels = modelListFn
683
+ // The 2.2.5 host exposes ctx.skill as the SkillEditor (list()); the SDK
684
+ // types this file sees declare skill as the registration hook, so the
685
+ // runtime shape is read through one narrow, feature-detected cast.
686
+ const skillDomain = (host as { skill?: { list?: () => unknown } }).skill
687
+ const skillList = skillDomain?.list
688
+ const permissionAssertFn = host.permission?.assert
689
+ const permissionAssert =
690
+ typeof permissionAssertFn === 'function'
691
+ ? (input: Record<string, unknown>) => permissionAssertFn.call(host.permission, input)
692
+ : undefined
693
+ return {
694
+ // Every host method is invoked with its owning domain as receiver: the
695
+ // canary records `ctx.model.list()` (bound) succeeding on 2.2.5 while a
696
+ // detached reference threw in the field and surfaced only as
697
+ // CATALOG_UNAVAILABLE. Same discipline as permissionAssert above.
698
+ listModels: () => listModels.call(host.model),
699
+ decide: (request: NativeDecisionRequest) => decide.call(decisionsOwner, request),
700
+ // Sync-or-async host skill list; absent/throwing falls back to the
701
+ // catalog-only preset inside the tool.
702
+ listSkills: async () => skillList?.call(skillDomain),
703
+ ...(permissionAssert === undefined ? {} : { permissionAssert }),
704
+ }
705
+ }
706
+
663
707
  /**
664
708
  * Attempt to register Pantheon tools via V2 ctx.tool.transform.
665
709
  *
@@ -675,6 +719,7 @@ function transformReferences(draft: ReferenceDraft): void {
675
719
  async function registerV2Tools(
676
720
  context: PluginContext,
677
721
  boundedRead?: ReturnType<typeof createV2BoundedReadTool>['definition'],
722
+ jevRuntime?: V2JevDecisionRuntime,
678
723
  ): Promise<boolean> {
679
724
  const host = hostDomains(context)
680
725
  const toolCtx = host.tool
@@ -698,34 +743,10 @@ async function registerV2Tools(
698
743
  const decisionsFn = host.experimental?.generate?.decisions
699
744
  const jevReady = visionReady && typeof decisionsFn === 'function'
700
745
  if (!jevReady) markUnsupported('jev-decision-tool')
701
- const permissionAssertFn = host.permission?.assert
702
- let jevRuntime: V2JevDecisionRuntime | undefined
703
- if (jevReady && typeof decisionsFn === 'function' && typeof modelListFn === 'function') {
704
- const decisionsOwner = host.experimental?.generate
705
- const decide = decisionsFn
706
- const listModels = modelListFn
707
- // The 2.2.5 host exposes ctx.skill as the SkillEditor (list()); the SDK
708
- // types this file sees declare skill as the registration hook, so the
709
- // runtime shape is read through one narrow, feature-detected cast.
710
- const skillDomain = (host as { skill?: { list?: () => unknown } }).skill
711
- const skillList = skillDomain?.list
712
- const permissionAssert =
713
- typeof permissionAssertFn === 'function'
714
- ? (input: Record<string, unknown>) => permissionAssertFn.call(host.permission, input)
715
- : undefined
716
- jevRuntime = {
717
- // Every host method is invoked with its owning domain as receiver:
718
- // the canary records `ctx.model.list()` (bound) succeeding on 2.2.5
719
- // while a detached reference threw in the field and surfaced only as
720
- // CATALOG_UNAVAILABLE. Same discipline as permissionAssert above.
721
- listModels: () => listModels.call(host.model),
722
- decide: (request: NativeDecisionRequest) => decide.call(decisionsOwner, request),
723
- // Sync-or-async host skill list; absent/throwing falls back to the
724
- // catalog-only preset inside the tool.
725
- listSkills: async () => skillList?.call(skillDomain),
726
- ...(permissionAssert === undefined ? {} : { permissionAssert }),
727
- }
728
- }
746
+ // The setup flow threads the ONE runtime instance it built (shared with
747
+ // the J1 observer in the execute.before hook); this local fallback keeps a
748
+ // direct registration call self-sufficient.
749
+ const runtime = jevRuntime ?? (jevReady ? buildV2JevRuntime(host) : undefined)
729
750
  // P3 (complexity) declares `tool.invoke`; its construction site is the
730
751
  // local selector's execute, fed by that tool's own input schema. The sink
731
752
  // is the 0b record path (in-memory, bounded, I/O-free) and every record
@@ -739,7 +760,7 @@ async function registerV2Tools(
739
760
  p3Sink.emit({ ...record, mode: 'shadow' })
740
761
  },
741
762
  },
742
- jevRuntime,
763
+ runtime,
743
764
  )
744
765
  if (boundedRead !== undefined) toolDefs.push(boundedRead)
745
766
 
@@ -894,6 +915,25 @@ export function getP11TelemetrySinkForTests(): TelemetrySink | undefined {
894
915
 
895
916
  let p11TelemetrySink: TelemetrySink | undefined
896
917
 
918
+ /**
919
+ * The J1 risk-score telemetry sink created by the most recent tool-hook
920
+ * registration.
921
+ *
922
+ * J1 (the risk-score advisory gate, `jev-risk-gate.ts`) is NOT a registry
923
+ * point: it is a flag-gated shadow observer on write/execute tool calls. The
924
+ * sink exists only when `PANTHEON_J1_RISK_SCORE` is on AND the host runtime
925
+ * exposes the native Decisions API, so flag-off leaves it undefined — the
926
+ * zero-overhead contract. Records go through the in-memory, bounded 0b path
927
+ * (`createTelemetrySink`, no I/O) and carry `mode: 'shadow'`; the observer is
928
+ * fire-and-observe, so the tool call never waits on it. Exported only for
929
+ * tests/pantheon/plugin-v2-contract.test.ts.
930
+ */
931
+ export function getJ1TelemetrySinkForTests(): TelemetrySink | undefined {
932
+ return j1TelemetrySink
933
+ }
934
+
935
+ let j1TelemetrySink: TelemetrySink | undefined
936
+
897
937
  /**
898
938
  * Attempt to subscribe to session events via V2 ctx.event.subscribe.
899
939
  *
@@ -1856,6 +1896,7 @@ async function registerV2ToolHooks(
1856
1896
  context: PluginContext,
1857
1897
  subagentOrigins: V2SubagentOriginRegistry,
1858
1898
  boundedReadOrigins?: V2BoundedReadOriginRegistry,
1899
+ jevRuntime?: V2JevDecisionRuntime,
1859
1900
  ): Promise<{ registered: boolean; beforeRegistered: boolean }> {
1860
1901
  const host = hostDomains(context)
1861
1902
  const toolCtx = host.tool
@@ -1872,6 +1913,26 @@ async function registerV2ToolHooks(
1872
1913
  onUnkeyed: appendV2HookLog,
1873
1914
  })
1874
1915
 
1916
+ // J1 risk-score advisory gate (jev-risk-gate.ts). Constructed ONLY when
1917
+ // PANTHEON_J1_RISK_SCORE is on AND the host runtime exposes the native
1918
+ // Decisions API (the same instance `pantheon_jev_decide` uses), so flag-off
1919
+ // is a hard zero: no sink, no observer, no per-call work. When enabled, the
1920
+ // observer runs the SAME gate chain as the explicit tool (config, consent,
1921
+ // ledger reservation, permission kill-switch) and records shadow records
1922
+ // only — it is fired WITHOUT await inside the before-handler (fire-and-
1923
+ // observe), self-bounds at 2s with an AbortController, and never retries.
1924
+ let j1Observer: ((event: unknown) => Promise<void>) | undefined
1925
+ if (jevRuntime !== undefined && j1RiskGateEnabledFromEnv()) {
1926
+ const j1Sink = createTelemetrySink()
1927
+ j1TelemetrySink = j1Sink
1928
+ j1Observer = createJ1RiskGateObserver({
1929
+ runtime: jevRuntime,
1930
+ sink: (record) => {
1931
+ j1Sink.emit({ ...record, mode: 'shadow' })
1932
+ },
1933
+ })
1934
+ }
1935
+
1875
1936
  // Symlink resolution for the Zeus read guard (#272). The predicate is pure,
1876
1937
  // so the filesystem work happens at this call site, rooted at the project
1877
1938
  // directory the host reports. Same mechanism as V1's (src/plugin.ts) so the
@@ -1987,6 +2048,17 @@ async function registerV2ToolHooks(
1987
2048
  if (origin !== undefined) {
1988
2049
  writeV2AdmissionProof('tool.execute.before', { ...origin })
1989
2050
  }
2051
+ // J1 risk-score shadow observation. Deliberately AFTER every guard: a
2052
+ // denied call must not spend decision budget. Fire-and-observe — the
2053
+ // promise is deliberately NOT awaited, so the hook's latency is
2054
+ // unchanged; the observer self-bounds at 2s (AbortController),
2055
+ // contains its own failures, records at most one shadow record per
2056
+ // event, and never blocks, retries, or queues. Undefined (no-op) when
2057
+ // the flag is off — the only cost of the flag-on check below is the
2058
+ // truthiness read.
2059
+ if (j1Observer !== undefined && isRiskGateTarget((event as { tool?: unknown }).tool)) {
2060
+ void j1Observer(event)
2061
+ }
1990
2062
  // Delegation audit START record (#266). Deliberately AFTER every guard
1991
2063
  // and the secret scan: a denied call must not leave a start record with
1992
2064
  // no matching stop. The formatter/stop halves run in `execute.after`.
@@ -2489,10 +2561,17 @@ export const plugin = define({
2489
2561
  }
2490
2562
 
2491
2563
  // ─── Phase 5: V2 Tool Hooks (best-effort) ────────────────────────
2564
+ // The Jev runtime is built ONCE here and threaded to both consumers — the
2565
+ // tool registration (Phase 6) and the J1 risk-score observer inside the
2566
+ // execute.before hook — so `decide` and `permissionAssert` are bound to
2567
+ // their owning host domains exactly once. Pure construction over the host
2568
+ // domains: nothing is marked unsupported here; Phase 6 keeps that job.
2569
+ const jevRuntime = buildV2JevRuntime(hostDomains(context))
2492
2570
  const toolHookResult = await registerV2ToolHooks(
2493
2571
  context,
2494
2572
  subagentOrigins,
2495
2573
  boundedRead?.origins,
2574
+ jevRuntime,
2496
2575
  ).catch(() => ({ registered: false, beforeRegistered: false }))
2497
2576
  if (!toolHookResult.registered) {
2498
2577
  markUnsupported('tool-execute-hooks')
@@ -2505,7 +2584,9 @@ export const plugin = define({
2505
2584
  if (boundedRead !== undefined && boundedReadDefinition === undefined) {
2506
2585
  markUnsupported('bounded-read')
2507
2586
  }
2508
- const toolsRegistered = await registerV2Tools(context, boundedReadDefinition).catch(() => false)
2587
+ const toolsRegistered = await registerV2Tools(context, boundedReadDefinition, jevRuntime).catch(
2588
+ () => false,
2589
+ )
2509
2590
  if (!toolsRegistered) markUnsupported('tool-transform')
2510
2591
 
2511
2592
  // ─── Phase 7: V2 Compaction Hook (best-effort) ───────────────────
@@ -3197,7 +3197,7 @@ function Sidebar(props) {
3197
3197
  setProp(_el$12, "width", "100%");
3198
3198
  setProp(_el$12, "padding", 1);
3199
3199
  setProp(_el$13, "attributes", 1);
3200
- insert(_el$13, `Pantheon v1.6.2-beta.15`);
3200
+ insert(_el$13, `Pantheon v1.6.2-beta.16`);
3201
3201
  insert(_el$14, () => presetHeaderLine(model.preset().name ?? "", model.provider()));
3202
3202
  insert(_el$12, createComponent(Show, {
3203
3203
  get when() {
@@ -3918,7 +3918,7 @@ function HomeStatus(props) {
3918
3918
  const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base;
3919
3919
  return (() => {
3920
3920
  var _el$72 = createElement("text");
3921
- insert(_el$72, () => `Pantheon v1.6.2-beta.15${preset().name ? ` ▸ ${preset().name}` : ""}`);
3921
+ insert(_el$72, () => `Pantheon v1.6.2-beta.16${preset().name ? ` ▸ ${preset().name}` : ""}`);
3922
3922
  effect((_$p) => setProp(_el$72, "fg", muted(), _$p));
3923
3923
  return _el$72;
3924
3924
  })();
@@ -167,7 +167,7 @@ async function detectVersion(api) {
167
167
  if (ver) return ver;
168
168
  }
169
169
  } catch {}
170
- return "1.6.2-beta.15";
170
+ return "1.6.2-beta.16";
171
171
  }
172
172
  /**
173
173
  * usage-bar — AI subscription usage gauge for the opencode TUI.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pantheon-tui",
3
- "version": "1.6.2-beta.15",
3
+ "version": "1.6.2-beta.16",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pantheon-tui",
9
- "version": "1.6.2-beta.15",
9
+ "version": "1.6.2-beta.16",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@opencode-ai/plugin": "1.18.33",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pantheon-tui",
3
3
  "type": "module",
4
- "version": "1.6.2-beta.15",
4
+ "version": "1.6.2-beta.16",
5
5
  "description": "Pantheon TUI plugin — V1 rich sidebar and usage gauges; native V2 status, session and delegation sidebar",
6
6
  "license": "MIT",
7
7
  "engines": {