pantheon-opencode 1.7.0-beta.1 → 2.0.0-beta.1

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 (168) hide show
  1. package/AGENTS.global.md +2 -2
  2. package/AGENTS.md +3 -3
  3. package/CHANGELOG.md +86 -1
  4. package/README.md +90 -45
  5. package/README.pt-BR.md +19 -19
  6. package/bin/pantheon-init.mjs +11 -48
  7. package/package.json +9 -13
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +7 -6
  11. package/scripts/{check-plugin-v2-coverage.mjs → check-plugin-coverage.mjs} +7 -7
  12. package/scripts/{decision-router-v2-budget.mjs → decision-router-budget-gates.mjs} +1 -1
  13. package/scripts/{decision-router-v2-egress.mjs → decision-router-egress.mjs} +1 -1
  14. package/scripts/decision-router.mjs +2 -2
  15. package/scripts/docs-media.mjs +1 -1
  16. package/scripts/doctor.mjs +225 -136
  17. package/scripts/install/behavior-overrides.bundle.mjs +123 -0
  18. package/scripts/install/{v2-capabilities.mjs → capabilities.mjs} +7 -7
  19. package/scripts/install/config-migration.mjs +60 -253
  20. package/scripts/install/file-inventory.mjs +6 -4
  21. package/scripts/install/interactive.mjs +9 -2
  22. package/scripts/install/opencode-state.mjs +13 -12
  23. package/scripts/install/opencode-version.mjs +97 -162
  24. package/scripts/install/opencode.mjs +271 -428
  25. package/scripts/install/plan.mjs +1 -9
  26. package/scripts/install/plugin.mjs +19 -35
  27. package/scripts/install/shared.mjs +40 -1
  28. package/scripts/package-evidence.mjs +1 -4
  29. package/scripts/probe-pantheon-cost.mjs +1 -1
  30. package/scripts/reconcile.mjs +5 -7
  31. package/scripts/release-gates.mjs +38 -58
  32. package/scripts/setup-v2-config.mjs +10 -8
  33. package/scripts/setup.mjs +12 -22
  34. package/scripts/sync-tui.mjs +9 -17
  35. package/scripts/{test-opencode-v2-sandbox.sh → test-opencode-sandbox.sh} +9 -9
  36. package/scripts/update-skills-lock.mjs +24 -12
  37. package/scripts/update.mjs +17 -1
  38. package/scripts/validate-routing.mjs +79 -4
  39. package/scripts/validate-sandbox-install.mjs +3 -3
  40. package/skills-lock.json +25 -8
  41. package/src/agents/zeus.md +1 -0
  42. package/src/pantheon/behavior-overrides.ts +191 -0
  43. package/src/pantheon/{v2-bounded-read.ts → bounded-read.ts} +1 -1
  44. package/src/pantheon/cost-command.ts +1 -1
  45. package/src/pantheon/{v2-decision-contracts.ts → decision-contracts.ts} +3 -3
  46. package/src/pantheon/{v2-decision-points → decision-points}/p1-agent.ts +3 -3
  47. package/src/pantheon/{v2-decision-points → decision-points}/p10-claims.ts +2 -2
  48. package/src/pantheon/{v2-decision-points → decision-points}/p11-catalog.ts +2 -2
  49. package/src/pantheon/{v2-decision-points → decision-points}/p2-skill.ts +3 -3
  50. package/src/pantheon/{v2-decision-points → decision-points}/p3-complexity.ts +6 -6
  51. package/src/pantheon/{v2-decision-points → decision-points}/p4-memory.ts +2 -2
  52. package/src/pantheon/{v2-decision-points → decision-points}/p5-themis-verify.ts +2 -2
  53. package/src/pantheon/{v2-decision-points → decision-points}/p6-council.ts +3 -3
  54. package/src/pantheon/{v2-decision-points → decision-points}/p7-loop.ts +5 -5
  55. package/src/pantheon/{v2-decision-points → decision-points}/p8-guardrail.ts +2 -2
  56. package/src/pantheon/{v2-decision-points → decision-points}/p9-memory-compaction.ts +2 -2
  57. package/src/pantheon/{v2-decision-points.ts → decision-points.ts} +5 -5
  58. package/src/pantheon/{v2-decision-policy.ts → decision-policy.ts} +2 -2
  59. package/src/pantheon/{v2-decision-prompt-surface.ts → decision-prompt-surface.ts} +3 -3
  60. package/src/pantheon/{v2-decision-registry.ts → decision-registry.ts} +10 -13
  61. package/src/pantheon/{v2-decision-resource-ids.ts → decision-resource-ids.ts} +1 -1
  62. package/src/pantheon/{v2-decision-shadow.ts → decision-shadow.ts} +1 -1
  63. package/src/pantheon/{v2-decision-telemetry.ts → decision-telemetry.ts} +1 -1
  64. package/src/pantheon/{v2-execute-after.ts → execute-after.ts} +4 -4
  65. package/src/pantheon/goal-store.ts +7 -0
  66. package/src/pantheon/{v2-hook-engine.ts → hook-engine.ts} +3 -3
  67. package/src/pantheon/jev-decision-tool.ts +3 -3
  68. package/src/pantheon/jev-decisions.ts +12 -6
  69. package/src/pantheon/jev-escalation.ts +6 -6
  70. package/src/pantheon/jev-quality-score.ts +2 -2
  71. package/src/pantheon/jev-rank-verify.ts +2 -2
  72. package/src/pantheon/jev-risk-gate.ts +4 -4
  73. package/src/pantheon/local-decision-agents.ts +1 -1
  74. package/src/pantheon/local-decision-router.ts +1 -1
  75. package/src/pantheon/local-decision-tool.ts +2 -2
  76. package/src/pantheon/local-orchestration.ts +1 -1
  77. package/src/pantheon/model-command.ts +1 -1
  78. package/src/pantheon/{v2-vision.ts → native-vision.ts} +12 -15
  79. package/src/pantheon/pantheon-decision-catalog.ts +12 -0
  80. package/src/pantheon/{v2-shell-hooks.ts → shell-hooks.ts} +4 -4
  81. package/src/pantheon/{v2-tools.ts → tools.ts} +4 -4
  82. package/src/pantheon/{v2-unsupported.d.mts → unsupported.d.mts} +3 -3
  83. package/src/pantheon/{v2-unsupported.mjs → unsupported.mjs} +8 -8
  84. package/src/pantheon/update-notifier.ts +101 -0
  85. package/src/pantheon/vision-local.ts +12 -3
  86. package/src/pantheon/vision.ts +120 -2
  87. package/src/{plugin-v2 → plugin}/index.ts +7 -7
  88. package/src/plugin.ts +2875 -500
  89. package/src/plugins/hook-runner.ts +3 -3
  90. package/src/plugins/tui/dist/server.d.ts +23 -9
  91. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  92. package/src/plugins/tui/dist/server.js +25 -12
  93. package/src/plugins/tui/dist/server.js.map +1 -1
  94. package/src/plugins/tui/dist/tui.d.ts +1023 -494
  95. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  96. package/src/plugins/tui/dist/tui.js +4841 -2066
  97. package/src/plugins/tui/dist/tui.js.map +1 -1
  98. package/src/plugins/tui/{index-v2.ts → index.ts} +1 -1
  99. package/src/plugins/tui/package-lock.json +2 -42
  100. package/src/plugins/tui/package.json +4 -10
  101. package/src/plugins/tui/src/cost-data.ts +1 -1
  102. package/src/plugins/tui/src/index.tsx +4222 -2822
  103. package/src/plugins/tui/src/pantheon-settings-state.ts +111 -0
  104. package/src/plugins/tui/src/pantheon-settings.tsx +236 -0
  105. package/src/plugins/tui/src/server.ts +23 -10
  106. package/src/plugins/tui/src/update-notice.ts +86 -0
  107. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  108. package/src/plugins/tui/tsdown.config.ts +3 -5
  109. package/src/plugins/tui/tui.ts +1 -2
  110. package/src/routing.yml +36 -0
  111. package/src/skills/README.md +16 -1
  112. package/src/skills/artifact-management/SKILL.md +10 -67
  113. package/src/skills/artifact-management/references/artifact-templates.md +71 -0
  114. package/src/skills/auto-continue/SKILL.md +10 -0
  115. package/src/skills/code-review-checklist/SKILL.md +11 -44
  116. package/src/skills/code-review-checklist/references/review-checklists.md +54 -0
  117. package/src/skills/instruction-forge/SKILL.md +57 -0
  118. package/src/skills/instruction-forge/references/agents-md-doctrine.md +50 -0
  119. package/src/skills/instruction-forge/references/eval-doctrine.md +37 -0
  120. package/src/skills/instruction-forge/references/skill-doctrine.md +62 -0
  121. package/src/skills/memory-bank/SKILL.md +11 -90
  122. package/src/skills/memory-bank/references/anti-patterns.md +33 -0
  123. package/src/skills/memory-bank/references/product-adoption.md +19 -0
  124. package/src/skills/memory-bank/references/storage-model.md +21 -0
  125. package/src/skills/memory-bank/references/structure-and-frequency.md +44 -0
  126. package/src/skills/reflect/SKILL.md +1 -0
  127. package/src/skills/session-goal/SKILL.md +7 -54
  128. package/src/skills/session-goal/references/goal-format.md +26 -0
  129. package/src/skills/session-goal/references/session-reuse.md +44 -0
  130. package/src/skills/tdd-with-agents/SKILL.md +11 -101
  131. package/src/skills/tdd-with-agents/references/advanced-testing-patterns.md +58 -0
  132. package/src/skills/tdd-with-agents/references/testing-by-layer.md +60 -0
  133. package/src/skills/visual-review-pipeline/SKILL.md +11 -120
  134. package/src/skills/visual-review-pipeline/references/findings-schema.md +49 -0
  135. package/src/skills/visual-review-pipeline/references/workflow-steps.md +111 -0
  136. package/scripts/hooks/log-session-start.sh +0 -48
  137. package/scripts/hooks/validate-post-conditions.sh +0 -21
  138. package/scripts/hooks/validate-talos-scope.sh +0 -50
  139. package/scripts/hooks/validate-tool-safety.sh +0 -49
  140. package/src/pantheon/goal-loop.ts +0 -314
  141. package/src/pantheon/idle-continuation.ts +0 -52
  142. package/src/pantheon/todo-preserve.ts +0 -301
  143. package/src/pantheon/tool-ceiling.ts +0 -159
  144. package/src/pantheon/v2-bridge.ts +0 -153
  145. package/src/plugin-v2.ts +0 -2954
  146. package/src/plugins/pantheon-hooks.ts +0 -1433
  147. package/src/plugins/tui/dist/server-v2.d.ts +0 -30
  148. package/src/plugins/tui/dist/server-v2.d.ts.map +0 -1
  149. package/src/plugins/tui/dist/server-v2.js +0 -33
  150. package/src/plugins/tui/dist/server-v2.js.map +0 -1
  151. package/src/plugins/tui/dist/tui-v2.d.ts +0 -1039
  152. package/src/plugins/tui/dist/tui-v2.d.ts.map +0 -1
  153. package/src/plugins/tui/dist/tui-v2.js +0 -4597
  154. package/src/plugins/tui/dist/tui-v2.js.map +0 -1
  155. package/src/plugins/tui/src/index-v2.tsx +0 -4496
  156. package/src/plugins/tui/src/server-v2.ts +0 -28
  157. package/src/plugins/tui/tui-v2.ts +0 -2
  158. /package/src/pantheon/{v2-decision-budget.ts → decision-budget.ts} +0 -0
  159. /package/src/pantheon/{v2-decision-egress.ts → decision-egress.ts} +0 -0
  160. /package/src/pantheon/{v2-decision-events.ts → decision-events.ts} +0 -0
  161. /package/src/pantheon/{v2-decision-heuristic.ts → decision-heuristic.ts} +0 -0
  162. /package/src/pantheon/{v2-decision-premises.ts → decision-premises.ts} +0 -0
  163. /package/src/pantheon/{v2-decision-rank.ts → decision-rank.ts} +0 -0
  164. /package/src/pantheon/{v2-decision-verify.ts → decision-verify.ts} +0 -0
  165. /package/src/pantheon/{v2-delegation-enforce.ts → delegation-policy.ts} +0 -0
  166. /package/src/pantheon/{v2-model-overrides.ts → model-overrides.ts} +0 -0
  167. /package/src/pantheon/{v2-native-decisions.ts → native-decisions.ts} +0 -0
  168. /package/src/plugins/tui/src/{opencode-v2.d.ts → opencode.d.ts} +0 -0
package/src/plugin.ts CHANGED
@@ -1,557 +1,2932 @@
1
- import type { Plugin, PluginInput } from '@opencode-ai/plugin'
2
- import type { PluginConfig } from 'opencode'
3
- import { createCommandNormalizer } from './pantheon/command-normalizer.ts'
1
+ /**
2
+ * Pantheon V2 Plugin — full orchestration plugin for OpenCode V2.
3
+ *
4
+ * Registers:
5
+ * - 4 unconditional self-sufficient tools via V2 tool.transform (hashline_edit,
6
+ * pantheon_cost, pantheon_model, pantheon_local_decision) plus up to 2 host-dependent ones: native
7
+ * `vision_describe` when the host exposes the V2 model catalog (it resolves
8
+ * OpenCode Zen auth and sends images directly to the selected multimodal
9
+ * model), and `pantheon_bounded_read` when the host exposes its permission
10
+ * and session APIs (root Zeus sessions only).
11
+ * `pantheon_local_decision` is advisory and rejects execution unless the
12
+ * host tool context identifies the caller as Zeus.
13
+ * The goal tools need V1 infrastructure and are absent from this surface.
14
+ * - 5 event subscriptions (session.created, idle, deleted, error, compacted)
15
+ * - Session hooks (prompt, context, compaction)
16
+ * - A tool `execute.before` hook that ENFORCES read-only sessions: the agent
17
+ * arrives on the host's event, a read-only agent (apollo/gaia) registers its
18
+ * session, and the shared `createEnforcementGuard` throws to deny
19
+ * `hashline_edit` / `pantheon_model` / `edit` / `write` / `bash` / `task`.
20
+ * See `registerV2ToolHooks`.
21
+ * - The SAME `execute.before` hook runs scripts/hooks/scan-secrets.sh over the
22
+ * tool input and throws on exit 2 (high-confidence token match). This is the
23
+ * ONLY hard security block on the V2 surface. It is wired HERE, not delegated
24
+ * to `src/plugins/pantheon-hooks.ts`: opencode.json declares only
25
+ * `src/plugin` in `plugins`, so the V1 plugin never loads on a V2-only
26
+ * install and V1's identical block was inert by construction.
27
+
28
+ * - A tool `execute.after` hook and a permission hook, with permission
29
+ * evaluation enforcing the caller/target matrix for Pantheon agents
30
+ *
31
+ * Every tool registered through `draft.add` MUST declare `output`, and its
32
+ * `execute` MUST resolve to a value carrying `output`. The host enforces the
33
+ * two as a pair — see `V2ToolDraft` for the exact contract.
34
+ *
35
+ * ## The host domains the SDK types do not carry
36
+ *
37
+ * `@opencode-ai/plugin` 1.18.33 types `PluginContext` as exactly:
38
+ * options · agent · aisdk · catalog · command · integration · plugin ·
39
+ * reference · skill
40
+ * — no `tool`, `event`, `permission` or `session`. The pin does not carry
41
+ * them, and the `latest` release (`1.19.4`, 2026-10-22) restructures the
42
+ * package instead of typing them, so following the newest SDK release does
43
+ * not resolve this: it is a STRUCTURAL DECLARATION task, not a pin
44
+ * reconciliation.
45
+ *
46
+ * A live opencode 2.0.22+ host DOES have these domains, with the shapes this module
47
+ * uses. Measured by `tests/canary/plugin-tool-canary.test.mjs`, which loads
48
+ * this file through the real loader and records `Object.keys(ctx)` from inside
49
+ * the host:
50
+ *
51
+ * agent aisdk app command event experimental generate integration location
52
+ * mcp model options permission plugin provider reference rpc session shell
53
+ * skill storage tool vcs websearch worktree
54
+ *
55
+ * ctx.tool.transform function
56
+ * ctx.tool.hook function
57
+ * ctx.tool.list function
58
+ * ctx.event.subscribe function
59
+ * ctx.permission.hook function
60
+ * ctx.session.hook function
61
+ * ctx.catalog absent
62
+ *
63
+ * `HostPluginContext` below declares exactly the minimum of that, and
64
+ * `hostDomains` is the SINGLE documented cast that reaches them — replacing the
65
+ * six repeated `as unknown as Record<string, unknown>` casts this file carried
66
+ * (Phases 2, 3, 4, 5, 6 and 7 — every phase except Phase 1, which reads the
67
+ * SDK-typed domains directly), each of which type-checked nothing at all. The
68
+ * per-domain definition checks stay: `registerV2Tools` still returns `false`
69
+ * and marks `tool-transform` when `ctx.tool.transform` is missing, and likewise
70
+ * for the others. The cast is not a licence to assume: the canary above is what
71
+ * proves the domains exist on a real host, and it fails if they stop existing.
72
+ *
73
+ * If the SDK ever exposes these host domains, replacing `hostDomains` with the real
74
+ * type is a one-line change. Do NOT make that change while 1.18.x lacks them.
75
+ *
76
+ * The separate offline native Decisions scaffold is typed against
77
+ * `@opencode/plugin@2.2.5`. It intentionally has no production call site and
78
+ * does not claim native Decisions support for V1 or OpenCode V2.0/2.1. The
79
+ * legacy plugin registrations are not migrated as part of that scaffold.
80
+ *
81
+ * V2_UNSUPPORTED_FEATURES distinguishes adapter limitations from observed
82
+ * host-absent APIs; setup handles optional registrations on a best-effort basis.
83
+ *
84
+ * @module plugin
85
+ */
86
+
87
+ import { appendFileSync, mkdirSync } from 'node:fs'
88
+ import { realpath as realpathAsync } from 'node:fs/promises'
89
+ import path from 'node:path'
90
+ import { fileURLToPath } from 'node:url'
91
+ import type {
92
+ AgentDraft,
93
+ CommandDraft,
94
+ PluginContext,
95
+ ReferenceDraft,
96
+ } from '@opencode-ai/plugin/v2/promise'
97
+ import { define } from '@opencode-ai/plugin/v2/promise'
98
+ import {
99
+ type EffectiveOverrides,
100
+ installDecision,
101
+ isRuntimeDisabled,
102
+ mergeOverrides,
103
+ } from './pantheon/behavior-overrides.ts'
104
+ import {
105
+ BOUNDED_READ_TOOL,
106
+ createV2BoundedReadTool,
107
+ type V2BoundedReadOriginRegistry,
108
+ } from './pantheon/bounded-read.ts'
4
109
  import { buildCompactionContext } from './pantheon/compaction-context.ts'
5
110
  import {
6
- type ContextSandboxConfig,
7
- createContextSandbox,
8
- resolveSandboxConfig,
9
- DEFAULT_CONFIG as SANDBOX_DEFAULT_CONFIG,
10
- DEFAULT_LIMITS as SANDBOX_DEFAULT_LIMITS,
11
- } from './pantheon/context-sandbox.ts'
12
- import { createCostCommand } from './pantheon/cost-command.ts'
111
+ CONTEXT_PRUNER_CONFIG_KEYS,
112
+ describeContextPrunerConfigIssues,
113
+ type PruneSite,
114
+ type PruneStats,
115
+ pruneMessages,
116
+ resolveContextPrunerConfig,
117
+ } from './pantheon/context-pruner.ts'
118
+ import { createP7LoopPoint, p7LoopEnabledFromEnv } from './pantheon/decision-points/p7-loop.ts'
119
+ import {
120
+ createP8Guardrail,
121
+ p8GuardrailEnabledFromEnv,
122
+ } from './pantheon/decision-points/p8-guardrail.ts'
123
+ import { evaluateCompactionMemoryPoint } from './pantheon/decision-points/p9-memory-compaction.ts'
124
+ import { evaluateCatalogPoint } from './pantheon/decision-points/p11-catalog.ts'
125
+ import { DECISION_POINT_REGISTRY } from './pantheon/decision-points.ts'
126
+ import { observePromptSurface } from './pantheon/decision-prompt-surface.ts'
127
+ import { createTelemetrySink, type TelemetrySink } from './pantheon/decision-telemetry.ts'
13
128
  import {
14
129
  createEnforcementGuard,
130
+ normalizeDelegationAgent,
15
131
  readOnlyRegistry,
16
- SessionHierarchyRegistry,
17
132
  syncReadOnlySession,
133
+ type ToolExecuteBeforeInput,
134
+ type ToolExecuteBeforeOutput,
18
135
  zeusReadGuard,
19
136
  } from './pantheon/delegation-enforce.ts'
20
- import { GOAL_LOOP_DEFAULTS, GoalLoop, GoalStore } from './pantheon/goal-loop.ts'
137
+ import {
138
+ type AuthoritativeSession,
139
+ evaluateV2Delegation,
140
+ PANTHEON_AGENTS,
141
+ type V2PermissionEvent,
142
+ V2SubagentOriginRegistry,
143
+ v2ResourceTarget,
144
+ } from './pantheon/delegation-policy.ts'
145
+ import { createV2ExecuteAfter, resolveV2SandboxConfig } from './pantheon/execute-after.ts'
146
+ import { GOAL_LOOP_DEFAULTS, GoalStore } from './pantheon/goal-store.ts'
21
147
  import { createGuardPathResolver } from './pantheon/guard-path.ts'
22
- import { createReadEnhancer } from './pantheon/hashline/read-enhancer.ts'
23
- import { createHashlineEditTool } from './pantheon/hashline/tool.ts'
24
- import { createIdleDispatcher } from './pantheon/idle-continuation.ts'
25
- import { createLocalDecisionTool } from './pantheon/local-decision-tool.ts'
26
- import { createPantheonLogger } from './pantheon/logger.ts'
27
- import { createModelCommand } from './pantheon/model-command.ts'
28
- import { pantheonPluginOnce } from './pantheon/plugin-once.ts'
29
- import { applyActivePresetToConfig } from './pantheon/presets.mjs'
30
- import { safeSessionPath } from './pantheon/session-guard.ts'
148
+ import { runSecretScanInProcess } from './pantheon/hook-engine.ts'
149
+ import { createJTelemetryMirror } from './pantheon/j-telemetry-file.ts'
150
+ import {
151
+ approvalInputHash,
152
+ hasApproval,
153
+ isAffirmativeAnswer,
154
+ j1ApprovalMarker,
155
+ mintApproval,
156
+ } from './pantheon/j1-approvals.ts'
157
+ import type { V2JevDecisionRuntime } from './pantheon/jev-decision-tool.ts'
158
+ import { specialistCallerAllowlist } from './pantheon/jev-decision-tool.ts'
159
+ import {
160
+ createJ3EscalationObserver,
161
+ isSubagentDispatchEvent,
162
+ j3EscalationEnabledFromEnv,
163
+ } from './pantheon/jev-escalation.ts'
164
+ import {
165
+ createJ1RiskGateObserver,
166
+ isRiskGateTarget,
167
+ type J1Verdict,
168
+ j1EnforceThresholdFromEnv,
169
+ j1ModeFromEnv,
170
+ } from './pantheon/jev-risk-gate.ts'
171
+ import { DECISION_EGRESS_ACTION } from './pantheon/local-decision-egress-gate.ts'
172
+ import { applyDecisionRouterToPrompt } from './pantheon/local-decision-prompt.ts'
173
+ import { applyV2ModelOverrides, readV2ModelConfiguration } from './pantheon/model-overrides.ts'
174
+ import type { NativeDecisionRequest } from './pantheon/native-decisions.ts'
175
+ import { buildV2VisionPromptContext, type V2VisionRuntime } from './pantheon/native-vision.ts'
31
176
  import { getSharedBoard } from './pantheon/shared-board.ts'
32
- import { createTaskResultGuard } from './pantheon/task-result-guard.ts'
177
+ import { createV2ShellHooks, type V2ShellRunner } from './pantheon/shell-hooks.ts'
33
178
  import {
34
179
  TODO_ENFORCER_DEFAULTS,
35
180
  TodoEnforcer,
181
+ type TodoEnforcerChild,
36
182
  type TodoEnforcerClient,
183
+ type TodoEnforcerMessage,
184
+ type TodoLike,
37
185
  todoEnforcerEnabledFromEnv,
38
186
  } from './pantheon/todo-enforcer.ts'
39
- import { TodoPreserver } from './pantheon/todo-preserve.ts'
40
- import { handleToolCeilingEvent, type ToolCeilingResult } from './pantheon/tool-ceiling.ts'
41
- import { checkTuiVersionStaleness } from './pantheon/tui-version-check.ts'
42
- import { createV2Bridge, registerV2Bridge } from './pantheon/v2-bridge.ts'
43
- import { activePresetCandidates, createVisionHandler } from './pantheon/vision.ts'
44
-
45
- // ─── Background Job Board Singleton ────────────────────────────────────
46
-
47
- // Silence-by-default TUI policy (pantheon-hooks L42-58): console output in a
48
- // plugin writes to the process stdout/stderr, which the opencode TUI renders
49
- // directly into the terminal — the "lixo". Every line goes to
50
- // .pantheon/logs/hooks.log; the console echo is opt-in via PANTHEON_HOOKS_LOG=1.
51
- const log = createPantheonLogger({ module: 'pantheon-plugin' })
52
-
53
- // beta.5: the board is a PROCESS-wide singleton (getSharedBoard) shared with
54
- // src/plugins/pantheon-hooks.ts, whose native-task mirror registers children
55
- // here. globalThis anchoring dedupes the npm+repo double load.
56
- const board = getSharedBoard()
57
- board
58
- .recoverRunningJobs()
59
- .catch((err) => log.error('[Pantheon Plugin] Failed to recover running jobs:', err))
60
- // ─── Phase 3: Board terminal audit log ─────────────────────────────────
61
-
62
- // The onTerminal listener is the completion AUDIT point: it writes a
63
- // file-only log line (console echo opt-in via PANTHEON_HOOKS_LOG). There is
64
- // deliberately NO chat delivery — the user policy is zero delegation
65
- // notifications in the transcript. Completion visibility lives in the board
66
- // `[unread]` marker and the TUI toasts owned by pantheon-hooks
67
- // (PANTHEON_TOASTS gate).
68
- board.onTerminal((taskID: string) => {
69
- const job = board.get(taskID)
70
- if (!job) return
71
- log.info(
72
- `[Pantheon Plugin] Board terminal: [${job.alias}] ${job.description} → ${job.state}${job.resultSummary ? ` — ${job.resultSummary}` : ''}`,
187
+ import { createV2ToolDefinitions, type V2ToolResult } from './pantheon/tools.ts'
188
+ import { UNSUPPORTED_FEATURE_SEED } from './pantheon/unsupported.mjs'
189
+ import { sanitizeVisionHistory } from './pantheon/vision.ts'
190
+ import type { HookPayload, HookResult } from './plugins/hook-runner.ts'
191
+
192
+ // ─── Unsupported Features Registry ───────────────────────────────────────
193
+
194
+ /**
195
+ * Features not implemented by the current Pantheon V2 adapter or absent from
196
+ * the observed host. A listed feature is not necessarily a host-absent API.
197
+ * Additional features are appended during setup when a required API is missing.
198
+ */
199
+ /**
200
+ * Live unsupported-feature list: the shared seed plus anything `markUnsupported`
201
+ * appends while this process talks to a real host.
202
+ *
203
+ * The seed lives in `src/pantheon/unsupported.mjs` — a plain-`.mjs` module —
204
+ * so that the V2 installer and `scripts/doctor.mjs` report the SAME strings
205
+ * without either of them having to import TypeScript. This array stays a
206
+ * mutable copy rather than the shared seed itself: `markUnsupported` appends to
207
+ * it, and the seed must stay frozen. `getUnsupportedFeatures()` still returns
208
+ * this exact reference.
209
+ */
210
+ export const V2_UNSUPPORTED_FEATURES: string[] = [...UNSUPPORTED_FEATURE_SEED]
211
+
212
+ // ─── Constants ───────────────────────────────────────────────────────────
213
+
214
+ const POLICY_MARKER = '<!-- pantheon-v2-policy -->'
215
+ const POLICY = `${POLICY_MARKER}\nFollow Pantheon routing policy: delegate implementation work to the named specialist and do not claim work was performed without verification.`
216
+
217
+ /** 2.0.16 `system` on a session hook payload is `Array<SystemPart>`. */
218
+ interface SystemPart {
219
+ type: 'text'
220
+ text: string
221
+ }
222
+
223
+ function isTextPart(entry: unknown): entry is SystemPart {
224
+ return (
225
+ typeof entry === 'object' &&
226
+ entry !== null &&
227
+ typeof (entry as { text?: unknown }).text === 'string'
73
228
  )
74
- })
229
+ }
75
230
 
76
- // Periodically prune terminal/reconciled jobs (24h TTL, every 30 min).
77
- // pruneExpired is async and internally swallows persistence errors, so the
78
- // void-catch here is purely defensive. .unref() ensures the timer never
79
- // keeps the process alive on its own.
80
- setInterval(
81
- () => {
82
- void board
83
- .pruneExpired(86_400_000)
84
- .catch((err: unknown) => log.error('[Pantheon Plugin] Background board prune failed:', err))
85
- },
86
- 30 * 60 * 1000,
87
- ).unref()
231
+ /**
232
+ * Extract text from a `system` entry. The host's own coercion accepts a bare
233
+ * string, but the canonical 2.0.16 shape is `{ type: 'text', text }`; the
234
+ * string branch is retained so the handler still works against a host that
235
+ * sends primitives. Never throws.
236
+ */
237
+ function systemEntryText(entry: unknown): string | null {
238
+ try {
239
+ if (typeof entry === 'string') return entry
240
+ if (isTextPart(entry)) return entry.text
241
+ return null
242
+ } catch {
243
+ return null
244
+ }
245
+ }
88
246
 
89
- // ─── Phase 4: Read-Only Enforcement + Compaction Context ───────────────
247
+ function hasPolicyMarker(arr: unknown[]): boolean {
248
+ try {
249
+ return arr.some((s) => {
250
+ const t = systemEntryText(s)
251
+ return t?.includes(POLICY_MARKER) ?? false
252
+ })
253
+ } catch {
254
+ return false
255
+ }
256
+ }
90
257
 
91
- // WS1 (PR #94): root-session predicate shared by the Phase 4 enforcement
92
- // guard and the native delegate toolset — both must agree on what a root is.
93
- // (Hoisted function: `rootSessions`/`sessionHierarchy` below are resolved at
94
- // call time, after module init.)
95
- function isRootSession(sessionID: string): boolean {
96
- return rootSessions.has(sessionID) || sessionHierarchy.isRoot(sessionID)
258
+ /**
259
+ * Normalize a `system` value to the 2.0.16 `Array<SystemPart>` shape.
260
+ *
261
+ * `SessionContext.system` is `Array<SystemPart>` where a part is
262
+ * `{ type: 'text', text }`. A raw string (the whole value, or an element) is
263
+ * not that shape, so it is upgraded: element strings become parts, and a bare
264
+ * string value becomes a one-element part array. Non-array, non-string values
265
+ * are returned unchanged.
266
+ *
267
+ * Returns the normalized array, or `null` when `system` is neither a string
268
+ * nor an array (nothing to normalize).
269
+ */
270
+ function normalizeSystemToParts(system: unknown): unknown[] | null {
271
+ if (typeof system === 'string') {
272
+ return [{ type: 'text', text: system } satisfies SystemPart]
273
+ }
274
+ if (!Array.isArray(system)) return null
275
+ for (let i = 0; i < system.length; i++) {
276
+ const entry = system[i]
277
+ if (typeof entry === 'string') {
278
+ system[i] = { type: 'text', text: entry } satisfies SystemPart
279
+ }
280
+ }
281
+ return system
97
282
  }
98
283
 
99
- // The read-only registry is populated by the chat.params hook below, when a
100
- // session's active agent is read-only (apollo/gaia — READ_ONLY_AGENTS /
101
- // syncReadOnlySession). The guard denies edit/write/bash/task/hashline_edit
102
- // inside those sessions by throwing from tool.execute.before; unknown sessions
103
- // are allowed (safe default).
104
- const enforcementGuard = createEnforcementGuard({
105
- getReadOnlySessions: () => readOnlyRegistry.sessionIDs(),
106
- options: {
107
- getSessionAgent: (sessionID) => sessionAgents.get(sessionID),
108
- isRootSession,
109
- isChildSession: (sessionID) => sessionHierarchy.isChild(sessionID),
110
- logger: log,
111
- },
112
- })
284
+ /** Set once, so a payload without a `system` channel warns once per process. */
285
+ let compactionChannelWarned = false
113
286
 
114
- // Fase 1 (command-normalizer): deterministic `python` → `python3` rewrite for
115
- // `bash` commands (PEP 394 — Ubuntu 20.04+ has no bare `python`). Unlike the
116
- // enforcement guard above (which THROWS to deny), this guard REWRITES the
117
- // command in place and lets it run. Logs every rewrite + `python -c` warning
118
- // to the shared hooks.log for @nyx frequency measurement.
119
- const commandNormalizer = createCommandNormalizer({ logger: log })
120
-
121
- // Root-session registry for the read-only enforcement guard: sessions created
122
- // without a parentID are roots. Populated from TWO sources:
123
- // 1. the `session.created` event hook (live roots — fires for sessions
124
- // created while the plugin runs);
125
- // 2. a fail-open startup seed from client.session.list() in the config
126
- // hook (compaction-134) — opencode does NOT replay session.created
127
- // events for sessions that exist before plugin load, so without the
128
- // seed a resumed root would never enter this set after a restart.
129
- // The guard treats unknown sessions as roots, so this set is an enrichment
130
- // that improves accuracy but is never required for correctness.
131
- const rootSessions = new Set<string>()
132
- const sessionHierarchy = new SessionHierarchyRegistry()
133
- const sessionAgents = new Map<string, string>()
134
- const sessionToolCeilings = new Map<string, ToolCeilingResult>()
135
-
136
- /** Pure helper: collect the IDs of root sessions (parentID === undefined). */
137
- function collectRootSessionIDs(
138
- sessions: ReadonlyArray<{ id: string; parentID?: string }>,
139
- ): Set<string> {
140
- const roots = new Set<string>()
141
- for (const session of sessions) {
142
- if (session.parentID === undefined) roots.add(session.id)
143
- }
144
- return roots
145
- }
146
-
147
- /**
148
- * Seed resumed root sessions without making OpenCode startup depend on the
149
- * session API responding. Some OpenCode environments do not have the API
150
- * ready while plugin config hooks run; awaiting session.list() there leaves
151
- * the TUI stuck before it can open. The enforcement guard treats an unknown
152
- * session as a root, so this enrichment is deliberately best-effort.
153
- */
154
- function seedRootSessionsInBackground(input: PluginInput): void {
155
- // Fail-open: environments without the session API (client.session absent or
156
- // not yet wired while config hooks run) must NOT break startup. `session`
157
- // is captured and the method invoked on it so `this` stays bound; the
158
- // delegation layer already treats unknown sessions as roots, so skipping
159
- // the seed is always safe.
160
- const session = input.client.session
161
- if (typeof session?.list !== 'function') return
162
- sessionHierarchy.beginSeed()
163
- void session
164
- .list()
165
- .then((result) => {
166
- if (!result.error && Array.isArray(result.data)) {
167
- sessionHierarchy.completeSeed(result.data)
168
- const seeded = collectRootSessionIDs(result.data)
169
- if (seeded.size > 0) {
170
- for (const id of seeded) rootSessions.add(id)
171
- log.info(`[Pantheon Plugin] Seeded ${seeded.size} root session(s) from session.list`)
172
- }
173
- } else {
174
- sessionHierarchy.failSeed()
287
+ /** Set once, so a failed enforcer construction logs one line per process. */
288
+ let idleEnforcerFailureLogged = false
289
+
290
+ /**
291
+ * Append text blocks to a hook payload's `system` channel.
292
+ *
293
+ * Returns `false` when the payload carries no usable channel (absent, or a
294
+ * shape that is neither string nor array) — the caller decides whether that is
295
+ * worth a diagnostic. A bare-string `system` is replaced by its part array on
296
+ * the payload itself, because the host reads the property, not our copy.
297
+ *
298
+ * Used by the V2 compaction hook (#266) to inject the compaction context
299
+ * blocks V1 pushes into `output.context`.
300
+ */
301
+ function appendSystemBlocks(
302
+ target: { system?: unknown } | null | undefined,
303
+ blocks: readonly string[],
304
+ ): boolean {
305
+ if (target == null || blocks.length === 0) return false
306
+ const normalized = normalizeSystemToParts(target.system)
307
+ if (normalized == null) return false
308
+ if (typeof target.system === 'string') target.system = normalized
309
+ for (const block of blocks) normalized.push({ type: 'text', text: block } satisfies SystemPart)
310
+ return true
311
+ }
312
+
313
+ /**
314
+ * Add a feature to the unsupported list (idempotent).
315
+ */
316
+ function markUnsupported(feature: string): void {
317
+ if (!V2_UNSUPPORTED_FEATURES.includes(feature)) {
318
+ V2_UNSUPPORTED_FEATURES.push(feature)
319
+ }
320
+ }
321
+
322
+ // ─── Host context domains the SDK types do not carry ────────────────────
323
+
324
+ /**
325
+ * The minimal shape of `ctx.tool` this module uses, as a live opencode 2.0.22
326
+ * host provides it. `transform` registers the Pantheon tools, `hook` installs
327
+ * the `execute.before`/`execute.after` guards, `list` is the host-built
328
+ * descriptor dump the canary asserts on.
329
+ */
330
+ interface V2ToolDomain {
331
+ transform?: (cb: (draft: V2ToolDraft) => void) => Promise<unknown>
332
+ hook?: (name: string, handler: (event: unknown) => void | Promise<void>) => Promise<unknown>
333
+ list?: () => Promise<unknown>
334
+ }
335
+
336
+ /** The minimal shape of `ctx.event`: one async-iterable subscription. */
337
+ interface V2EventDomain {
338
+ subscribe?: (opts?: { signal?: AbortSignal }) => AsyncIterable<V2SessionEvent>
339
+ }
340
+
341
+ /**
342
+ * The minimal shape of `ctx.permission`.
343
+ *
344
+ * The V2.0.25 live contract supplies an `evaluate` event with `resources`;
345
+ * runtime validation remains defensive because SDK declarations omit this
346
+ * domain and the host may evolve independently.
347
+ */
348
+ interface V2PermissionDomain {
349
+ assert?: (input: Record<string, unknown>) => Promise<unknown>
350
+ hook?: (
351
+ name: string,
352
+ handler: (event: unknown, output?: unknown) => void | Promise<void>,
353
+ ) => Promise<unknown>
354
+ }
355
+
356
+ /**
357
+ * The minimal shape of `ctx.session` used by this module. `get` follows the V2
358
+ * Promise API's object input (`{ sessionID }`); session hooks accept any string
359
+ * and silently drop an unknown one, which is why the host-backed hook canary
360
+ * exists.
361
+ */
362
+ interface V2SessionDomain {
363
+ hook?: (name: string, handler: (event: unknown) => void | Promise<void>) => Promise<unknown>
364
+ get?: (input: { sessionID: string }) => Promise<unknown>
365
+ }
366
+
367
+ interface V2LocationDomain {
368
+ directory?: string
369
+ project?: { id?: string }
370
+ }
371
+
372
+ interface V2ModelDomain {
373
+ list?: V2VisionRuntime['model']['list']
374
+ }
375
+
376
+ interface V2GenerateDomain {
377
+ text?: (input: { model: { providerID: string; id: string }; prompt: string }) => Promise<unknown>
378
+ }
379
+
380
+ /**
381
+ * The host's experimental generation domain. Only `decisions` is declared: the
382
+ * native Jev route feature-detects it, and every other member stays unknown.
383
+ */
384
+ interface V2ExperimentalDomain {
385
+ generate?: {
386
+ decisions?: (request: NativeDecisionRequest) => Promise<unknown>
387
+ }
388
+ }
389
+
390
+ /** `PluginContext` plus the host domains 1.18.x omits. See the module header. */
391
+ interface HostPluginContext extends PluginContext {
392
+ tool?: V2ToolDomain
393
+ event?: V2EventDomain
394
+ permission?: V2PermissionDomain
395
+ session?: V2SessionDomain
396
+ model?: V2ModelDomain
397
+ generate?: V2GenerateDomain
398
+ experimental?: V2ExperimentalDomain
399
+ location?: V2LocationDomain
400
+ }
401
+
402
+ /**
403
+ * THE cast to the host's context. Every optional member stays optional and every
404
+ * caller re-checks before use, so this narrows nothing away: it replaces five
405
+ * anonymous `Record<string, unknown>` casts with one named, documented,
406
+ * type-checked boundary.
407
+ *
408
+ * When the SDK ships these four domains, delete this function and use
409
+ * `PluginContext` directly.
410
+ */
411
+ function hostDomains(context: PluginContext): HostPluginContext {
412
+ return context as HostPluginContext
413
+ }
414
+
415
+ // ─── Idle todo enforcer ────────────────────────────────────────────────
416
+
417
+ /**
418
+ * Module-level todo enforcer, set at plugin setup by
419
+ * `installV2TodoEnforcer`. Event handlers receive no context, so it lives
420
+ * here for the process lifetime. Stays `undefined` when the host session
421
+ * domain lacks the methods the enforcer needs — reported via the
422
+ * `idle-todo-enforcer` marker.
423
+ */
424
+ let idleTodoEnforcer: TodoEnforcer | undefined
425
+
426
+ /**
427
+ * Named-behavior overrides loaded at setup (project `.pantheon/overrides.json`
428
+ * wins over the global config dir's `pantheon-overrides.json`). Runtime gates
429
+ * consult `isGateDisabled` before wiring; an override file that cannot be
430
+ * read or parsed degrades to no overrides (built-in behavior), never to a
431
+ * partial parse.
432
+ */
433
+ let runtimeOverrides: EffectiveOverrides = {}
434
+ let runtimeOverridesLoaded = false
435
+
436
+ function loadRuntimeOverrides(): void {
437
+ if (runtimeOverridesLoaded) return
438
+ runtimeOverridesLoaded = true
439
+ try {
440
+ const read = (path: string): string | undefined => {
441
+ const fs = require('node:fs') as typeof import('node:fs')
442
+ try {
443
+ return fs.readFileSync(path, 'utf8')
444
+ } catch {
445
+ return undefined
175
446
  }
176
- })
177
- .catch((err) => {
178
- sessionHierarchy.failSeed()
179
- log.warn('[Pantheon Plugin] Root session seed failed (fail-open):', err)
180
- })
447
+ }
448
+ const path = require('node:path') as typeof import('node:path')
449
+ const globalRaw = read(path.join(resolveGlobalOverrideDir(), 'pantheon-overrides.json'))
450
+ const projectRaw = read(path.join(process.cwd(), '.pantheon', 'overrides.json'))
451
+ runtimeOverrides = mergeOverrides(globalRaw, projectRaw).entries
452
+ } catch {
453
+ runtimeOverrides = {}
454
+ }
455
+ }
456
+
457
+ function resolveGlobalOverrideDir(): string {
458
+ const env = process.env.XDG_CONFIG_HOME
459
+ const base = env && env.startsWith('/') ? env : path.join(process.env.HOME ?? '', '.config')
460
+ return path.join(base, 'opencode')
461
+ }
462
+
463
+ /** True when a runtime gate behavior is disabled by override. */
464
+ function gateDisabled(behaviorId: string): boolean {
465
+ return runtimeOverrides[behaviorId]?.action === 'disable'
181
466
  }
182
467
 
183
- /** Extract the SDK error message ({name, data: {message}}) or a fallback. */
184
- function sdkErrorMessage(error: { data?: { message?: string } } | null | undefined): string {
185
- const message = error?.data?.message
186
- return typeof message === 'string' && message.trim() !== '' ? message : 'request failed'
468
+ /**
469
+ * The subset of the host's `session` domain a `TodoEnforcerClient` needs.
470
+ *
471
+ * Declared structurally and checked at runtime instead of being added to
472
+ * {@link V2SessionDomain} on faith: the measured 2.1.4 host exposes
473
+ * `hook`/`get`/`list`/`create`/`remove`/`prompt`/`generate`/`interrupt` on that
474
+ * domain. Its `prompt` takes `{ sessionID, text }` and is a DIFFERENT call from
475
+ * V1's `promptAsync({ path, body: { agent?, model?, parts } })` — the enforcer's
476
+ * agent/model inheritance has no V2 counterpart — and whether it exposes
477
+ * `todo`/`messages`/`children` at all is not measured by the repository. The
478
+ * check below therefore requires the V1 shape exactly: a client built on a
479
+ * method that is absent (or on a same-named method with a different contract)
480
+ * would throw inside the enforcer's fail-open guards and leave idle
481
+ * continuation silently dead again — the exact defect this wiring closes.
482
+ */
483
+ interface V2TodoSessionMethods {
484
+ todo?: (input: { path: { id: string } }) => Promise<unknown>
485
+ messages?: (input: { path: { id: string } }) => Promise<unknown>
486
+ children?: (input: { path: { id: string } }) => Promise<unknown>
487
+ promptAsync?: (input: { path: { id: string }; body: Record<string, unknown> }) => Promise<unknown>
187
488
  }
188
489
 
490
+ const V2_TODO_CLIENT_METHODS = ['todo', 'messages', 'children', 'promptAsync'] as const
491
+
189
492
  /**
190
- * Adapt the opencode SDK client to the structural TodoEnforcerClient the
191
- * todo enforcer expects: unwraps the SDK `{data, error, request, response}`
192
- * result and surfaces errors as throws (the enforcer swallows + logs them,
193
- * so the event hook can never break the session).
493
+ * Adapt the host's `session` domain to the {@link TodoEnforcerClient} the V1
494
+ * enforcer instance expects, or `undefined` when the domain does not carry the
495
+ * four methods. The input shape is V1's (`{ path: { id } }`) because the
496
+ * enforcer is the V1 instance — this is an adapter, not a second enforcer.
194
497
  */
195
- function adaptTodoEnforcerClient(client: PluginInput['client']): TodoEnforcerClient {
498
+ function createV2TodoEnforcerClient(
499
+ session: V2SessionDomain | undefined,
500
+ ): TodoEnforcerClient | undefined {
501
+ if (session === undefined) return undefined
502
+ const methods = session as V2TodoSessionMethods
503
+ for (const method of V2_TODO_CLIENT_METHODS) {
504
+ if (typeof methods[method] !== 'function') return undefined
505
+ }
506
+ // Every method is present: the guard above is the only place absence is
507
+ // tolerated, so the assertions below cannot fire at runtime.
508
+ const todo = methods.todo as NonNullable<V2TodoSessionMethods['todo']>
509
+ const messages = methods.messages as NonNullable<V2TodoSessionMethods['messages']>
510
+ const children = methods.children as NonNullable<V2TodoSessionMethods['children']>
511
+ const promptAsync = methods.promptAsync as NonNullable<V2TodoSessionMethods['promptAsync']>
196
512
  return {
197
513
  session: {
198
- todo: async (input) => {
199
- const path = safeSessionPath(input.path.id)
200
- if (!path) {
201
- log.warn(`[Pantheon Plugin] todo skipped: invalid sessionID "${input.path.id}"`)
202
- return []
203
- }
204
- const result = await client.session.todo({ path: path.path })
205
- if (result.error) throw new Error(sdkErrorMessage(result.error))
206
- return result.data
207
- },
208
- messages: async (input) => {
209
- const path = safeSessionPath(input.path.id)
210
- if (!path) {
211
- log.warn(`[Pantheon Plugin] messages skipped: invalid sessionID "${input.path.id}"`)
212
- return []
213
- }
214
- const result = await client.session.messages({ path: path.path })
215
- if (result.error) throw new Error(sdkErrorMessage(result.error))
216
- return result.data
217
- },
218
- children: async (input) => {
219
- const path = safeSessionPath(input.path.id)
220
- if (!path) {
221
- log.warn(`[Pantheon Plugin] children skipped: invalid sessionID "${input.path.id}"`)
222
- return []
223
- }
224
- const result = await client.session.children({ path: path.path })
225
- if (result.error) throw new Error(sdkErrorMessage(result.error))
226
- return result.data
227
- },
228
- promptAsync: async (input) => {
229
- const path = safeSessionPath(input.path.id)
230
- if (!path) {
231
- log.warn(`[Pantheon Plugin] promptAsync skipped: invalid sessionID "${input.path.id}"`)
232
- throw new Error(`invalid sessionID: ${input.path.id}`)
233
- }
234
- const result = await client.session.promptAsync({ path: path.path, body: input.body })
235
- if (result.error) throw new Error(sdkErrorMessage(result.error))
236
- return result.data
237
- },
514
+ todo: (input) => todo.call(session, input) as Promise<TodoLike[]>,
515
+ messages: (input) => messages.call(session, input) as Promise<TodoEnforcerMessage[]>,
516
+ children: (input) => children.call(session, input) as Promise<TodoEnforcerChild[]>,
517
+ promptAsync: (input) => promptAsync.call(session, input),
238
518
  },
239
519
  }
240
520
  }
241
521
 
242
522
  /**
243
- * Pantheon plugin for OpenCode. Pasted images are intercepted via the
244
- * `chat.message` hook (proven to fire in opencode 1.18.11). Credentials follow
245
- * the endpoint: a Zen endpoint (`opencode` / `opencode-go*`) may use the shared
246
- * `PANTHEON_OPENCODE_API_KEY` / `OPENCODE_API_KEY` env keys and the legacy
247
- * `opencode-go` / `opencode` auth-store entries, while a non-Zen endpoint uses
248
- * ONLY its own auth-store entry (never the Zen env keys or legacy entries).
249
- * When a credential is available the image is described NATIVELY by the
250
- * multimodal model via the endpoint's OpenAI-compatible API, and replaced with
251
- * the text description — no MCP tool required. Without a credential the legacy
252
- * pattern applies: the image is replaced with a text instruction telling the
253
- * model to call a vision MCP tool (default `pantheon_vision_vision_describe`).
254
- * Either way the image never reaches the main provider, so text-only models
255
- * cannot fail with an `image_url` error.
256
- *
257
- * The canonical `pantheon-vision` MCP owns the standalone describe/OCR/analyze
258
- * tools. The installed OpenCode plugin API exposes no stable pre-provider
259
- * message hook (1.18.11 only exposes the experimental history transform), so
260
- * that transform is retained as the runtime-compatible fallback. If a stable
261
- * provider-bound hook is added, register the same sanitizer there instead of
262
- * assuming this experimental hook is guaranteed to run.
263
- *
264
- * IMPORTANT (OpenCode 1.18.11 legacy loader): this module must export EXACTLY
265
- * ONE function-valued export — the default plugin. The legacy loader does
266
- * `Object.values(mod)` and invokes every function export as a plugin factory;
267
- * any named function export (e.g. a re-exported helper like
268
- * generateInjectionPrompt) is called with a PluginInput object and can throw.
269
- * Helpers live in src/pantheon/vision.ts and are imported from there directly.
270
- */
271
- const plugin: Plugin = async (input: PluginInput) => {
272
- // release-134: runtime guard against DOUBLE registration (duplicate toasts +
273
- // duplicate task_ids in one process — 2026-08-12 live logs). opencode
274
- // merges the global config (npm-package plugin paths) with the project
275
- // config (repo source paths), so this module loads from TWO filesystem
276
- // paths in the same process and the factory would otherwise run twice. The
277
- // second invocation becomes a no-op: an empty hooks object (every Hooks
278
- // field is optional) → hooks/tools register exactly once.
279
- if (pantheonPluginOnce('pantheon:plugin')) {
280
- return {}
281
- }
282
- // Runtime TUI version staleness check — warns if the copied TUI plugin
283
- // is older than the installed package. Runs once, fail-open, no auto-sync.
284
- checkTuiVersionStaleness((msg) => log.warn(msg))
285
- // Symlink resolution for the Zeus read guard (#272). The guard predicate is
286
- // pure and synchronous, so the filesystem work happens here instead: one
287
- // resolver per plugin instance, rooted at the project directory the host
288
- // reported. `docs/link → ../src` must not read `src/` just because the
289
- // string path looks harmless.
290
- const resolveGuardPath = createGuardPathResolver(
291
- input.directory || input.worktree || process.cwd(),
292
- )
293
- const vision = createVisionHandler(input)
294
- // Wave 1 (PR #46): TODO continuation enforcer for root sessions. The event
295
- // hook routes `session.idle` events here; an active goal owns the idle
296
- // (goal loop), otherwise the todo enforcer re-injects. Runtime kill-switch:
297
- // PANTHEON_TODO_ENFORCER=off (routing.yml is a doc mirror only — the env var
298
- // is the real switch, PANTHEON_TOASTS pattern).
299
- const todoEnforcer = new TodoEnforcer({
300
- client: adaptTodoEnforcerClient(input.client),
301
- board,
302
- options: { ...TODO_ENFORCER_DEFAULTS, enabled: todoEnforcerEnabledFromEnv() },
303
- })
523
+ * Construct the idle-path singletons, V2-native (no V1 plugin): the shared
524
+ * background-job board and the todo enforcer. The enforcer exists only when
525
+ * the host session domain exposes the four methods it needs — otherwise the
526
+ * `idle-todo-enforcer` reduction is marked and stays part of the seed.
527
+ *
528
+ * Stored module-level (event handlers get no context) and returned to
529
+ * setup, so the compaction hook lists pending todos with the same instance.
530
+ */
531
+ function installV2TodoEnforcer(context: PluginContext): TodoEnforcer | undefined {
532
+ const todoClient = createV2TodoEnforcerClient(hostDomains(context).session)
533
+ if (todoClient === undefined) markUnsupported('idle-todo-enforcer')
534
+ const board = getSharedBoard()
535
+ const todoEnforcer =
536
+ todoClient === undefined
537
+ ? undefined
538
+ : new TodoEnforcer({
539
+ client: todoClient,
540
+ board,
541
+ options: { ...TODO_ENFORCER_DEFAULTS, enabled: todoEnforcerEnabledFromEnv() },
542
+ })
543
+ idleTodoEnforcer = todoEnforcer
544
+ return todoEnforcer
545
+ }
304
546
 
305
- // release-134 Phase 3: post-compaction todo restore. Captures the session's
306
- // todo list in 'experimental.session.compacting', activates the snapshot on
307
- // 'session.compacted', and rewrites the first post-compaction `todowrite`
308
- // with the exact list (todo-preserve.ts). Additive + fail-open: every step
309
- // degrades to a logged warn, never throws in a hook.
310
- const todoPreserver = new TodoPreserver({
311
- client: adaptTodoEnforcerClient(input.client),
312
- })
547
+ // ─── V2 Transform Functions ─────────────────────────────────────────────
548
+
549
+ function transformAgents(draft: AgentDraft): void {
550
+ // Beta 19192 guard (issue #92): draft may not have `list`, or list()
551
+ // may return a non-iterable. Never throw — mark unsupported and return.
552
+ let agents: Iterable<{ id: string }>
553
+ try {
554
+ const maybeList = (draft as unknown as { list?: unknown }).list
555
+ if (typeof maybeList !== 'function') {
556
+ markUnsupported('agent-transform-list')
557
+ return
558
+ }
559
+ const result = (maybeList as (this: unknown) => unknown).call(draft)
560
+ if (
561
+ result == null ||
562
+ typeof (result as { [Symbol.iterator]?: unknown })[Symbol.iterator] !== 'function'
563
+ ) {
564
+ markUnsupported('agent-transform-list')
565
+ return
566
+ }
567
+ agents = result as Iterable<{ id: string }>
568
+ } catch {
569
+ markUnsupported('agent-transform-list')
570
+ return
571
+ }
572
+ try {
573
+ const modelConfiguration = readV2ModelConfiguration()
574
+ if (modelConfiguration.warnings.length > 0) {
575
+ // The V2 server PluginContext has no documented user-visible notification
576
+ // or logging channel; preserve the degradation for status diagnostics.
577
+ markUnsupported('agent-model-overrides')
578
+ }
579
+ applyV2ModelOverrides(draft, modelConfiguration.overrides)
580
+ } catch {
581
+ // Model configuration is optional. Preserve host models if it cannot be read.
582
+ markUnsupported('agent-model-overrides')
583
+ }
584
+ try {
585
+ for (const agent of agents) {
586
+ draft.update(agent.id, (current) => {
587
+ // Beta 19192 hardening + SystemPart SKIP: `system` may be a non-string
588
+ // (host shape drift, e.g. object). `?.` covers only null/undefined, not
589
+ // wrong types — guard with typeof. String path preserved; empty/absent
590
+ // degrades to POLICY; truthy non-string OBJECT is SKIPPED (preserve host
591
+ // shape, avoid schema validation failure). Other primitives degrade to
592
+ // POLICY. Never throw.
593
+ try {
594
+ const sys: unknown = (current as { system?: unknown }).system
595
+ if (typeof sys === 'string' && sys.includes(POLICY_MARKER)) {
596
+ // Policy already present — nothing to do.
597
+ } else if (typeof sys === 'string' && sys) {
598
+ current.system = `${sys}\n\n${POLICY}`
599
+ } else if (sys == null || sys === '') {
600
+ current.system = POLICY
601
+ } else if (typeof sys === 'object') {
602
+ // Host object shape (e.g. SystemPart): SKIP instead of overwriting.
603
+ } else {
604
+ current.system = POLICY
605
+ }
606
+ } catch {
607
+ // Fail-open: leave agent untouched on unexpected shape.
608
+ }
609
+ if (agent.id === 'zeus') current.mode = 'primary'
610
+ })
611
+ }
612
+ } catch {
613
+ markUnsupported('agent-transform')
614
+ }
615
+ }
616
+
617
+ function transformCommands(draft: CommandDraft): void {
618
+ // Beta 19192 guard (issue #92): draft may not have `list`, or list()
619
+ // may return a non-iterable. Never throw — mark unsupported and return.
620
+ let commands: Iterable<{ name: string }>
621
+ try {
622
+ const maybeList = (draft as unknown as { list?: unknown }).list
623
+ if (typeof maybeList !== 'function') {
624
+ markUnsupported('command-transform-list')
625
+ return
626
+ }
627
+ const result = (maybeList as (this: unknown) => unknown).call(draft)
628
+ if (
629
+ result == null ||
630
+ typeof (result as { [Symbol.iterator]?: unknown })[Symbol.iterator] !== 'function'
631
+ ) {
632
+ markUnsupported('command-transform-list')
633
+ return
634
+ }
635
+ commands = result as Iterable<{ name: string }>
636
+ } catch {
637
+ markUnsupported('command-transform-list')
638
+ return
639
+ }
640
+ try {
641
+ for (const command of commands) {
642
+ if (command.name.startsWith('pantheon-')) {
643
+ draft.update(command.name, (current) => {
644
+ current.description ??= 'Pantheon orchestration command'
645
+ })
646
+ }
647
+ }
648
+ } catch {
649
+ markUnsupported('command-transform')
650
+ }
651
+ }
313
652
 
314
- // Wave 3 (PR #46): goal loop. The plugin uses hard-coded GOAL_LOOP_DEFAULTS;
315
- // routing.yml documents defaults/guards but no runtime config enables the
316
- // loop in this build. File-based GoalStore
317
- // (`.pantheon/goals/<sessionID>.json` — the plugin layer cannot reach MCP
318
- // KV). Idle routing: an active goal owns the idle (goal loop); otherwise
319
- // the todo enforcer gets it (see idle-continuation.ts).
320
- const goalStore = new GoalStore({ dir: '.pantheon/goals' })
321
- const goalLoop = new GoalLoop({
322
- store: goalStore,
323
- client: adaptTodoEnforcerClient(input.client),
324
- board,
325
- options: GOAL_LOOP_DEFAULTS,
653
+ function transformReferences(draft: ReferenceDraft): void {
654
+ draft.add('pantheon-agents', {
655
+ type: 'local',
656
+ path: fileURLToPath(new URL('../AGENTS.md', import.meta.url)),
657
+ description: 'Pantheon agent and execution policy',
326
658
  })
327
- const goalTools = goalLoop.tools()
328
- const idleDispatcher = createIdleDispatcher({ goalLoop, todoEnforcer })
329
-
330
- // Cross-generation bridge (issue #265 review): publish THESE singletons so a
331
- // V2 plugin loaded in the same process reuses this enforcer instead of
332
- // building a second one. Two enforcers would answer one `session.idle` twice
333
- // — V1's dispatcher below and V2's `onSessionIdle` would each inject a
334
- // continuation prompt. Registration is a no-op on a V1-only install: nothing
335
- // in this process reads the registry unless a V2 entry resolves it.
336
- registerV2Bridge(createV2Bridge({ board, todoEnforcer }))
337
-
338
- // Wave 2 (PR #46): hashline — tag-anchored edits. The read enhancer
339
- // (tool.execute.after) augments `read` output with per-line sha256 tags
340
- // (`12#XJ|content`); hashline_edit anchors edits to those refs. Additive —
341
- // the plugin has no tool.execute.after yet, and pantheon-hooks.ts (a
342
- // separate plugin instance) keeps its own. Mirrors routing.yml `hashline`.
343
- const hashlineEdit = createHashlineEditTool()
344
- const readEnhancer = createReadEnhancer()
345
-
346
- // Context Window Optimization (v2 P0) — tool output sandboxing
347
- // Pure truncation hook: read/grep/glob/webfetch → head + [TRUNCATED] + tail
348
- // Fail-open: never throws, disabled via opencode.json context_sandbox.enabled
349
- const sandboxConfig: ContextSandboxConfig = {
350
- enabled: SANDBOX_DEFAULT_CONFIG.enabled,
351
- limits: {
352
- read: { ...SANDBOX_DEFAULT_LIMITS.read },
353
- grep: { ...SANDBOX_DEFAULT_LIMITS.grep },
354
- glob: { ...SANDBOX_DEFAULT_LIMITS.glob },
355
- webfetch: { ...SANDBOX_DEFAULT_LIMITS.webfetch },
659
+ }
660
+
661
+ // ─── V2 Tool Registration ───────────────────────────────────────────────
662
+
663
+ /**
664
+ * Construct the ONE Jev runtime the plugin threads everywhere: the explicit
665
+ * `pantheon_jev_decide` tool and the J1 risk-score shadow observer both call
666
+ * through this instance, so `decide` and `permissionAssert` are bound to their
667
+ * owning host domains exactly once. `undefined` when the host lacks either the
668
+ * native Decisions API or the model catalog (the route no longer consults the
669
+ * catalog, but the tool registration contract still feature-detects both).
670
+ */
671
+ function buildV2JevRuntime(host: ReturnType<typeof hostDomains>): V2JevDecisionRuntime | undefined {
672
+ const specialistCallers = specialistCallerAllowlist(process.env.PANTHEON_JEV_SPECIALIST_CALLERS)
673
+ const decisionsFn = host.experimental?.generate?.decisions
674
+ const modelListFn = host.model?.list
675
+ if (typeof decisionsFn !== 'function' || typeof modelListFn !== 'function') return undefined
676
+ const decisionsOwner = host.experimental?.generate
677
+ const decide = decisionsFn
678
+ const listModels = modelListFn
679
+ // The 2.2.5 host exposes ctx.skill as the SkillEditor (list()); the SDK
680
+ // types this file sees declare skill as the registration hook, so the
681
+ // runtime shape is read through one narrow, feature-detected cast.
682
+ const skillDomain = (host as { skill?: { list?: () => unknown } }).skill
683
+ const skillList = skillDomain?.list
684
+ const permissionAssertFn = host.permission?.assert
685
+ const permissionAssert =
686
+ typeof permissionAssertFn === 'function'
687
+ ? (input: Record<string, unknown>) => permissionAssertFn.call(host.permission, input)
688
+ : undefined
689
+ // The J4 output-quality review telemetry sink (jev-quality-score.ts): the
690
+ // review mode of `pantheon_jev_decide` records ONE observer-style shadow
691
+ // record per run (q-token or skip token) through the in-memory, bounded 0b
692
+ // path (`createTelemetrySink`, no I/O), carrying `mode: 'shadow'`. The sink
693
+ // is created per runtime build so it always matches the runtime that holds
694
+ // it; the records are advisory and never read back by the tool path.
695
+ const j4Sink = createTelemetrySink()
696
+ j4TelemetrySink = j4Sink
697
+ const j4Mirror = createJTelemetryMirror({ enabled: true })
698
+ return {
699
+ specialistCallers,
700
+ // Every host method is invoked with its owning domain as receiver: the
701
+ // canary records `ctx.model.list()` (bound) succeeding on 2.2.5 while a
702
+ // detached reference threw in the field and surfaced only as
703
+ // CATALOG_UNAVAILABLE. Same discipline as permissionAssert above.
704
+ listModels: () => listModels.call(host.model),
705
+ decide: (request: NativeDecisionRequest) => decide.call(decisionsOwner, request),
706
+ // Sync-or-async host skill list; absent/throwing falls back to the
707
+ // catalog-only preset inside the tool.
708
+ listSkills: async () => skillList?.call(skillDomain),
709
+ ...(permissionAssert === undefined ? {} : { permissionAssert }),
710
+ shadowSink: (record) => {
711
+ const shadowRecord = { ...record, mode: 'shadow' }
712
+ j4Sink.emit(shadowRecord)
713
+ j4Mirror?.record(shadowRecord)
356
714
  },
357
715
  }
358
- const sandboxHandler = createContextSandbox(sandboxConfig)
359
- // Task Result Guard (2026-09-10): detect empty task() results from native
360
- // opencode subagent calls and convert to explicit errors. Runs FIRST in the
361
- // chain so the error message is visible even if later handlers skip.
362
- const taskResultGuard = createTaskResultGuard()
363
- const combinedAfter: typeof readEnhancer = async (input, output) => {
364
- await taskResultGuard(input, output)
365
- await sandboxHandler(input, output)
366
- await readEnhancer(input, output)
716
+ }
717
+
718
+ /**
719
+ * Attempt to register Pantheon tools via V2 ctx.tool.transform.
720
+ *
721
+ * The V2 tool.transform API (when available) provides:
722
+ * draft.namespace({ name: "pantheon", description: "..." })
723
+ * draft.add({ name, description, input, output, execute })
724
+ *
725
+ * `output` is part of the required shape, not an optional extra: see
726
+ * `V2ToolDraft` for the host contract that makes it mandatory.
727
+ *
728
+ * Returns true if tools were registered, false if the API is unavailable.
729
+ */
730
+ async function registerV2Tools(
731
+ context: PluginContext,
732
+ boundedRead?: ReturnType<typeof createV2BoundedReadTool>['definition'],
733
+ jevRuntime?: V2JevDecisionRuntime,
734
+ ): Promise<boolean> {
735
+ const host = hostDomains(context)
736
+ const toolCtx = host.tool
737
+
738
+ if (!toolCtx?.transform) {
739
+ return false
367
740
  }
368
741
 
369
- // Wave 4 (PR #46): /cost — delegation cost + token visibility. Reads
370
- // opencode.db read-only via the single node:sqlite backend. Fully wired.
371
- const costCommand = createCostCommand()
372
- const modelCommand = createModelCommand()
373
- const localDecisionTool = createLocalDecisionTool()
742
+ try {
743
+ // Tool definitions carry their own `output` declaration; the draft requires
744
+ // it, and the host rejects a definition whose result shape cannot satisfy
745
+ // the declaration it makes.
746
+ const model = host.model
747
+ const modelListFn = model?.list
748
+ const visionReady = typeof modelListFn === 'function'
749
+ if (!visionReady) markUnsupported('vision-tool')
750
+ const visionRuntime = visionReady ? ({ model } as V2VisionRuntime) : undefined
751
+ // The native Jev tool needs BOTH the V2 model catalog (route resolution)
752
+ // and the host's native Decisions API. A host without either simply does
753
+ // not get the tool — same feature-detect discipline as vision_describe.
754
+ const decisionsFn = host.experimental?.generate?.decisions
755
+ const jevReady = visionReady && typeof decisionsFn === 'function'
756
+ if (!jevReady) markUnsupported('jev-decision-tool')
757
+ // The setup flow threads the ONE runtime instance it built (shared with
758
+ // the J1 observer in the execute.before hook); this local fallback keeps a
759
+ // direct registration call self-sufficient.
760
+ const runtime = jevRuntime ?? (jevReady ? buildV2JevRuntime(host) : undefined)
761
+ // P3 (complexity) declares `tool.invoke`; its construction site is the
762
+ // local selector's execute, fed by that tool's own input schema. The sink
763
+ // is the 0b record path (in-memory, bounded, I/O-free) and every record
764
+ // carries `mode: 'shadow'` — the mode the registry declares.
765
+ const p3Sink = createTelemetrySink()
766
+ p3TelemetrySink = p3Sink
767
+ const toolDefs = createV2ToolDefinitions(
768
+ visionRuntime,
769
+ {
770
+ complexitySink: (record) => {
771
+ p3Sink.emit({ ...record, mode: 'shadow' })
772
+ },
773
+ },
774
+ runtime,
775
+ )
776
+ if (boundedRead !== undefined) toolDefs.push(boundedRead)
777
+
778
+ // P11's record sink, created per registration (in-memory, bounded, I/O-free).
779
+ const p11Sink = createTelemetrySink()
780
+ p11TelemetrySink = p11Sink
374
781
 
375
- return {
376
- config: async (config: PluginConfig) => {
377
- // compaction-134 seed: opencode does NOT replay `session.created`
378
- // events for sessions that exist before plugin load, so after a
379
- // restart the resumed ROOT session never enters rootSessions and the
380
- // read-only enforcement guard would misclassify it. Seed the registry
381
- // from session.list() in the background — every session WITHOUT a
382
- // parentID is a root. Fail-open: a failed/throttled list leaves the set
383
- // untouched (the guard treats unknown sessions as roots), and config
384
- // setup must never wait for the session API.
385
- // Context sandbox config — opencode.json → context_sandbox: {enabled, limits}
386
- try {
387
- const raw = (config as unknown as Record<string, unknown>).context_sandbox
388
- const resolved = resolveSandboxConfig(raw)
389
- sandboxConfig.enabled = resolved.enabled
390
- sandboxConfig.limits = resolved.limits
391
- } catch {
392
- // fail-open: keep defaults
782
+ await toolCtx.transform((draft: V2ToolDraft) => {
783
+ // Catalog grouping only. The host computes a tool's registration id as
784
+ // `options.namespace === undefined ? name : `${namespace}_${name}``, and
785
+ // `draft.namespace()` does NOT set `options.namespace` on later `add`
786
+ // calls — so the tools stay `hashline_edit` / `pantheon_cost` /
787
+ // `pantheon_model`, not `pantheon_*`. That bare name is what the
788
+ // enforcement guard's blocked-tool list matches on; see
789
+ // `adaptV2ExecuteBeforeEvent`.
790
+ draft.namespace({ name: 'pantheon', description: 'Pantheon orchestration tools' })
791
+ for (const def of toolDefs) {
792
+ draft.add({
793
+ name: def.name,
794
+ description: def.description,
795
+ input: def.input,
796
+ // Required by the host contract: without this the tool fails on
797
+ // every call with "Tool result declared output without an output
798
+ // schema". Must stay paired with def.execute resolving to `output`.
799
+ output: def.output,
800
+ execute: def.execute,
801
+ })
393
802
  }
394
- seedRootSessionsInBackground(input)
395
- config.agentsPath = config.agentsPath ?? []
396
- config.agentsPath.push(new URL('./agents', import.meta.url).pathname)
397
- config.skillsPaths = config.skillsPaths ?? []
398
- config.skillsPaths.push(new URL('./skills', import.meta.url).pathname)
399
-
400
- // Apply the active model preset (`init --preset` / `set-tier` write
401
- // .pantheon/active-preset.json): resolve it with the SAME candidate
402
- // order the vision handler uses (project > XDG > HOME) and mutate the
403
- // agent models / reasoning effort / fallback models + provider configs.
404
- // Fail-safe: without an active preset the config is untouched; a missing
405
- // provider key is logged and skipped — the hook must never break startup
406
- // (set-tier already fail-fast validates keys at write time). Vision
407
- // rotation stays in vision.ts, which resolves its model independently.
803
+
804
+ // P11 (catalog) shadow observation on the only measured catalogue
805
+ // surface: the draft the host hands this callback — `{list, get,
806
+ // namespace, add, update, remove}`, 20 host tools, 46 with MCP servers
807
+ // registered (F-07). `ctx.catalog` is absent at every measured point
808
+ // (F-05) and is not used. The adapter reads and nothing else: `list()` is
809
+ // called, the six members are type-checked, and no add/update/remove is
810
+ // ever invoked, so the registration above is the only mutation. Shadow
811
+ // has no responder, so the record names the validated `choice` question
812
+ // (`catalog.no.answer`) instead of inventing a selection. Runs after the
813
+ // adds so the draft it reads is the one the host will keep.
408
814
  try {
409
- const resolved = applyActivePresetToConfig(config, {
410
- candidates: activePresetCandidates(),
815
+ evaluateCatalogPoint(draft, (record) => {
816
+ p11Sink.emit({ ...record, mode: 'shadow' })
411
817
  })
412
- if (resolved) {
413
- log.info(`[Pantheon Plugin] Applied model preset: ${resolved.name} (${resolved.source})`)
414
- }
415
818
  } catch {
416
- // Fully STATIC warning — the thrown error object is tainted because
417
- // presets.mjs constructs it with the provider's apiKeyEnv name (e.g.
418
- // PANTHEON_OPENCODE_API_KEY), and CodeQL's clear-text logging dataflow
419
- // flags ANY interpolation derived from it — including err.name and
420
- // err.message. The env var name is not itself sensitive to log, but
421
- // the scanner cannot distinguish it, so nothing derived from the error
422
- // may appear here. Diagnostics (provider id + env var) are already
423
- // emitted by applyActivePresetToConfig's own logger before it throws.
424
- // The catch binding is intentionally omitted so no tainted value can
425
- // ever reach this log line (CodeQL alert #11).
426
- log.warn('[plugin] preset application failed (see logs for details)')
427
- }
428
- },
429
- // Plugin tool surface: tag-anchored edits (hashline_edit), the full-auto
430
- // goal loop, /cost and /pantheon-model management.
431
- tool: {
432
- hashline_edit: hashlineEdit,
433
- // Wave 3 (PR #46): full-auto goal tools (single active goal/session).
434
- pantheon_goal_create: goalTools.pantheon_goal_create,
435
- pantheon_goal_update: goalTools.pantheon_goal_update,
436
- pantheon_goal_get: goalTools.pantheon_goal_get,
437
- // Wave 4 (PR #46): /cost — delegation cost report from opencode.db.
438
- pantheon_cost: costCommand.pantheon_cost,
439
- // Deterministic /pantheon-model management of top-level model fields.
440
- pantheon_model: modelCommand.pantheon_model,
441
- // Local advisory routing; execute() requires the host's Zeus agent context.
442
- pantheon_local_decision: localDecisionTool,
443
- },
444
- 'chat.message': async (hookInput, output) => {
445
- await vision.chatMessage(hookInput, output)
446
- // No delegation notification delivery here — the user policy is ZERO
447
- // notification text injected into the chat transcript.
448
- // Wave 1: a user message is activity — the todo enforcer's
449
- // user-activity gate skips injection for userActivityQuietMs afterwards.
450
- todoEnforcer.noteUserActivity(hookInput.sessionID)
451
- },
452
- 'chat.params': async (hookInput) => {
453
- // The SDK exposes the active agent here; tool.execute.before has no
454
- // agent field. Never infer identity from a prompt or tool name.
455
- sessionAgents.set(hookInput.sessionID, hookInput.agent)
456
- // Phase 4: chat.params is the ONLY hook with the active agent, so this
457
- // is where the read-only registry is populated — apollo/gaia sessions
458
- // must be denied edit/write/bash/task/hashline_edit by the guard.
459
- syncReadOnlySession(readOnlyRegistry, hookInput.sessionID, hookInput.agent)
460
- },
461
- 'experimental.chat.messages.transform': vision.messagesTransform,
462
- event: async ({ event: ev }) => {
463
- // Phase 3: sessions created without a parent are roots for the depth guard.
464
- if (ev.type === 'session.created') {
465
- const info = ev.properties.info
466
- if (info) {
467
- sessionHierarchy.register(info)
468
- if (info.parentID === undefined) rootSessions.add(info.id)
469
- }
470
- }
471
- // Phase 4: a deleted session must not leave a read-only registration
472
- // (or cached agent identity) behind.
473
- if (ev.type === 'session.deleted') {
474
- readOnlyRegistry.unregister(ev.properties.info.id)
475
- sessionAgents.delete(ev.properties.info.id)
476
- }
477
- // release-134 Phase 3: activate the todo snapshot captured at
478
- // compacting time — the first todowrite within the restore window is
479
- // rewritten with the exact list (see todo-preserve.ts). Fail-open.
480
- if (ev.type === 'session.compacted') {
481
- await todoPreserver.onCompacted(ev.properties.sessionID)
482
- }
483
- if (ev.type === 'message.updated') {
484
- await handleToolCeilingEvent(input.client, ev, sessionToolCeilings)
819
+ // Observation must never fail the tool registration.
485
820
  }
486
- // Wave 1/3: `session.idle` → idle dispatcher. An active goal owns the
487
- // idle (goal loop); otherwise the todo enforcer re-injects. onIdle never
488
- // throws (internal failures are logged + swallowed), so the session is
489
- // safe.
490
- if (ev.type === 'session.idle') {
491
- await idleDispatcher.onIdle(ev.properties.sessionID)
492
- }
493
- await vision.event({ event: ev })
494
- },
495
- // Phase 4: deny mutating tools in read-only delegated sessions. Additive
496
- // key — does not touch Phase 3's tools/event/onTerminal/chat.message.
497
- 'tool.execute.before': async (input, output) => {
498
- // Chain: Zeus read guard runs first (denies read/glob/grep of source
499
- // code when the active agent is Zeus — delegate to @apollo), then the
500
- // read-only enforcement guard (denies mutating tools in read-only
501
- // sessions), then release-134 Phase 3 rewrites the first
502
- // post-compaction `todowrite` with the captured todo snapshot. All are
503
- // no-ops for non-matching sessions/tools. The read guard also checks the
504
- // SYMLINK-RESOLVED form of every target path (#272), so a link into a
505
- // denied root cannot pass on its string spelling.
506
- zeusReadGuard(input.tool, output?.args, sessionAgents.get(input.sessionID), resolveGuardPath)
507
- await enforcementGuard(input, output)
508
- await commandNormalizer(input, output)
509
- await todoPreserver.beforeTodoWrite(input, output)
821
+ })
822
+ return true
823
+ } catch {
824
+ return false
825
+ }
826
+ }
827
+
828
+ // ─── V2 Event Subscription ──────────────────────────────────────────────
829
+
830
+ /**
831
+ * The P7 telemetry sink created by the most recent event subscription.
832
+ *
833
+ * P7 writes through the 0b record path (`createTelemetrySink`): in-memory,
834
+ * bounded and I/O-free by design, so a test that asserts "the decision was
835
+ * actually recorded" has to read the same collector the wiring wrote to.
836
+ * Exported only for tests/pantheon/plugin-contract.test.ts — production has
837
+ * no caller, and nothing in the plugin reads this back.
838
+ */
839
+ export function getP7TelemetrySinkForTests(): TelemetrySink | undefined {
840
+ return p7TelemetrySink
841
+ }
842
+
843
+ let p7TelemetrySink: TelemetrySink | undefined
844
+
845
+ /**
846
+ * The P8 telemetry sink created by the most recent permission-hook
847
+ * registration.
848
+ *
849
+ * P8 records every outcome it is responsible for — `guardrail.narrow`,
850
+ * `guardrail.keep`, `guardrail.refusal`, `p8.write.rejected`,
851
+ * `p8.write.delegation` and `p8.write.unconfirmed` — through the 0b record path
852
+ * (`createTelemetrySink`, in-memory, bounded, I/O-free). A guardrail that
853
+ * narrows without a record is indistinguishable from an inert one, which is
854
+ * exactly the defect PH5-1 closed. Every record carries the P8 registry `mode`
855
+ * (`off`), never `active`, and a `narrow` is recorded only when a re-read of
856
+ * the event still holds it (N9/N10). Exported only for
857
+ * tests/pantheon/plugin-contract.test.ts.
858
+ */
859
+ export function getP8TelemetrySinkForTests(): TelemetrySink | undefined {
860
+ return p8TelemetrySink
861
+ }
862
+
863
+ let p8TelemetrySink: TelemetrySink | undefined
864
+
865
+ /**
866
+ * The prompt-surface telemetry sink created by the most recent prompt-hook
867
+ * registration.
868
+ *
869
+ * P1 and P2 observe the same admission payload through `observePromptSurface`;
870
+ * each shadow record is reduced through the 0b record path
871
+ * (`createTelemetrySink`, in-memory, bounded, I/O-free) and carries
872
+ * `mode: 'shadow'` — the registry mode both declare. Nothing in production
873
+ * reads this collector back, so the write is only a claim if a reader can
874
+ * assert it: this accessor is that reader, and
875
+ * tests/pantheon/plugin-contract.test.ts is its only caller.
876
+ */
877
+ export function getPromptSurfaceTelemetrySinkForTests(): TelemetrySink | undefined {
878
+ return promptSurfaceTelemetrySink
879
+ }
880
+
881
+ let promptSurfaceTelemetrySink: TelemetrySink | undefined
882
+
883
+ /**
884
+ * The P3 telemetry sink created by the most recent tool registration.
885
+ *
886
+ * P3 is constructed at `tool.invoke`: `pantheon_local_decision`'s execute calls
887
+ * the adapter with the tool input, which carries `complexity` and `gateStatus`.
888
+ * Records are reduced through the same in-memory 0b path and carry the P3
889
+ * registry `mode` (`shadow`). Exported only for
890
+ * tests/pantheon/plugin-contract.test.ts and the wiring audit.
891
+ */
892
+ export function getP3TelemetrySinkForTests(): TelemetrySink | undefined {
893
+ return p3TelemetrySink
894
+ }
895
+
896
+ let p3TelemetrySink: TelemetrySink | undefined
897
+
898
+ /**
899
+ * The P9 telemetry sink created by the most recent compaction-hook
900
+ * registration.
901
+ *
902
+ * P9 declares `session.hook('compaction')` and observes the MEASURED carrier
903
+ * only: the top-level `sessionID` and the `system` part array (F-01, F-02).
904
+ * Records go through the same in-memory, bounded 0b path and carry the P9
905
+ * registry `mode` (`shadow`). Exported only for
906
+ * tests/pantheon/plugin-contract.test.ts and the wiring audit.
907
+ */
908
+ export function getP9TelemetrySinkForTests(): TelemetrySink | undefined {
909
+ return p9TelemetrySink
910
+ }
911
+
912
+ let p9TelemetrySink: TelemetrySink | undefined
913
+
914
+ /**
915
+ * The P11 telemetry sink created by the most recent tool registration.
916
+ *
917
+ * P11 declares `tool.transform` and reads the draft the host hands that
918
+ * callback (F-07) — the only measured catalogue surface, since `ctx.catalog` is
919
+ * absent (F-05). Records go through the in-memory, bounded 0b path and carry the
920
+ * P11 registry `mode` (`shadow`). Exported only for
921
+ * tests/pantheon/plugin-contract.test.ts and the wiring audit.
922
+ */
923
+ export function getP11TelemetrySinkForTests(): TelemetrySink | undefined {
924
+ return p11TelemetrySink
925
+ }
926
+
927
+ let p11TelemetrySink: TelemetrySink | undefined
928
+
929
+ /**
930
+ * The J1 risk-score telemetry sink created by the most recent tool-hook
931
+ * registration.
932
+ *
933
+ * J1 (the risk-score advisory gate, `jev-risk-gate.ts`) is NOT a registry
934
+ * point: it is a flag-gated shadow observer on write/execute tool calls. The
935
+ * sink exists only when `PANTHEON_J1_RISK_SCORE` is on AND the host runtime
936
+ * exposes the native Decisions API, so flag-off leaves it undefined — the
937
+ * zero-overhead contract. Records go through the in-memory, bounded 0b path
938
+ * (`createTelemetrySink`, no I/O) and carry `mode: 'shadow'`; the observer is
939
+ * fire-and-observe, so the tool call never waits on it. Exported only for
940
+ * tests/pantheon/plugin-contract.test.ts.
941
+ */
942
+ export function getJ1TelemetrySinkForTests(): TelemetrySink | undefined {
943
+ return j1TelemetrySink
944
+ }
945
+
946
+ let j1TelemetrySink: TelemetrySink | undefined
947
+
948
+ /**
949
+ * The J3 turn-complexity escalation telemetry sink created by the most recent
950
+ * tool-hook registration.
951
+ *
952
+ * J3 (the escalation shadow classifier, `jev-escalation.ts`) is NOT a registry
953
+ * point: it is a flag-gated shadow observer on delegate dispatches (the native
954
+ * `subagent` tool). The sink exists only when `PANTHEON_J3_ESCALATION` is on
955
+ * AND the host runtime exposes the native Decisions API, so flag-off leaves it
956
+ * undefined — the zero-overhead contract. Records go through the in-memory,
957
+ * bounded 0b path (`createTelemetrySink`, no I/O) and carry `mode: 'shadow'`;
958
+ * the observer is fire-and-observe, so the dispatch never waits on it. The
959
+ * recorded verdict never changes the dispatched model: the override mechanism
960
+ * for the activation step lives in `jev-escalation.ts` and is unreachable from
961
+ * this wiring. Exported only for tests/pantheon/plugin-contract.test.ts.
962
+ */
963
+ export function getJ3TelemetrySinkForTests(): TelemetrySink | undefined {
964
+ return j3TelemetrySink
965
+ }
966
+
967
+ let j3TelemetrySink: TelemetrySink | undefined
968
+
969
+ /**
970
+ * The J4 output-quality review telemetry sink created by the most recent Jev
971
+ * runtime build.
972
+ *
973
+ * J4 (the review mode of `pantheon_jev_decide`, `jev-quality-score.ts`) is
974
+ * NOT a registry point and has no flag: the review runs only when Zeus
975
+ * explicitly requests it, and the record (`point: 'J4'`, `mode: 'shadow'`,
976
+ * `effect: 'none'`, reason token `q-<n>-review-<yes|no|na>` or a `skip-…`
977
+ * token) is the whole effect — advisory, never read back by the tool path.
978
+ * The sink is created inside `buildV2JevRuntime`, so it exists exactly when
979
+ * the runtime (and with it the tool) exists. Exported only for
980
+ * tests/pantheon/plugin-contract.test.ts.
981
+ */
982
+ export function getJ4TelemetrySinkForTests(): TelemetrySink | undefined {
983
+ return j4TelemetrySink
984
+ }
985
+
986
+ let j4TelemetrySink: TelemetrySink | undefined
987
+
988
+ /**
989
+ * Attempt to subscribe to session events via V2 ctx.event.subscribe.
990
+ *
991
+ * The V2 event.subscribe API (when available) provides an async iterable:
992
+ * for await (const event of ctx.event.subscribe({ signal })) { ... }
993
+ *
994
+ * Returns a cleanup function, or undefined if the API is unavailable.
995
+ */
996
+ function subscribeV2Events(
997
+ context: PluginContext,
998
+ onTurnEnd?: (sessionID: string) => void,
999
+ ): (() => void) | undefined {
1000
+ const eventCtx = hostDomains(context).event
1001
+
1002
+ if (!eventCtx?.subscribe) {
1003
+ return undefined
1004
+ }
1005
+
1006
+ // P7 loop adapter (PLAN §5.1 branch 1, selected by PROBE-D §7). Constructed
1007
+ // here but inert unless PANTHEON_P7_LOOP is set: the flag is OFF by
1008
+ // default, and activation is Phase 4b — not this change. Observation is
1009
+ // synchronous and self-contained, so it cannot block the stream, cannot
1010
+ // throw into the dispatch, and does not alter the cleanup below.
1011
+ //
1012
+ // The sink is the 0b telemetry record path (`createTelemetrySink`, in-memory
1013
+ // and bounded, no I/O). Each shadow record is reduced to its own allowlisted
1014
+ // fields plus `mode: 'migration'` — the P7 registry mode — and nothing else:
1015
+ // the execution count is not on the allowlist, so it is not recorded, and no
1016
+ // prompt, response or user content can reach the record. A disabled adapter
1017
+ // never calls the sink, so flag-off still emits zero records.
1018
+ const telemetrySink = createTelemetrySink()
1019
+ p7TelemetrySink = telemetrySink
1020
+ const loopPoint = createP7LoopPoint({
1021
+ enabled: p7LoopEnabledFromEnv(),
1022
+ sink: (record) => {
1023
+ telemetrySink.emit({ ...record, mode: 'migration' })
510
1024
  },
511
- // Wave 2 (PR #46) + Context Sandbox (v2 P0): sandbox truncates oversized
512
- // outputs BEFORE hashline tags (so tags remain stable on kept lines).
513
- // Additive —
514
- // pantheon-hooks.ts (a separate plugin instance) owns its own
515
- // tool.execute.after, so there is no key collision. Non-read tools pass
516
- // through untouched.
517
- 'tool.execute.after': combinedAfter,
518
- // Phase 4 + release-134 Phase 2: keep the session's working state across
519
- // compaction — preservation directive, active goals (<mission_context>)
520
- // and pending todos (<todo_context>). Guarded: only pushes when there is
521
- // something to preserve; a build failure must never break the experimental
522
- // compaction hook.
523
- 'experimental.session.compacting': async (_input, output) => {
524
- try {
525
- const blocks = await buildCompactionContext({
526
- sessionID: _input.sessionID,
527
- goals: {
528
- enabled: GOAL_LOOP_DEFAULTS.enabled,
529
- list: (sessionID: string) => goalStore.list(sessionID),
530
- },
531
- todos: {
532
- enabled: todoEnforcerEnabledFromEnv(),
533
- list: (sessionID: string) => todoEnforcer.listPendingTodos(sessionID),
534
- },
535
- })
536
- const ceiling = sessionToolCeilings.get(_input.sessionID)
537
- if (ceiling?.status === 'OK') {
538
- output.context.push(
539
- `<tool_ceiling remaining_context_tokens="${ceiling.ceiling}">` +
540
- 'Use the remaining host-reported context budget when selecting tools.</tool_ceiling>',
541
- )
1025
+ })
1026
+
1027
+ const controller = new AbortController()
1028
+ void (async () => {
1029
+ try {
1030
+ // biome-ignore lint/style/noNonNullAssertion: subscribe guaranteed by guard above
1031
+ for await (const event of eventCtx.subscribe!({ signal: controller.signal })) {
1032
+ await handleV2SessionEvent(event)
1033
+ try {
1034
+ loopPoint.observe(event)
1035
+ } catch {
1036
+ // The adapter contains its own failures; this keeps a future
1037
+ // regression out of the dispatch loop.
542
1038
  }
543
- if (blocks.length > 0) {
544
- output.context.push(...blocks)
1039
+ // KNOWN DEFECT, out of scope for Phase 4a: this branch and
1040
+ // `handleV2SessionEvent`'s `session.compacted` case key on types the
1041
+ // measured host never delivers — `session.idle` 0/11 runs and
1042
+ // `session.compacted` 0/11 (PROBE-C, F-12). The live turn-end signal
1043
+ // is `session.execution.succeeded`, observed above. The branches are
1044
+ // left untouched on purpose; removing them is a separate change.
1045
+ if (event.type === 'session.idle' || event.type === 'session.deleted') {
1046
+ const properties = event.properties ?? {}
1047
+ const info = properties.info
1048
+ const infoID =
1049
+ info !== null && typeof info === 'object' ? (info as { id?: unknown }).id : undefined
1050
+ const sessionID =
1051
+ typeof properties.sessionID === 'string'
1052
+ ? properties.sessionID
1053
+ : typeof infoID === 'string'
1054
+ ? infoID
1055
+ : undefined
1056
+ if (sessionID) onTurnEnd?.(sessionID)
545
1057
  }
546
- // release-134 Phase 3 (additive): snapshot the session's full todo
547
- // list for post-compaction restore. Best-effort — a GET failure is
548
- // logged and the compaction proceeds normally.
549
- await todoPreserver.capture(_input.sessionID)
550
- } catch (err: unknown) {
551
- log.warn('[Pantheon Plugin] Compaction context build failed:', err)
552
1058
  }
553
- },
554
- }
1059
+ } catch (err: unknown) {
1060
+ if (err instanceof Error && err.name === 'AbortError') return
1061
+ // Log but don't crash
1062
+ console.warn('[Pantheon V2] Event subscription error:', err)
1063
+ }
1064
+ })()
1065
+
1066
+ return () => controller.abort()
1067
+ }
1068
+
1069
+ /**
1070
+ * Route a V2 session event to the appropriate handler.
1071
+ */
1072
+ async function handleV2SessionEvent(event: V2SessionEvent): Promise<void> {
1073
+ switch (event.type) {
1074
+ case 'session.created':
1075
+ await onSessionCreated(event)
1076
+ break
1077
+ case 'session.idle':
1078
+ await onSessionIdle(event)
1079
+ break
1080
+ case 'session.deleted':
1081
+ await onSessionDeleted(event)
1082
+ break
1083
+ case 'session.error':
1084
+ await onSessionError(event)
1085
+ break
1086
+ case 'session.compacted':
1087
+ await onSessionCompacted(event)
1088
+ break
1089
+ default:
1090
+ break
1091
+ }
1092
+ }
1093
+
1094
+ /**
1095
+ * Record the v2.0.29 lifecycle event in the opt-in F4A canary. Runtime events
1096
+ * use a `{ id, created, type, data }` envelope; the child data carries
1097
+ * `sessionID`, `parentID` and `agent`. Admission itself does not depend on this
1098
+ * subscription: it checks the current permission source and `ctx.session.get`
1099
+ * synchronously, so resumed roots and children use the same path.
1100
+ */
1101
+ async function onSessionCreated(event: V2SessionEvent): Promise<void> {
1102
+ const payload = event as V2SessionEvent & Record<string, unknown>
1103
+ const properties = event.properties ?? {}
1104
+ const data =
1105
+ event.data !== null && typeof event.data === 'object'
1106
+ ? (event.data as Record<string, unknown>)
1107
+ : {}
1108
+ const info = properties.info ?? data.info
1109
+ const sessionInfo =
1110
+ info !== null && typeof info === 'object' ? (info as Record<string, unknown>) : {}
1111
+ writeV2AdmissionProof('session.created', {
1112
+ eventKeys: Object.keys(payload),
1113
+ propertyKeys: Object.keys(properties),
1114
+ dataKeys: Object.keys(data),
1115
+ infoKeys: Object.keys(sessionInfo),
1116
+ id:
1117
+ sessionInfo.id ??
1118
+ sessionInfo.sessionID ??
1119
+ data.id ??
1120
+ data.sessionID ??
1121
+ properties.id ??
1122
+ properties.sessionID ??
1123
+ payload.sessionID ??
1124
+ null,
1125
+ parentID: sessionInfo.parentID ?? data.parentID ?? properties.parentID ?? null,
1126
+ agent: sessionInfo.agent ?? data.agent ?? properties.agent ?? null,
1127
+ })
1128
+ }
1129
+
1130
+ async function onSessionIdle(_event: V2SessionEvent): Promise<void> {
1131
+ // Temp-image sweep on the V2-only path: DELIBERATELY DEFERRED.
1132
+ //
1133
+ // V1 unlinks a session's temp images on `session.idle`/`session.deleted`
1134
+ // (`cleanupSessionTempImages`, grace-guarded and refcounted). V2 cannot reuse
1135
+ // it: `saveDataUrlImageSync` (the V2 materialization path) receives no session
1136
+ // id, so there is no per-session `path → createdAt` map to sweep, and the
1137
+ // content-hash temp dir is refcounted ONLY on the V1 path. The one reusable
1138
+ // piece, `enforceTempFileCap`, is already invoked off every V2 save
1139
+ // (`saveDataUrlImageSync`), so disk usage is bounded without an idle pass —
1140
+ // re-running it here would be redundant, and a GLOBAL age-based unlink fired
1141
+ // by one session's idle could delete a file another live session still
1142
+ // references. Delivery is also best-effort: with no `ctx.event.subscribe`
1143
+ // the stream is unsupported (`markUnsupported('event-stream')`) and no idle
1144
+ // ever arrives. Implementing this safely needs V2-side session threading
1145
+ // first; until then it stays deferred rather than approximated.
1146
+ //
1147
+ // Idle continuation — todo enforcer dispatch. The enforcer is constructed
1148
+ // by THIS module at setup (installV2TodoEnforcer) when the host session
1149
+ // domain exposes the methods the enforcer uses.
1150
+ const sessionID = _event.properties?.sessionID as string | undefined
1151
+ if (!sessionID) return
1152
+ const enforcer = idleTodoEnforcer
1153
+ if (enforcer != null) {
1154
+ try {
1155
+ await enforcer.onIdle(sessionID)
1156
+ } catch {
1157
+ // Fail-open: the enforcer never breaks the session.
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ /**
1163
+ * Session-deleted handler: drop the read-only registration.
1164
+ *
1165
+ * `readOnlyRegistry` is a process-wide singleton and the `execute.before` hook
1166
+ * populates it on every delegated `apollo`/`gaia` call. V1 prunes it on
1167
+ * `session.deleted` (`src/plugin.ts`); V2 did not, so on a long-lived host
1168
+ * every finished investigation session stayed registered for the life of the
1169
+ * process — a slow leak, and a stale entry that would keep denying tools if
1170
+ * the id were ever reused.
1171
+ *
1172
+ * This mirrors V1: unregister the session, which drops its agent entry with it
1173
+ * (the registry stores one `ReadOnlyEntry` per session id). V1 also clears a
1174
+ * `sessionAgents` map here; V2 has no such map and needs no equivalent, since
1175
+ * it reads the active agent off the event instead of caching it.
1176
+ *
1177
+ * The id is read from `properties.sessionID` — the field the sibling
1178
+ * `session.idle` handler already uses — falling back to V1's
1179
+ * `properties.info.id`. Both spellings are accepted because the V2 SDK types
1180
+ * `session.deleted` as `{ sessionID, info }` and a miss here is a silent leak,
1181
+ * which is precisely the bug this handler exists to close.
1182
+ *
1183
+ * A payload with NEITHER spelling is fail-open, and unavoidably so: unregistering
1184
+ * is what needs the id, so an id that cannot be resolved cannot be cleaned up
1185
+ * and the entry survives. The docstring used to leave that as a documented
1186
+ * silent branch; it now warns on the way out, because the only other symptom of
1187
+ * a renamed field is a registry that grows for the life of the process.
1188
+ */
1189
+ async function onSessionDeleted(event: V2SessionEvent): Promise<void> {
1190
+ const properties = event.properties
1191
+ if (properties === undefined) return
1192
+ const info = properties.info
1193
+ const sessionID =
1194
+ typeof properties.sessionID === 'string'
1195
+ ? properties.sessionID
1196
+ : info !== null && typeof info === 'object'
1197
+ ? (info as { id?: unknown }).id
1198
+ : undefined
1199
+ if (typeof sessionID !== 'string' || sessionID === '') {
1200
+ // Fail-open by necessity, loud by choice: the entry for this session (if
1201
+ // any) cannot be identified, so it stays registered. Same `console.warn`
1202
+ // channel as the event-subscription error above — this module has no
1203
+ // logger, and a diagnostic nobody reads on stderr is still a silent leak.
1204
+ console.warn(
1205
+ '[Pantheon V2] session.deleted carried no session id ' +
1206
+ '(neither properties.sessionID nor properties.info.id); ' +
1207
+ 'its read-only registration cannot be pruned and will persist.',
1208
+ )
1209
+ return
1210
+ }
1211
+ readOnlyRegistry.unregister(sessionID)
1212
+ }
1213
+
1214
+ /**
1215
+ * Session-error handler: no V2-side implementation.
1216
+ *
1217
+ * The board error transition lives in V1's event hook, which is not loaded on
1218
+ * a V2-only install. There is nothing to do here — deliberately, rather than
1219
+ * describing behaviour this handler does not have.
1220
+ */
1221
+ async function onSessionError(_event: V2SessionEvent): Promise<void> {}
1222
+
1223
+ /**
1224
+ * Session-compacted handler: no V2-side implementation.
1225
+ *
1226
+ * Todo preservation and compaction context build live in the V1 path
1227
+ * (`todo-preserve.ts`, driven by V1's compaction hook), which is not loaded on
1228
+ * a V2-only install.
1229
+ */
1230
+ async function onSessionCompacted(_event: V2SessionEvent): Promise<void> {}
1231
+
1232
+ // ─── V2 Session Hooks ───────────────────────────────────────────────────
1233
+
1234
+ /** One entry per no-op reason and session/site; successful passes retain each saving. */
1235
+ const pruneSkipSessions = new Set<string>()
1236
+ const PRUNE_SKIP_SESSIONS_MAX = 256
1237
+
1238
+ function logContextPrune(stats: PruneStats, sessionID: unknown): void {
1239
+ if (stats.changed) {
1240
+ appendV2HookLog(
1241
+ `[context-pruner] site=${stats.site} messages=${stats.messagesTouched} ` +
1242
+ `parts=${stats.partsPruned} est_tokens_saved=${stats.estimatedTokensSaved}`,
1243
+ )
1244
+ return
1245
+ }
1246
+ if (
1247
+ stats.skipReason === null ||
1248
+ stats.skipReason === 'not-array' ||
1249
+ stats.skipReason === 'malformed'
1250
+ ) {
1251
+ return
1252
+ }
1253
+
1254
+ const session = typeof sessionID === 'string' && sessionID !== '' ? sessionID : 'unknown'
1255
+ const key = `${stats.site}:${session}:${stats.skipReason}`
1256
+ if (pruneSkipSessions.has(key)) return
1257
+ if (pruneSkipSessions.size >= PRUNE_SKIP_SESSIONS_MAX) pruneSkipSessions.clear()
1258
+ pruneSkipSessions.add(key)
1259
+ appendV2HookLog(
1260
+ `[context-pruner] site=${stats.site} skip=${stats.skipReason} ` +
1261
+ `messages=${stats.messagesTouched} parts=${stats.partsPruned} ` +
1262
+ `est_tokens_saved=${stats.estimatedTokensSaved}`,
1263
+ )
1264
+ }
1265
+
1266
+ /**
1267
+ * Fail-open diagnostics: at most ONE line per session, whatever the engine
1268
+ * threw or however malformed the payload was. Bounded so a long-lived host
1269
+ * cannot accumulate session ids forever.
1270
+ */
1271
+ const pruneFailureSessions = new Set<string>()
1272
+ const PRUNE_FAILURE_SESSIONS_MAX = 256
1273
+
1274
+ function logPruneFailureOnce(sessionID: unknown, site: PruneSite, error: unknown): void {
1275
+ const session = typeof sessionID === 'string' && sessionID !== '' ? sessionID : ''
1276
+ const key = session !== '' ? session : `${site}:unknown`
1277
+ if (pruneFailureSessions.has(key)) return
1278
+ if (pruneFailureSessions.size >= PRUNE_FAILURE_SESSIONS_MAX) pruneFailureSessions.clear()
1279
+ pruneFailureSessions.add(key)
1280
+ const message = error instanceof Error ? error.message : String(error)
1281
+ appendV2HookLog(`[context-pruner] failed open site=${site} session=${key}: ${message}`)
1282
+ }
1283
+
1284
+ /**
1285
+ * A compaction payload whose `messages` is absent or misnamed is a shape drift,
1286
+ * not a normal no-op: the feature is always-on at that site, so silence would
1287
+ * hide the drift forever. Report `not-array`/`malformed` with the same
1288
+ * once-per-session channel as a thrown failure. The `context` caller invokes
1289
+ * this only when the feature is enabled.
1290
+ */
1291
+ function logPruneShapeIssue(stats: PruneStats, sessionID: unknown, site: PruneSite): void {
1292
+ if (stats.skipReason !== 'not-array' && stats.skipReason !== 'malformed') return
1293
+ const detail =
1294
+ stats.skipReason === 'not-array'
1295
+ ? 'not-array: payload.messages is not an array; input left unchanged'
1296
+ : 'malformed: unexpected message shape; input left unchanged'
1297
+ logPruneFailureOnce(sessionID, site, new Error(detail))
1298
+ }
1299
+
1300
+ /**
1301
+ * Config typos are otherwise invisible: `keepTurn: 7` resolves to the default 4
1302
+ * and the operator believes it applied. Warn ONCE per process, name the
1303
+ * ignored keys and the accepted keys, and keep the fail-open resolution.
1304
+ */
1305
+ let contextPrunerConfigWarned = false
1306
+
1307
+ function warnContextPrunerConfigOnce(options: unknown): void {
1308
+ if (contextPrunerConfigWarned) return
1309
+ try {
1310
+ const issues = describeContextPrunerConfigIssues(options)
1311
+ if (issues.length === 0) return
1312
+ contextPrunerConfigWarned = true
1313
+ appendV2HookLog(
1314
+ `[context-pruner] ignored invalid context_pruner config: ${issues.join('; ')}; ` +
1315
+ `accepted keys: ${CONTEXT_PRUNER_CONFIG_KEYS.join(', ')}`,
1316
+ )
1317
+ } catch {
1318
+ // A validator must never break setup; silence is the only safe fallback.
1319
+ contextPrunerConfigWarned = true
1320
+ }
1321
+ }
1322
+
1323
+ /**
1324
+ * Empty description cache for {@link sanitizeVisionHistory}.
1325
+ *
1326
+ * V1 fills this from the vision handler (per-part text captured at
1327
+ * `chat.message` time). V2 has no equivalent cache, so the sanitizer falls back
1328
+ * to its own placeholder text for every image part — which is the contract that
1329
+ * matters: an image never reaches the provider as image content.
1330
+ */
1331
+ const V2_VISION_HISTORY_TEXT: ReadonlyMap<string, ReadonlyMap<string, string>> = new Map()
1332
+
1333
+ /**
1334
+ * Register session hooks via V2 ctx.session.hook.
1335
+ *
1336
+ * The V2 session.hook API (when available) provides:
1337
+ * ctx.session.hook("prompt", handler) — message admission
1338
+ * ctx.session.hook("context", handler) — system context injection
1339
+ * ctx.session.hook("compaction", handler) — registered in setup Phase 7
1340
+ *
1341
+ * Returns true if any hooks were registered.
1342
+ */
1343
+ async function registerV2SessionHooks(context: PluginContext): Promise<boolean> {
1344
+ // Config validity is independent of hook availability; warn before the early
1345
+ // return so a typo is visible even on a host that registers no session hook.
1346
+ warnContextPrunerConfigOnce(context.options)
1347
+ const host = hostDomains(context)
1348
+ const sessionCtx = host.session
1349
+
1350
+ if (!sessionCtx?.hook) {
1351
+ return false
1352
+ }
1353
+
1354
+ // Resolved once, mirroring `resolveV2SandboxConfig(context.options)`: the
1355
+ // per-request context prune is opt-in because it invalidates the provider
1356
+ // prompt cache and has no measured cost baseline. The compaction site below
1357
+ // applies the rules unconditionally.
1358
+ const prunerConfig = resolveContextPrunerConfig(context.options)
1359
+
1360
+ let registered = false
1361
+
1362
+ try {
1363
+ // "context" hook — inject routing policy + compaction state
1364
+ await sessionCtx.hook('context', (event: unknown) => {
1365
+ try {
1366
+ // Opt-in lifetime proof for the host-backed hook canary (MODE=real).
1367
+ // Inert unless PANTHEON_HOOK_CANARY_LIFETIME_PROOF is set.
1368
+ if (process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF) {
1369
+ try {
1370
+ appendFileSync(
1371
+ process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF,
1372
+ 'plugin:session.hook:context\n',
1373
+ )
1374
+ } catch {
1375
+ // Best-effort instrumentation.
1376
+ }
1377
+ }
1378
+ // 2.0.16 payload is `{ system: Array<SystemPart> }`. Normalize any
1379
+ // string entries to `{ type: 'text', text }` parts and append the
1380
+ // policy as a part. Junk entries are ignored; a non-array,
1381
+ // non-string system is left untouched. Never throws (fail-open).
1382
+ const ctx = event as
1383
+ | { system?: unknown; messages?: unknown; sessionID?: unknown }
1384
+ | null
1385
+ | undefined
1386
+ if (ctx == null) return
1387
+ const normalized = normalizeSystemToParts(ctx.system)
1388
+ if (normalized != null) {
1389
+ // A bare string is replaced by its part array; an array is mutated in
1390
+ // place (the host may read the original reference).
1391
+ if (typeof ctx.system === 'string') ctx.system = normalized
1392
+ if (!hasPolicyMarker(normalized)) {
1393
+ normalized.push({ type: 'text', text: POLICY } satisfies SystemPart)
1394
+ }
1395
+ }
1396
+ // Vision history sanitization (V1
1397
+ // `experimental.chat.messages.transform` parity, #266). Image parts are
1398
+ // replaced with their cached description, or with the same placeholder
1399
+ // V1 uses, BEFORE a text-only provider serializer can turn them into
1400
+ // `image_url` content. The host's `context` payload carries the
1401
+ // provider-bound `messages` array and honors mutations per request, so
1402
+ // this is the same seam V1's transform occupies.
1403
+ //
1404
+ // The description map is empty on V2 by construction: descriptions are
1405
+ // cached by the V1 vision handler, which has no V2 counterpart (V2
1406
+ // materializes the image and asks the model to call `vision_describe`).
1407
+ // Every image part therefore becomes the placeholder — the safety
1408
+ // property V1's transform exists for — never a raw image.
1409
+ try {
1410
+ sanitizeVisionHistory({ messages: ctx.messages }, V2_VISION_HISTORY_TEXT)
1411
+ } catch (error) {
1412
+ logPruneFailureOnce(ctx.sessionID, 'context', error)
1413
+ }
1414
+ // Opt-in DCP: same engine as the compaction site, but per-request
1415
+ // pruning invalidates the prompt cache, so it runs only when
1416
+ // `context_pruner.enabled` is explicitly true. Disabled = the hook is
1417
+ // byte-for-byte the previous behaviour. The named-behavior override
1418
+ // `gate-context-pruner` disables it entirely (2.0 overrides layer).
1419
+ loadRuntimeOverrides()
1420
+ if (prunerConfig.enabled && !gateDisabled('gate-context-pruner')) {
1421
+ try {
1422
+ const stats = pruneMessages(ctx.messages, prunerConfig, 'context')
1423
+ logContextPrune(stats, ctx.sessionID)
1424
+ logPruneShapeIssue(stats, ctx.sessionID, 'context')
1425
+ } catch (error) {
1426
+ logPruneFailureOnce(ctx.sessionID, 'context', error)
1427
+ }
1428
+ }
1429
+ } catch {
1430
+ // Fail-open: never throw to the host.
1431
+ }
1432
+ })
1433
+ registered = true
1434
+ } catch {
1435
+ // Context hook not supported
1436
+ }
1437
+
1438
+ try {
1439
+ // Prompt-surface shadow points (P1 and P2) share this payload. P3 moved to
1440
+ // `tool.invoke`, where its input actually carries a complexity vector; P6
1441
+ // and P10 are unwired because no measured surface carries their inputs.
1442
+ // The sink is in-memory and bounded, exactly like P7/P8; it is created per
1443
+ // registration so one setup cannot observe another's records.
1444
+ const promptSurfaceSink = createTelemetrySink()
1445
+ promptSurfaceTelemetrySink = promptSurfaceSink
1446
+ // "prompt" hook — preserve attached image references and add model-visible
1447
+ // instructions so Zeus can inspect visual context and pass it to the
1448
+ // implementation specialist before editing.
1449
+ await sessionCtx.hook('prompt', async (event: unknown) => {
1450
+ try {
1451
+ // 2.0.29 host payload: `{ sessionID, messageID, prompt: { text,
1452
+ // files, agents, skills }, metadata, delivery }`. The session id is
1453
+ // top-level (verified against the host's `SessionPrompt.prepare`), so a
1454
+ // data: attachment's panic-free moment also relays it to the MCP.
1455
+ const admission = event as {
1456
+ sessionID?: unknown
1457
+ messageID?: unknown
1458
+ prompt?: { text?: unknown; files?: unknown; skills?: unknown }
1459
+ } | null
1460
+ const prompt = admission?.prompt
1461
+ if (!prompt || typeof prompt.text !== 'string') return
1462
+ const userRequest = prompt.text
1463
+ if (!prompt.text.includes('<!-- pantheon-v2-visual-context -->')) {
1464
+ const sessionID =
1465
+ typeof admission?.sessionID === 'string' && admission.sessionID.trim() !== ''
1466
+ ? admission.sessionID
1467
+ : undefined
1468
+ const visualContext = buildV2VisionPromptContext(prompt.files, prompt.text, sessionID)
1469
+ if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
1470
+ }
1471
+
1472
+ // Local deterministic recommendations are advisory only. This path
1473
+ // never consults provider consent/credentials or invokes remote egress.
1474
+ await applyDecisionRouterToPrompt(admission, userRequest)
1475
+
1476
+ // Shadow observation only. The projection carries `prompt.agents` and
1477
+ // `prompt.skills` and nothing else, so no prompt text or file bytes
1478
+ // reach a record; observeShadow clones and freezes it, so admission is
1479
+ // not mutated. A failure here is contained by the outer catch and never
1480
+ // reaches the host.
1481
+ observePromptSurface(admission, (record) => {
1482
+ promptSurfaceSink.emit({ ...record, mode: 'shadow' })
1483
+ })
1484
+ } catch {
1485
+ // Fail-open: malformed/unsupported prompt shapes must not block input.
1486
+ }
1487
+ })
1488
+ registered = true
1489
+ } catch {
1490
+ // Prompt hook not supported
1491
+ }
1492
+
1493
+ return registered
1494
+ }
1495
+
1496
+ // ─── V2 Secret Scan ─────────────────────────────────────────────────────
1497
+
1498
+ /**
1499
+ * High-confidence secret token formats — MIRRORS `SECRET_MASK_RE` in
1500
+ * src/plugins/pantheon-hooks.ts (V1) and `HIGH_CONFIDENCE_PATTERNS` in
1501
+ * scripts/hooks/scan-secrets.sh.
1502
+ *
1503
+ * Duplicated rather than imported because the V1 module is a separate plugin
1504
+ * that is NOT loaded on a V2-only install (see the module header), and pulling
1505
+ * it in for one regex would resurrect exactly the V1-hook coupling V2 exists to
1506
+ * remove. The drift risk is real and is asserted by a test in
1507
+ * tests/pantheon/plugin-contract.test.ts.
1508
+ *
1509
+ * Applied to every log line this module writes, so a hook trail can never
1510
+ * contain a raw credential. Header/KEY names (the Bifrost header alone,
1511
+ * `api_key=...`) are deliberately NOT matched: they are not secret values.
1512
+ */
1513
+ const SECRET_MASK_RE =
1514
+ /(sk-bf-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9_]{36,}|glpat-[A-Za-z0-9_-]{20}|sk-[a-zA-Z0-9]{20,}|sk_live_[a-zA-Z0-9]{20,}|sk_test_[a-zA-Z0-9]{20,}|xox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24}|bearer\s+[a-zA-Z0-9_.-]{20,}|eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*)/gi
1515
+
1516
+ /** Replace every high-confidence secret match with '****'. */
1517
+ function maskSecret(text: string): string {
1518
+ return text.replace(SECRET_MASK_RE, '****')
1519
+ }
1520
+
1521
+ /**
1522
+ * Message thrown when scan-secrets.sh exits 2 (a high-confidence token match).
1523
+ *
1524
+ * This is the only deliberate throw on the V2 surface. opencode's
1525
+ * Plugin.trigger has no catch around hook invocations, so the rejection
1526
+ * propagates and fails the tool's execute promise BEFORE the tool body runs —
1527
+ * the same hard block V1 has (src/plugins/pantheon-hooks.ts
1528
+ * `SECRET_BLOCK_MESSAGE`), which was inert on a V2-only install because
1529
+ * pantheon-hooks.ts is never loaded there (opencode.json `plugins` declares only
1530
+ * `src/plugin`).
1531
+ *
1532
+ * English, like every other message this module emits: this string surfaces in
1533
+ * the user's session as the tool error, so it is read by whoever hit the block,
1534
+ * not by the code that raised it. A Portuguese release note elsewhere in the
1535
+ * repo is not a reason for the runtime message to be Portuguese too.
1536
+ */
1537
+ const SECRET_BLOCK_MESSAGE =
1538
+ '[plugin] Blocked: high-confidence secret detected in tool input — see .pantheon/logs/hooks.log'
1539
+
1540
+ /**
1541
+ * Message thrown when the secret scanner cannot produce a trustworthy verdict —
1542
+ * the script is missing/unexecutable, the child timed out or was killed, the
1543
+ * payload could not be serialized, the report was malformed, or the exit status
1544
+ * was unexpected.
1545
+ *
1546
+ * This is a deliberate fail-CLOSED denial. The previous handler blocked only
1547
+ * `code === 2` and treated every other outcome as advisory — but the runner
1548
+ * reports a missing script, a spawn failure and a payload-serialization failure
1549
+ * as `code: 1` too (src/plugins/hook-runner.ts), so a broken scanner read as a
1550
+ * clean advisory and the tool ran, silently disabling the only hard secret block
1551
+ * on the V2 surface.
1552
+ *
1553
+ * English and user-facing, like {@link SECRET_BLOCK_MESSAGE}. It carries no
1554
+ * scanner output on purpose: a scan that failed mid-flight may still be holding
1555
+ * the raw payload, and the denial must not become the leak it exists to prevent.
1556
+ */
1557
+ const SECRET_SCAN_UNAVAILABLE_MESSAGE =
1558
+ '[plugin] Blocked: the secret scanner could not complete, so this tool call was denied (fail-closed) — see .pantheon/logs/hooks.log'
1559
+
1560
+ /**
1561
+ * Append one masked, ISO-stamped line to .pantheon/logs/hooks.log under the
1562
+ * working directory, and return whether it landed.
1563
+ *
1564
+ * V1's `reportFailure` also writes to `client.app.log` and shows a TUI toast.
1565
+ * The V2 `PluginContext` exposes NEITHER (it is
1566
+ * `{options, agent, aisdk, catalog, command, integration, plugin, reference,
1567
+ * skill}` — no `client`, no `directory`), so this module has only the file
1568
+ * channel. That is a real reduction in observability versus V1, stated here
1569
+ * rather than implied. Best-effort by contract: a logging failure must never
1570
+ * take down the session.
1571
+ */
1572
+ function appendV2HookLog(line: string): boolean {
1573
+ const masked = maskSecret(line)
1574
+ if (masked === '') return false
1575
+ const stamp = new Date().toISOString()
1576
+ // Multi-line scanner stderr would otherwise produce continuation lines with
1577
+ // no timestamp (V1's P0-5 fix) — one message becomes N timestamped lines.
1578
+ const body = masked
1579
+ .split('\n')
1580
+ .map((part) => part.trim())
1581
+ .filter((part) => part !== '')
1582
+ .map((part) => `[${stamp}] ${part}`)
1583
+ .join('\n')
1584
+ if (body === '') return false
1585
+ try {
1586
+ const dir = path.join(process.cwd(), '.pantheon', 'logs')
1587
+ mkdirSync(dir, { recursive: true })
1588
+ appendFileSync(path.join(dir, 'hooks.log'), `${body}\n`, 'utf8')
1589
+ return true
1590
+ } catch {
1591
+ return false
1592
+ }
1593
+ }
1594
+
1595
+ // ─── BENCH Hook Timing (beta-10 latency slice, Phase 0) ────────────────
1596
+
1597
+ /**
1598
+ * BENCH INSTRUMENTATION — observation only, zero behavior change.
1599
+ *
1600
+ * The beta-10 latency slice measures the V2 tool hook chain. These helpers
1601
+ * record the start/end of `execute.before` and `execute.after` per tool call
1602
+ * and append one single-line `[bench]` entry per hook end to the EXISTING
1603
+ * hooks.log channel (same appendV2HookLog path as every other line: masked,
1604
+ * stamped, best-effort, never throwing). The lines are consumed by
1605
+ * bench/lib/hooklog.mjs.
1606
+ *
1607
+ * Deliberate properties:
1608
+ * - the log call happens in `finally`, so denied calls (read-only guard,
1609
+ * secret block) are timed too, and the denial still propagates unchanged
1610
+ * - the join key is the host callID (`event.id`); a TTL-bounded map prunes
1611
+ * stale entries so a background/never-after call cannot leak memory
1612
+ * - `since_before_ms=unavailable` when no before record exists — the bench
1613
+ * contract never lets "unavailable" be encoded as 0
1614
+ */
1615
+
1616
+ /** Entries older than this are pruned (a task tool result may never fire after). */
1617
+ const BENCH_TIMING_TTL_MS = 5 * 60_000
1618
+ /** Hard cap — mirrors the V1 delegationStarts bound. */
1619
+ const BENCH_TIMING_MAX = 256
1620
+
1621
+ const benchTimings = new Map<string, number>()
1622
+
1623
+ function pruneBenchTimings(now: number): void {
1624
+ for (const [callID, startedAt] of benchTimings) {
1625
+ if (now - startedAt > BENCH_TIMING_TTL_MS) benchTimings.delete(callID)
1626
+ }
1627
+ while (benchTimings.size >= BENCH_TIMING_MAX) {
1628
+ let oldestID: string | null = null
1629
+ let oldestAt = Number.POSITIVE_INFINITY
1630
+ for (const [id, at] of benchTimings) {
1631
+ if (at < oldestAt) {
1632
+ oldestAt = at
1633
+ oldestID = id
1634
+ }
1635
+ }
1636
+ if (oldestID === null) break
1637
+ benchTimings.delete(oldestID)
1638
+ }
1639
+ }
1640
+
1641
+ /** Read `{tool, id}` off a V2 tool event without assuming its exact shape. */
1642
+ function benchEventIdentity(event: unknown): { tool: string; callID: string } {
1643
+ if (event === null || typeof event !== 'object') return { tool: '', callID: '' }
1644
+ const payload = event as { tool?: unknown; id?: unknown }
1645
+ return {
1646
+ tool: typeof payload.tool === 'string' ? payload.tool : '',
1647
+ callID: typeof payload.id === 'string' ? payload.id : '',
1648
+ }
1649
+ }
1650
+
1651
+ /**
1652
+ * Append one `[bench]` timing line for a finished hook phase. Best-effort and
1653
+ * exception-free by construction (appendV2HookLog never throws).
1654
+ */
1655
+ function logBenchHookTiming(phase: 'before' | 'after', event: unknown, startedAt: number): void {
1656
+ try {
1657
+ const { tool, callID } = benchEventIdentity(event)
1658
+ const endedAt = Date.now()
1659
+ if (phase === 'before') {
1660
+ if (callID !== '') {
1661
+ benchTimings.set(callID, startedAt)
1662
+ pruneBenchTimings(startedAt)
1663
+ }
1664
+ appendV2HookLog(
1665
+ `[bench] tool.execute.before end tool=${tool} callID=${callID} ` +
1666
+ `started_at=${new Date(startedAt).toISOString()} duration_ms=${endedAt - startedAt}`,
1667
+ )
1668
+ return
1669
+ }
1670
+ const beforeAt = callID !== '' ? benchTimings.get(callID) : undefined
1671
+ if (beforeAt !== undefined) benchTimings.delete(callID)
1672
+ const sinceBefore = beforeAt === undefined ? 'unavailable' : String(endedAt - beforeAt)
1673
+ appendV2HookLog(
1674
+ `[bench] tool.execute.after end tool=${tool} callID=${callID} ` +
1675
+ `duration_ms=${endedAt - startedAt} since_before_ms=${sinceBefore}`,
1676
+ )
1677
+ } catch {
1678
+ // Instrumentation must never affect the hook chain.
1679
+ }
1680
+ }
1681
+
1682
+ // ─── V2 Secret-Scan Verdict ─────────────────────────────────────────────
1683
+
1684
+ /**
1685
+ * The scanner's own report marker, written to stderr on every non-clean run
1686
+ * (exit 1 advisory, exit 2 block). It is the discriminator between a genuine
1687
+ * low-confidence advisory and a runner infrastructure failure, BOTH of which
1688
+ * surface as `code === 1`: the runner's own failures (missing/unexecutable
1689
+ * script, spawn error, payload-serialization error) resolve a structured
1690
+ * `HookResult` with `code: 1` and no scan report, while the real scanner's
1691
+ * advisory always carries this marker. Requiring it means a scanner that stops
1692
+ * reporting fails toward a denial, never toward a silent allow.
1693
+ */
1694
+ const SECRET_SCAN_MARKER = '[SECRET SCAN]'
1695
+
1696
+ /** Sanitized failure classes — logged in place of raw scanner output. */
1697
+ type SecretScanFailureReason =
1698
+ | 'scanner-timeout'
1699
+ | 'scanner-signal'
1700
+ | 'scanner-spawn-failure'
1701
+ | 'scanner-serialization-failure'
1702
+ | 'scanner-malformed-output'
1703
+ | 'scanner-unexpected-exit'
1704
+
1705
+ type SecretScanDecision =
1706
+ | { action: 'allow' }
1707
+ | { action: 'advisory' }
1708
+ | { action: 'block' }
1709
+ | { action: 'fail-closed'; reason: SecretScanFailureReason }
1710
+
1711
+ /**
1712
+ * The runner's own infrastructure-failure messages (see hook-runner.ts), matched
1713
+ * at the start of stderr where the runner is the only writer. Matching a prefix
1714
+ * rather than a substring keeps a scan report that merely happens to quote one
1715
+ * of these phrases from flipping a valid advisory into a denial.
1716
+ */
1717
+ const SCANNER_INFRA_FAILURES: ReadonlyArray<[string, SecretScanFailureReason]> = [
1718
+ ['payload serialization failed:', 'scanner-serialization-failure'],
1719
+ ['spawn failed:', 'scanner-spawn-failure'],
1720
+ ['hook script failed to spawn:', 'scanner-spawn-failure'],
1721
+ ]
1722
+
1723
+ /**
1724
+ * Classify one secret-scan {@link HookResult} into an enforcement decision.
1725
+ *
1726
+ * fail-closed by construction: `allow` and `advisory` are reachable only from a
1727
+ * result that is unambiguously a completed scanner run. Everything else —
1728
+ * timeout, signal, spawn/serialization failure, missing report, unknown or
1729
+ * unexpected exit status — denies. `advisory` additionally requires the
1730
+ * scanner's own report marker, which is what separates an exit-1 advisory from
1731
+ * the runner's exit-1 infrastructure failure.
1732
+ *
1733
+ * `block` covers the high-confidence match (exit 2); the caller turns it into
1734
+ * the user-facing block.
1735
+ */
1736
+ function evaluateSecretScanResult(scan: HookResult): SecretScanDecision {
1737
+ if (scan.timedOut) return { action: 'fail-closed', reason: 'scanner-timeout' }
1738
+ if (scan.signal !== null) return { action: 'fail-closed', reason: 'scanner-signal' }
1739
+ if (!Number.isInteger(scan.code)) {
1740
+ return { action: 'fail-closed', reason: 'scanner-malformed-output' }
1741
+ }
1742
+ for (const [signature, reason] of SCANNER_INFRA_FAILURES) {
1743
+ if (scan.stderr.startsWith(signature)) return { action: 'fail-closed', reason }
1744
+ }
1745
+ if (scan.code === 0) return { action: 'allow' }
1746
+ if (scan.code === 2) return { action: 'block' }
1747
+ if (scan.code === 1) {
1748
+ return scan.stderr.includes(SECRET_SCAN_MARKER)
1749
+ ? { action: 'advisory' }
1750
+ : { action: 'fail-closed', reason: 'scanner-malformed-output' }
1751
+ }
1752
+ return { action: 'fail-closed', reason: 'scanner-unexpected-exit' }
1753
+ }
1754
+
1755
+ /** Invocation of the secret scan used by the tool guard. */
1756
+ type SecretScanRunner = (payload: HookPayload) => Promise<HookResult>
1757
+
1758
+ /**
1759
+ * The scan runs IN-PROCESS (src/pantheon/hook-engine.ts, same patterns and
1760
+ * exit-code contract as the former scripts/hooks/scan-secrets.sh) so a tool
1761
+ * call no longer spawns a bash child. The runner signature and the classifier
1762
+ * below are unchanged; {@link setV2SecretScanRunnerForTests} still injects
1763
+ * structured results the in-process path cannot produce on its own.
1764
+ */
1765
+ const defaultSecretScanRunner: SecretScanRunner = async (payload) => runSecretScanInProcess(payload)
1766
+
1767
+ let secretScanRunner: SecretScanRunner = defaultSecretScanRunner
1768
+
1769
+ /**
1770
+ * Test seam — override (or, with `null`, restore) the V2 secret-scan runner.
1771
+ *
1772
+ * Exported only for tests/pantheon/plugin-contract.test.ts, which injects
1773
+ * structured {@link HookResult}s (missing scanner, timeout, malformed output)
1774
+ * that the real script cannot be made to produce on demand. There is no
1775
+ * production caller; the shipped handler always uses `defaultSecretScanRunner`.
1776
+ */
1777
+ export function setV2SecretScanRunnerForTests(runner: SecretScanRunner | null): void {
1778
+ secretScanRunner = runner ?? defaultSecretScanRunner
1779
+ }
1780
+
1781
+ // ─── V2 Tool Hooks ──────────────────────────────────────────────────────
1782
+
1783
+ /**
1784
+ * The `tool.execute.before` event as the host dispatches it (opencode 2.0.22).
1785
+ *
1786
+ * Transcribed from the host's tool service:
1787
+ *
1788
+ * trigger("tool", "execute.before", { tool, sessionID, agent, messageID, id, input })
1789
+ *
1790
+ * Two shape differences from V1's positional `(input, output)` pair, both
1791
+ * handled by {@link adaptV2ExecuteBeforeEvent}: the host passes ONE payload
1792
+ * object, and the tool arguments live on `input` where V1 called them
1793
+ * `output.args`.
1794
+ *
1795
+ * `agent` is a required field of the host's tool context
1796
+ * (`ToolInvocation.context = { sessionID, agent, messageID, id }`), so the
1797
+ * active agent arrives on the very event the enforcement guard needs. V1 had to
1798
+ * learn it from a separate `chat.params` hook and keep a session→agent map; V2
1799
+ * does not have to, and neither does this module.
1800
+ */
1801
+ interface V2ToolExecuteBeforeEvent {
1802
+ tool?: unknown
1803
+ sessionID?: unknown
1804
+ messageID?: unknown
1805
+ agent?: unknown
1806
+ id?: unknown
1807
+ input?: unknown
1808
+ }
1809
+
1810
+ /**
1811
+ * Read-only enforcement for the V2 tool surface.
1812
+ *
1813
+ * The same factory, the same `DEFAULT_BLOCKED_TOOLS` and the same read-only set
1814
+ * that V1 uses, so the two surfaces cannot drift on what counts as a mutating
1815
+ * tool — `hashline_edit` and `pantheon_model` are denied here for exactly the
1816
+ * reason they are denied in V1.
1817
+ *
1818
+ * Deliberately NOT passed `getSessionAgent` / `isRootSession` / `isChildSession`.
1819
+ * There are TWO distinct reasons, and conflating them is what produced a wrong
1820
+ * causal chain here once already — keep them apart:
1821
+ *
1822
+ * 1. MISSING `getSessionAgent` (wiring). This is what would deny every
1823
+ * `task()` call. V2 learns the active agent from the `execute.before` event
1824
+ * itself and keeps no session→agent map, so there is no lookup to hand the
1825
+ * guard. The guard would call `isDelegationAllowed(undefined, target)`,
1826
+ * which returns `false`, and throw "caller agent is unavailable" — for
1827
+ * every caller, including Zeus. Note what is NOT happening: an unseeded
1828
+ * `isRootSession` would *pass* the root gate (`isRoot` reports `true` for an
1829
+ * unknown session), so the hierarchy is not what denies here.
1830
+ *
1831
+ * 2. UNWIRED HIERARCHY (design). `SessionHierarchyRegistry` is what gates
1832
+ * exactly two things, and nothing else: the depth-2 child deny
1833
+ * (`isChildSession`) and the root-session gate (`isRootSession`). Left
1834
+ * unseeded, `isChild` is `false` for every session, so depth-2 would never
1835
+ * fire on a genuine child — a hierarchy that cannot tell a child from a root
1836
+ * is not a trustworthy input to either check.
1837
+ *
1838
+ * "Unwired", not "impossible": the V2 `session.created` event carries
1839
+ * `properties.info: Session` including `parentID?`, the same field V1 seeds
1840
+ * from on the same event, so one line in `onSessionCreated` would seed live
1841
+ * sessions (see its docstring). What has no V2 equivalent is V1's SECOND
1842
+ * source, the `client.session.list()` startup seed — V2's `PluginContext`
1843
+ * exposes no `client`. Whether a live 2.0.22 host populates `info.parentID`
1844
+ * is UNVERIFIED; no canary reads an event payload. So the correct summary is
1845
+ * "seeded for nothing", not "unseedable", and the guard's omission is right
1846
+ * today for the weaker reason that nothing seeds it at all.
1847
+ *
1848
+ * Omitting all three skips the branch wholesale: the guard only enters it when
1849
+ * `options?.isRootSession !== undefined`. `task` is still denied inside a
1850
+ * read-only session via the blocked-tool list, so the read-only half of depth-2
1851
+ * holds for apollo/gaia.
1852
+ *
1853
+ * The caller/target half is NOT this guard's job on V2, and that is a division
1854
+ * of labour rather than a gap: V2 delegates through the native `subagent` tool
1855
+ * and its `permission.hook('evaluate')` handler, which calls
1856
+ * `evaluateV2Delegation` — the matrix (zeus → anyone; athena/hermes → apollo)
1857
+ * plus the same depth-2 rule, expressed as "a caller session that carries a
1858
+ * `parentID` is denied". Both are proved in
1859
+ * tests/pantheon/plugin-contract.test.ts and
1860
+ * tests/pantheon/delegation-policy.test.ts.
1861
+ *
1862
+ * The Zeus read guard is a SEPARATE call in the same `execute.before` handler
1863
+ * (issue #264), fed from the same event `agent`; it is not part of this guard.
1864
+ */
1865
+ const v2EnforcementGuard = createEnforcementGuard({
1866
+ getReadOnlySessions: () => readOnlyRegistry.sessionIDs(),
1867
+ })
1868
+
1869
+ /**
1870
+ * Project a V2 `execute.before` event onto the two-argument shape
1871
+ * `createEnforcementGuard` was built for.
1872
+ *
1873
+ * `tool` is the host's registration id, computed as
1874
+ * `options.namespace === undefined ? name : `${namespace}_${name}``. Pantheon
1875
+ * declares a namespace for catalog grouping but sets `options.namespace` on no
1876
+ * tool, so the id is the bare name (`hashline_edit`) and the blocked-tool match
1877
+ * fires. A tool that opted into `options.namespace` would gain a prefix and stop
1878
+ * matching — the integration test in tests/pantheon/plugin-contract.test.ts
1879
+ * drives the real registration path and asserts on the registered names, so
1880
+ * that drift fails a test instead of silently disabling enforcement.
1881
+ *
1882
+ * A missing `sessionID` maps to the empty key: the registry lookup then matches
1883
+ * the event's own (absent) identity, so a blocked tool in a read-only session is
1884
+ * still denied. Fail-closed on the one axis that matters.
1885
+ */
1886
+ function adaptV2ExecuteBeforeEvent(event: unknown): {
1887
+ input: ToolExecuteBeforeInput
1888
+ output: ToolExecuteBeforeOutput
1889
+ agent: unknown
1890
+ } {
1891
+ const payload = (event ?? {}) as V2ToolExecuteBeforeEvent
1892
+ return {
1893
+ input: {
1894
+ tool: typeof payload.tool === 'string' ? payload.tool : '',
1895
+ sessionID: typeof payload.sessionID === 'string' ? payload.sessionID : '',
1896
+ callID: typeof payload.id === 'string' ? payload.id : '',
1897
+ },
1898
+ output: { args: payload.input },
1899
+ agent: payload.agent,
1900
+ }
1901
+ }
1902
+
1903
+ /**
1904
+ * Test seam — override (or, with `null`, restore) the V2 shell-hook runner.
1905
+ *
1906
+ * Exported only for tests/pantheon/plugin-contract.test.ts, which asserts
1907
+ * that the REGISTERED `execute.before`/`execute.after` handlers invoke the
1908
+ * formatter and the delegation audit scripts. Spawning the real scripts would
1909
+ * make the assertion depend on the shell, not on the wiring; the scripts
1910
+ * themselves are covered by tests/pantheon/shell-hooks.test.ts.
1911
+ */
1912
+ export function setV2ShellRunnerForTests(runner: V2ShellRunner | null): void {
1913
+ shellRunnerOverride = runner ?? undefined
1914
+ }
1915
+
1916
+ let shellRunnerOverride: V2ShellRunner | undefined
1917
+
1918
+ /**
1919
+ * Test seam — clear the module-level idle todo enforcer.
1920
+ *
1921
+ * Exported only for tests/pantheon/plugin-contract.test.ts, which must
1922
+ * start from "no enforcer" when asserting the construction path.
1923
+ */
1924
+ export function resetV2IdleEnforcerForTests(): void {
1925
+ idleTodoEnforcer = undefined
1926
+ }
1927
+
1928
+ /**
1929
+ * Register tool execution hooks via V2 ctx.tool.hook.
1930
+ *
1931
+ * The V2 tool.hook API (when available) provides:
1932
+ * ctx.tool.hook("execute.before", handler) — pre-execution guard
1933
+ * ctx.tool.hook("execute.after", handler) — post-execution augment
1934
+ *
1935
+ * Returns true if any hooks were registered.
1936
+ */
1937
+ async function registerV2ToolHooks(
1938
+ context: PluginContext,
1939
+ subagentOrigins: V2SubagentOriginRegistry,
1940
+ boundedReadOrigins?: V2BoundedReadOriginRegistry,
1941
+ jevRuntime?: V2JevDecisionRuntime,
1942
+ ): Promise<{ registered: boolean; beforeRegistered: boolean }> {
1943
+ const host = hostDomains(context)
1944
+ const toolCtx = host.tool
1945
+
1946
+ if (!toolCtx?.hook) {
1947
+ return { registered: false, beforeRegistered: false }
1948
+ }
1949
+
1950
+ // V1 shell-hook parity (#266): formatter on every after-event, delegation
1951
+ // audit start/stop. Both scripts are environment-independent, so they are
1952
+ // invoked through the same runner the secret scan uses.
1953
+ const shellHooks = createV2ShellHooks({
1954
+ ...(shellRunnerOverride === undefined ? {} : { run: shellRunnerOverride }),
1955
+ onUnkeyed: appendV2HookLog,
1956
+ })
1957
+
1958
+ // J1 risk-score advisory gate (jev-risk-gate.ts). Constructed ONLY when
1959
+ // PANTHEON_J1_RISK_SCORE is on AND the host runtime exposes the native
1960
+ // Decisions API (the same instance `pantheon_jev_decide` uses), so flag-off
1961
+ // is a hard zero: no sink, no observer, no per-call work. When enabled, the
1962
+ // observer runs the SAME gate chain as the explicit tool (config, consent,
1963
+ // ledger reservation, permission kill-switch) and records shadow records
1964
+ // only — it is fired WITHOUT await inside the before-handler (fire-and-
1965
+ // observe), self-bounds at 2s with an AbortController, and never retries.
1966
+ const j1Mode = j1ModeFromEnv()
1967
+ loadRuntimeOverrides()
1968
+ const j1OverrideOff = gateDisabled('gate-j1-risk-gate')
1969
+ if (j1OverrideOff) {
1970
+ appendV2HookLog(
1971
+ '[gate-j1-risk-gate] disabled by override — the J1 risk gate is off this session',
1972
+ )
1973
+ }
1974
+ let j1Observer: ((event: unknown) => Promise<J1Verdict | undefined>) | undefined
1975
+ if (jevRuntime !== undefined && j1Mode !== 'off' && !j1OverrideOff) {
1976
+ const j1Sink = createTelemetrySink()
1977
+ j1TelemetrySink = j1Sink
1978
+ j1Observer = createJ1RiskGateObserver({
1979
+ runtime: jevRuntime,
1980
+ mode: j1Mode,
1981
+ threshold: j1EnforceThresholdFromEnv(),
1982
+ sink: (record) => {
1983
+ j1Sink.emit({ ...record, mode: j1Mode === 'enforce' ? 'enforce' : 'shadow' })
1984
+ },
1985
+ })
1986
+ }
1987
+
1988
+ // J3 turn-complexity escalation (jev-escalation.ts) — SHADOW. Constructed
1989
+ // ONLY when PANTHEON_J3_ESCALATION is on AND the host runtime exposes the
1990
+ // native Decisions API (the same instance `pantheon_jev_decide` uses), so
1991
+ // flag-off is a hard zero: no sink, no observer, no per-dispatch work. When
1992
+ // enabled, the observer classifies ONE delegate dispatch (the native
1993
+ // `subagent` tool) through the SAME gate chain as the explicit tool and
1994
+ // records shadow records only — fired WITHOUT await inside the before-
1995
+ // handler (fire-and-observe), self-bounded at 2s with an AbortController,
1996
+ // never retried. The verdict NEVER changes the dispatched model in this
1997
+ // phase: the per-agent override mechanism for activation lives in
1998
+ // jev-escalation.ts and this wiring has no path to it (asserted
1999
+ // structurally by the contract test below — the override function's name
2000
+ // must not appear in this file at all).
2001
+ let j3Observer: ((event: unknown) => Promise<void>) | undefined
2002
+ if (jevRuntime !== undefined && j3EscalationEnabledFromEnv()) {
2003
+ const j3Sink = createTelemetrySink()
2004
+ j3TelemetrySink = j3Sink
2005
+ const j3Mirror = createJTelemetryMirror({ enabled: true })
2006
+ j3Observer = createJ3EscalationObserver({
2007
+ runtime: jevRuntime,
2008
+ sink: (record) => {
2009
+ const shadowRecord = { ...record, mode: 'shadow' }
2010
+ j3Sink.emit(shadowRecord)
2011
+ j3Mirror?.record(shadowRecord)
2012
+ },
2013
+ })
2014
+ }
2015
+
2016
+ // Symlink resolution for the Zeus read guard (#272). The predicate is pure,
2017
+ // so the filesystem work happens at this call site, rooted at the project
2018
+ // directory the host reports. Same mechanism as V1's (src/plugin.ts) so the
2019
+ // two registration paths stay consistent.
2020
+ const resolveGuardPath = createGuardPathResolver(host.location?.directory || process.cwd())
2021
+
2022
+ let registered = false
2023
+ let beforeRegistered = false
2024
+
2025
+ try {
2026
+ // "execute.before" — read-only enforcement. Throwing from this handler
2027
+ // DENIES the tool call and the host surfaces the message to the session,
2028
+ // which is how the guard blocks a mutating tool in a read-only session.
2029
+ //
2030
+ // This is the enforcement point for the V2 surface, not a delegation to
2031
+ // V1: `src/plugin.ts` is not loaded when only `plugin` is configured
2032
+ // (opencode.json `plugins`), so the V1 `tool.execute.before` hook does not
2033
+ // exist in that process. The guard below is instantiated here and consulted
2034
+ // here; without it the tools registered by registerV2Tools would be a live
2035
+ // write path in every session, including read-only ones.
2036
+ await toolCtx.hook('execute.before', async (event: unknown) => {
2037
+ const benchStartedAt = Date.now()
2038
+ const { input, output, agent } = adaptV2ExecuteBeforeEvent(event)
2039
+ try {
2040
+ // V2's equivalent of V1's `chat.params` trigger: the host puts the active
2041
+ // agent on the event itself, so registering here needs no separate hook
2042
+ // and no session→agent map. A non-read-only (or absent) agent revokes the
2043
+ // registration, which also covers an in-session agent switch.
2044
+ syncReadOnlySession(readOnlyRegistry, input.sessionID, agent)
2045
+ // Zeus read guard (issue #264). V1 wires this from its `chat.params`
2046
+ // session→agent map (`src/plugin.ts`); V2 has no such map because the
2047
+ // host puts the active agent on THIS event, so the guard is fed from
2048
+ // the event's `agent` field — the same identity the read-only
2049
+ // registry above already trusts.
2050
+ //
2051
+ // Fail-closed on casing: `zeusReadGuard` compares the agent with an
2052
+ // exact `!== 'zeus'`, so a host that reports `Zeus` would silently
2053
+ // disable the guard. Normalizing through the shared
2054
+ // `normalizeDelegationAgent` keeps the comparison meaningful without
2055
+ // changing the predicate V1 uses.
2056
+ //
2057
+ // Runs BEFORE the read-only guard, matching V1's chain order. Both
2058
+ // throw to deny; neither is inside the scanner's try/catch, so a
2059
+ // denial keeps propagating to the host. The resolver is V1's too:
2060
+ // every TARGET path is also checked in its SYMLINK-RESOLVED form
2061
+ // (#272), and a resolution failure denies.
2062
+ zeusReadGuard(input.tool, output.args, normalizeDelegationAgent(agent), resolveGuardPath)
2063
+ // Deliberately OUTSIDE the try/catch below: a read-only denial must keep
2064
+ // propagating to the host, not be swallowed as a scanner failure.
2065
+ await v2EnforcementGuard(input, output)
2066
+
2067
+ // High-confidence secret scan (scripts/hooks/scan-secrets.sh). This is the
2068
+ // ONLY hard block on the V2 surface, and it exists here — rather than via
2069
+ // `src/plugins/pantheon-hooks.ts` — because that module is a separate
2070
+ // plugin that is never loaded on a V2-only install: opencode.json
2071
+ // `plugins` declares only `src/plugin`. V1's scan-secrets block was
2072
+ // therefore inert by construction, not by misconfiguration.
2073
+ //
2074
+ // exit 0 → allow. exit 1 with a valid scanner report → advisory, logged
2075
+ // only. exit 2 (high-confidence match) → deny. A scanner that does NOT
2076
+ // produce a trustworthy verdict — missing/unexecutable script, timeout,
2077
+ // killed child, spawn/serialization failure, malformed or unexpected
2078
+ // output — is fail-CLOSED: this pending tool call is denied, the session
2079
+ // is not. (runHook resolves a structured result instead of rejecting, so
2080
+ // the exit-code-only reading below cannot lean on an exception.)
2081
+ let blockError: Error | null = null
2082
+ try {
2083
+ const payload: HookPayload = {
2084
+ tool_name: input.tool,
2085
+ tool_input: output.args ?? {},
2086
+ agent_id: typeof agent === 'string' ? agent : '',
2087
+ session_id: input.sessionID,
2088
+ }
2089
+ const scan = await secretScanRunner(payload)
2090
+ const decision = evaluateSecretScanResult(scan)
2091
+ if (decision.action === 'block') {
2092
+ appendV2HookLog(SECRET_BLOCK_MESSAGE)
2093
+ appendV2HookLog(scan.stderr)
2094
+ blockError = new Error(SECRET_BLOCK_MESSAGE)
2095
+ } else if (decision.action === 'advisory') {
2096
+ // Advisory: log only, never block.
2097
+ appendV2HookLog(scan.stderr)
2098
+ } else if (decision.action === 'fail-closed') {
2099
+ // Sanitized failure category only — never the scanner's raw stderr,
2100
+ // which on a failure path is unverified and may carry the very
2101
+ // payload the scan exists to keep out of logs.
2102
+ appendV2HookLog(`${SECRET_SCAN_UNAVAILABLE_MESSAGE} (${decision.reason})`)
2103
+ blockError = new Error(SECRET_SCAN_UNAVAILABLE_MESSAGE)
2104
+ }
2105
+ } catch {
2106
+ // The runner is contracted to resolve a structured result, so this only
2107
+ // guards an unexpected throw (including a future change to the runner).
2108
+ // A scanner that cannot run is fail-CLOSED: deny this call rather than
2109
+ // let it through with no scan at all.
2110
+ appendV2HookLog(SECRET_SCAN_UNAVAILABLE_MESSAGE)
2111
+ blockError = new Error(SECRET_SCAN_UNAVAILABLE_MESSAGE)
2112
+ }
2113
+ if (blockError !== null) throw blockError
2114
+ const boundedReadOrigin = boundedReadOrigins?.capture(event)
2115
+ const eventTool = (event as V2ToolExecuteBeforeEvent | null)?.tool
2116
+ if (eventTool === BOUNDED_READ_TOOL && boundedReadOrigin === undefined) {
2117
+ throw new Error('BOUND_READ_UNAUTHORIZED')
2118
+ }
2119
+ if (boundedReadOrigin !== undefined) {
2120
+ writeV2AdmissionProof('tool.execute.before bounded-read', {
2121
+ sessionID: boundedReadOrigin.sessionID,
2122
+ messageID: boundedReadOrigin.messageID,
2123
+ callID: boundedReadOrigin.callID,
2124
+ agent: boundedReadOrigin.agent,
2125
+ })
2126
+ }
2127
+ const origin = subagentOrigins.capture(event)
2128
+ if (origin !== undefined) {
2129
+ writeV2AdmissionProof('tool.execute.before', { ...origin })
2130
+ }
2131
+ // J1 risk-score shadow observation. Deliberately AFTER every guard: a
2132
+ // denied call must not spend decision budget. Fire-and-observe — the
2133
+ // promise is deliberately NOT awaited, so the hook's latency is
2134
+ // unchanged; the observer self-bounds at 2s (AbortController),
2135
+ // contains its own failures, records at most one shadow record per
2136
+ // event, and never blocks, retries, or queues. Undefined (no-op) when
2137
+ // the flag is off — the only cost of the flag-on check below is the
2138
+ // truthiness read.
2139
+ if (j1Observer !== undefined && isRiskGateTarget((event as { tool?: unknown }).tool)) {
2140
+ // Ladder semantics: shadow/warn stay fire-and-observe (latency
2141
+ // unchanged); ENFORCE awaits (bounded 2s) and DENIES via throw —
2142
+ // the host surfaces the thrown message in the session, which is the
2143
+ // block's visible form. Unavailability never denies (fail-open by
2144
+ // design: a dead budget must not brick every shell call).
2145
+ if (j1Mode === 'enforce') {
2146
+ // The approval path (field beta.21: "exigir uma aprovação explícita
2147
+ // para execução" — a deny must be askable, not destructive): an
2148
+ // approved retry of the EXACT call (session + input hash, TTL
2149
+ // bounded) passes without re-asking.
2150
+ const enforceEvent = event as { tool?: unknown; input?: unknown; sessionID?: unknown }
2151
+ const sessionID =
2152
+ typeof enforceEvent.sessionID === 'string' ? enforceEvent.sessionID : ''
2153
+ const inputHash = approvalInputHash(enforceEvent.input)
2154
+ if (sessionID !== '' && hasApproval(sessionID, inputHash)) {
2155
+ // Approved by the user: execute — and still observe (the
2156
+ // approved execution is exactly the record the baseline wants).
2157
+ void j1Observer(event)
2158
+ return
2159
+ }
2160
+ const verdict = (await j1Observer(event)) as J1Verdict | undefined
2161
+ if (verdict?.block === true) {
2162
+ // The block is an APPROVAL REQUEST (not an error to route
2163
+ // around): ask the user through the `question` tool with the
2164
+ // marker below; an affirmative answer mints a hash-pinned,
2165
+ // TTL-bounded approval and the retry passes. Never echo the
2166
+ // tool input here — the arguments may carry the very secret
2167
+ // the risk score flagged; the agent owns its own rendering.
2168
+ throw new Error(
2169
+ `[J1 enforce] risco ${verdict.riskScore?.toFixed(2)} >= threshold ` +
2170
+ `— APROVAÇÃO EXPLÍCITA NECESSÁRIA: use a tool question com o nome ` +
2171
+ `"${j1ApprovalMarker(inputHash)}" perguntando ao USUÁRIO se aprova esta exata chamada ` +
2172
+ '(apresente a ferramenta e o que ela faria, sem executá-la nem contorná-la). ' +
2173
+ 'Se ele aprovar, reintente a MESMA chamada — ela passará. Se ele recusar, siga sem o ' +
2174
+ 'passo arriscado ou entregue a execução manual a ele.',
2175
+ )
2176
+ }
2177
+ } else {
2178
+ void j1Observer(event)
2179
+ }
2180
+ }
2181
+ // J3 turn-complexity shadow classification. Same fire-and-observe
2182
+ // discipline as J1: the dispatch's latency is unchanged, the observer
2183
+ // self-bounds at 2s, contains its own failures, records at most one
2184
+ // shadow record per dispatch, and never blocks, retries, or queues.
2185
+ // The recorded verdict NEVER changes the dispatched model (shadow
2186
+ // contract); undefined (no-op) when the flag is off.
2187
+ if (j3Observer !== undefined && isSubagentDispatchEvent(event)) {
2188
+ void j3Observer(event)
2189
+ }
2190
+ // Delegation audit START record (#266). Deliberately AFTER every guard
2191
+ // and the secret scan: a denied call must not leave a start record with
2192
+ // no matching stop. The formatter/stop halves run in `execute.after`.
2193
+ await shellHooks.before(event)
2194
+ } finally {
2195
+ // BENCH instrumentation — observation only; runs on the deny paths too.
2196
+ logBenchHookTiming('before', event, benchStartedAt)
2197
+ }
2198
+ })
2199
+ registered = true
2200
+ beforeRegistered = true
2201
+ } catch {
2202
+ // Tool before-hook not supported
2203
+ }
2204
+
2205
+ try {
2206
+ // "execute.after" — the V1 parity chain (task-result-guard →
2207
+ // context-sandbox → read-enhancer) rebuilt on the V2 event shape.
2208
+ //
2209
+ // This IS behaviour, not a registration point: on a V2-only install the V1
2210
+ // `pantheon-hooks` plugin is not loaded, so this handler is the only thing
2211
+ // that truncates oversized output and tags `read` with hashline refs.
2212
+ // The sandbox config comes from `ctx.options.context_sandbox` (the V2 copy
2213
+ // the installer writes — V2.0.25 drops the V1 top-level key), resolved with
2214
+ // the same resolver V1 uses.
2215
+ const v2ExecuteAfter = createV2ExecuteAfter({
2216
+ sandbox: resolveV2SandboxConfig(context.options),
2217
+ })
2218
+ await toolCtx.hook('execute.after', async (event: unknown) => {
2219
+ const benchStartedAt = Date.now()
2220
+ try {
2221
+ subagentOrigins.forget(event)
2222
+ boundedReadOrigins?.forget(event)
2223
+ // J1 approval minter: the user's affirmative answer to a
2224
+ // `j1-approval-<hash12>` question mints the hash-pinned, TTL-bounded
2225
+ // approval the enforce gate checks. Only the OBSERVED host result can
2226
+ // mint — the agent cannot fabricate an answer.
2227
+ if (j1Mode === 'enforce') {
2228
+ try {
2229
+ const after = (event ?? {}) as {
2230
+ tool?: unknown
2231
+ sessionID?: unknown
2232
+ output?: unknown
2233
+ input?: unknown
2234
+ }
2235
+ if (after.tool === 'question') {
2236
+ const sessionID = typeof after.sessionID === 'string' ? after.sessionID : ''
2237
+ const serialized = JSON.stringify(after.output ?? {}) ?? ''
2238
+ const markerMatch = serialized.match(/j1-approval-([0-9a-f]{12})/)
2239
+ const markerHash = markerMatch?.[1]
2240
+ if (sessionID !== '' && markerHash !== undefined) {
2241
+ const name = `j1-approval-${markerHash}`
2242
+ if (isAffirmativeAnswer(name, serialized)) {
2243
+ mintApproval(sessionID, markerHash)
2244
+ }
2245
+ }
2246
+ }
2247
+ } catch {
2248
+ // The minter is best-effort; a parse failure just means no
2249
+ // approval (fail-closed).
2250
+ }
2251
+ }
2252
+ await v2ExecuteAfter(event)
2253
+ // Formatter + delegation audit STOP (#266). Awaited for the same
2254
+ // reason V1 awaits it: the log record should exist before the tool
2255
+ // result is surfaced. Failures are swallowed inside the module.
2256
+ await shellHooks.after(event)
2257
+ } finally {
2258
+ // BENCH instrumentation — observation only; the awaited call means the
2259
+ // duration covers the whole parity chain, not just its dispatch.
2260
+ logBenchHookTiming('after', event, benchStartedAt)
2261
+ }
2262
+ })
2263
+ registered = true
2264
+ } catch {
2265
+ // Tool after-hook not supported
2266
+ }
2267
+
2268
+ return { registered, beforeRegistered }
2269
+ }
2270
+
2271
+ // ─── V2 Permission Hook ─────────────────────────────────────────────────
2272
+
2273
+ /**
2274
+ * Read `event.effect` after P8 wrote to it, for the record.
2275
+ *
2276
+ * A hostile getter reads as `null`, which can only downgrade a recorded
2277
+ * `narrow` to `keep`, never upgrade one — the failure direction is "the record
2278
+ * claims less", never "the record claims an effect the event does not hold".
2279
+ */
2280
+ function readPermissionEffect(event: unknown): string | null {
2281
+ try {
2282
+ if (event === null || typeof event !== 'object') return null
2283
+ const effect = (event as { readonly effect?: unknown }).effect
2284
+ return typeof effect === 'string' ? effect : null
2285
+ } catch {
2286
+ return null
2287
+ }
2288
+ }
2289
+
2290
+ /**
2291
+ * Register permission hook via V2 ctx.permission.hook.
2292
+ *
2293
+ * The V2 permission.hook API (when available) provides:
2294
+ * ctx.permission.hook("evaluate", handler) — host permission evaluation
2295
+ * The handler receives one mutable PermissionEvaluation event; decisions are
2296
+ * written to event.effect/event.message (there is no separate V1-style output).
2297
+ *
2298
+ * Returns true if the hook was registered.
2299
+ */
2300
+ async function registerV2PermissionHook(
2301
+ context: PluginContext,
2302
+ subagentOrigins: V2SubagentOriginRegistry,
2303
+ ): Promise<boolean> {
2304
+ const domains = hostDomains(context)
2305
+ const permCtx = domains.permission
2306
+
2307
+ if (!permCtx?.hook) {
2308
+ markUnsupported('permission-hook')
2309
+ return false
2310
+ }
2311
+
2312
+ // P8 guardrail (PLAN §5 P8, Phase 5). Constructed once at registration and
2313
+ // inert by default: `PANTHEON_P8_GUARDRAIL` is absent in a default
2314
+ // install, and absent means disabled — this ships no behavioural change.
2315
+ // Enabled, it may only replace a wider effect with `deny`; it is synchronous,
2316
+ // never throws, and never runs for `decision.egress` or an existing deny.
2317
+ // Its outcome is recorded through the 0b telemetry path (in-memory, bounded,
2318
+ // I/O-free) so a narrow, a refusal and a rejected write are observable; the
2319
+ // disabled guardrail emits nothing.
2320
+ const p8Guardrail = createP8Guardrail({ enabled: p8GuardrailEnabledFromEnv() })
2321
+ const p8Sink = createTelemetrySink()
2322
+ p8TelemetrySink = p8Sink
2323
+ // The record's `mode` mirrors the P8 registry entry — `off` today — instead
2324
+ // of asserting `active` (N10a). A record may never advertise an activation
2325
+ // the registry and C8 deny, and deriving the value from the registry means
2326
+ // the two cannot drift apart again. `mode` describes the point's declared
2327
+ // mode; `decision`/`reason` carry the observation.
2328
+ const p8RegistryMode = DECISION_POINT_REGISTRY.find((point) => point.id === 'P8')?.mode ?? 'off'
2329
+ /**
2330
+ * Record one P8 outcome.
2331
+ *
2332
+ * `event` is re-read immediately before emitting: `narrowed`/`wrote` are the
2333
+ * guardrail's own post-write read, and a `Proxy` whose descriptor trap lies
2334
+ * can make that read and the next one disagree (N9). A `narrow` is therefore
2335
+ * recorded only when the event still holds `deny`; otherwise the record
2336
+ * states the effect that is actually there (`guardrail.keep` with
2337
+ * `p8.write.unconfirmed`), so sink and proof cannot contradict each other.
2338
+ */
2339
+ const recordP8 = (result: ReturnType<typeof p8Guardrail.apply>, event: unknown): void => {
2340
+ if (!p8Guardrail.enabled) return
2341
+ try {
2342
+ const unconfirmed = result.narrowed && readPermissionEffect(event) !== 'deny'
2343
+ p8Sink.emit({
2344
+ point: 'P8',
2345
+ decision: unconfirmed ? 'guardrail.keep' : result.decision,
2346
+ reason: unconfirmed ? 'p8.write.unconfirmed' : result.reason,
2347
+ mode: p8RegistryMode,
2348
+ })
2349
+ } catch {
2350
+ // Telemetry is best-effort and must not affect permission flow.
2351
+ }
2352
+ }
2353
+
2354
+ try {
2355
+ await permCtx.hook('evaluate', async (rawEvent: unknown) => {
2356
+ const event = rawEvent as V2PermissionEvent | null
2357
+ const effectBefore = event?.effect
2358
+ let origin: ReturnType<V2SubagentOriginRegistry['consume']>
2359
+ let decision: string | null = null
2360
+ let callerSessionParentID: unknown
2361
+ const writeProof = (): void => {
2362
+ const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF
2363
+ if (!proofPath || !event || !Array.isArray(event.resources)) return
2364
+ try {
2365
+ appendFileSync(
2366
+ proofPath,
2367
+ `permission.evaluate ${JSON.stringify({
2368
+ action: event.action,
2369
+ resources: event.resources,
2370
+ agent: event.agent,
2371
+ sessionID: event.sessionID,
2372
+ callerSessionParentID: callerSessionParentID ?? null,
2373
+ source: event.source,
2374
+ matchedOrigin: origin ?? null,
2375
+ decision,
2376
+ effect: event.effect,
2377
+ message: event.message,
2378
+ eventFields: ['action', 'resources', 'agent', 'sessionID', 'source', 'effect'].filter(
2379
+ (key) => Object.hasOwn(event, key),
2380
+ ),
2381
+ effectBefore: effectBefore ?? null,
2382
+ effectAfter: event.effect ?? null,
2383
+ })}\n`,
2384
+ )
2385
+ } catch {
2386
+ // Instrumentation is best-effort and must not affect permission flow.
2387
+ }
2388
+ }
2389
+ const deny = (reason: string): void => {
2390
+ if (event === null || typeof event !== 'object') {
2391
+ throw new Error(
2392
+ `permission event is unavailable; denying V2 permission evaluation (${reason})`,
2393
+ )
2394
+ }
2395
+ event.effect = 'deny'
2396
+ event.message = `Pantheon delegation denied: ${reason}`
2397
+ if (event.effect !== 'deny') {
2398
+ throw new Error(
2399
+ `permission event is not mutable; denying V2 permission evaluation (${reason})`,
2400
+ )
2401
+ }
2402
+ writeProof()
2403
+ }
2404
+
2405
+ if (event?.effect === 'deny') {
2406
+ writeProof()
2407
+ return // explicit host deny is final
2408
+ }
2409
+ if (event == null) {
2410
+ deny('permission event is missing')
2411
+ return
2412
+ }
2413
+ // `decision.egress` is Pantheon's own custom action. It is NOT decided
2414
+ // here: the user-level config/consent is the source of truth, and the
2415
+ // host's own permission rules are the kill-switch (see
2416
+ // local-decision-egress-gate). The v2.2.0 canary observed this hook runs
2417
+ // on the allow path of `permission.assert` and is skipped for an explicit
2418
+ // deny, so egress must never depend on it. Leaving the effect untouched
2419
+ // preserves whatever the host decided.
2420
+ if (event.action === DECISION_EGRESS_ACTION) {
2421
+ writeProof()
2422
+ return
2423
+ }
2424
+ if (!Array.isArray(event.resources) || event.resources.length === 0) {
2425
+ deny('permission resources are missing or malformed')
2426
+ return
2427
+ }
2428
+ const targets = event.resources.map(v2ResourceTarget)
2429
+ if (targets.some((target) => target === undefined)) {
2430
+ deny('permission resource target is malformed')
2431
+ return
2432
+ }
2433
+ const hasPantheonTarget = targets.some((target) => PANTHEON_AGENTS.has(target ?? ''))
2434
+ let session: AuthoritativeSession | undefined
2435
+ if (hasPantheonTarget) {
2436
+ origin = subagentOrigins.consume(event)
2437
+ if (origin === undefined) {
2438
+ deny('matching host subagent tool origin is missing or stale')
2439
+ return
2440
+ }
2441
+ const sessionID = typeof event.sessionID === 'string' ? event.sessionID.trim() : ''
2442
+ if (!sessionID) {
2443
+ deny('caller session ID is missing')
2444
+ return
2445
+ }
2446
+
2447
+ const sessionDomain = domains.session
2448
+ if (!sessionDomain || typeof sessionDomain.get !== 'function') {
2449
+ deny('session lookup API is unavailable')
2450
+ return
2451
+ }
2452
+
2453
+ let retrieved: unknown
2454
+ try {
2455
+ retrieved = await sessionDomain.get({ sessionID })
2456
+ } catch {
2457
+ deny('caller session lookup failed')
2458
+ return
2459
+ }
2460
+ if (retrieved === null || retrieved === undefined) {
2461
+ deny('caller session was not found')
2462
+ return
2463
+ }
2464
+ if (typeof retrieved !== 'object' || Array.isArray(retrieved)) {
2465
+ deny('caller session lookup returned invalid data')
2466
+ return
2467
+ }
2468
+ session = retrieved as AuthoritativeSession
2469
+ callerSessionParentID = session.parentID
2470
+ }
2471
+
2472
+ // Native-only resources remain under host policy. If a Pantheon target
2473
+ // appears anywhere, the shared policy evaluates the complete resource set.
2474
+ decision = evaluateV2Delegation(event, session, event.effect, origin)
2475
+
2476
+ // P8 (Phase 5): read the effect left in place and, only when the flag is
2477
+ // on and a declared rule matches, replace it with `deny`. Off by default,
2478
+ // synchronous, contained — it cannot grant, delay or throw into admission.
2479
+ //
2480
+ // Apply BEFORE recording (PH5-1): `writeProof` reads `event.effect`, so a
2481
+ // proof written first recorded `effectAfter: allow` for an event P8 then
2482
+ // narrowed. The order below is apply → final effect → record, and the
2483
+ // record carries the post-apply effect plus the guardrail outcome.
2484
+ //
2485
+ // Record only after the effect is final (N10b). `deny()` below rewrites
2486
+ // the effect, and a record emitted before it would describe a state the
2487
+ // handler never leaves behind; when the delegation policy already denies,
2488
+ // the deny is the policy's, so P8 claims no narrowing at all — it changed
2489
+ // nothing about that outcome. `deny()` also throws on an immutable event,
2490
+ // and a record emitted after a throw would describe an unreached state.
2491
+ const p8Result = p8Guardrail.apply(event)
2492
+ if (decision === 'deny') {
2493
+ deny('caller or target is not allowed by delegation policy')
2494
+ return
2495
+ }
2496
+ writeProof()
2497
+ recordP8(p8Result, event)
2498
+ })
2499
+ return true
2500
+ } catch {
2501
+ markUnsupported('permission-hook')
2502
+ return false
2503
+ }
2504
+ }
2505
+
2506
+ // ─── Tool Definition Factory ─────────────────────────────────────────────
2507
+
2508
+ /**
2509
+ * Minimal structural view of the V2 tool draft.
2510
+ *
2511
+ * `output` is REQUIRED. The host (opencode 2.0.22) enforces a biconditional on
2512
+ * a tool's declared `output` and the value its `execute` resolves to:
2513
+ * `def.output === undefined` together with `'output' in result` throws
2514
+ * "Tool result declared output without an output schema", and a declared
2515
+ * `output` whose result omits the key throws "Tool did not return its
2516
+ * declared output". A missing declaration therefore fails every call, so the
2517
+ * field is mandatory here rather than optional.
2518
+ */
2519
+ interface V2ToolDraft {
2520
+ namespace(config: { name: string; description: string }): void
2521
+ add(tool: {
2522
+ name: string
2523
+ description: string
2524
+ input: Record<string, unknown>
2525
+ output: Record<string, unknown>
2526
+ execute: (input: Record<string, unknown>, context: unknown) => Promise<V2ToolResult>
2527
+ }): void
2528
+ }
2529
+
2530
+ export type { V2ToolDef, V2ToolResult } from './pantheon/tools.ts'
2531
+
2532
+ // ─── Plugin Definition ───────────────────────────────────────────────────
2533
+
2534
+ /** Event type from V2 event stream. */
2535
+ interface V2SessionEvent {
2536
+ type: string
2537
+ properties?: Record<string, unknown>
2538
+ data?: unknown
2539
+ }
2540
+
2541
+ /** Opt-in trace used by the isolated F4A canary; never logs prompts or inputs. */
2542
+ function writeV2AdmissionProof(label: string, detail: Record<string, unknown>): void {
2543
+ const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF
2544
+ if (!proofPath) return
2545
+ try {
2546
+ appendFileSync(proofPath, `${label} ${JSON.stringify(detail)}\n`)
2547
+ } catch {
2548
+ // Proof is best-effort and must not affect admission behavior.
2549
+ }
2550
+ }
2551
+
2552
+ async function prepareV2BoundedRead(
2553
+ context: PluginContext,
2554
+ ): Promise<ReturnType<typeof createV2BoundedReadTool> | undefined> {
2555
+ const host = hostDomains(context)
2556
+ const directory = host.location?.directory
2557
+ const projectID = host.location?.project?.id
2558
+ const session = host.session
2559
+ const permission = host.permission
2560
+ if (
2561
+ typeof directory !== 'string' ||
2562
+ directory.trim() === '' ||
2563
+ typeof projectID !== 'string' ||
2564
+ projectID.trim() === '' ||
2565
+ typeof session?.get !== 'function' ||
2566
+ typeof permission?.assert !== 'function' ||
2567
+ typeof host.event?.subscribe !== 'function' ||
2568
+ typeof host.tool?.transform !== 'function' ||
2569
+ typeof host.tool?.hook !== 'function'
2570
+ ) {
2571
+ markUnsupported('bounded-read')
2572
+ return undefined
2573
+ }
2574
+
2575
+ const rootDirectory = await realpathAsync(directory).catch(() => undefined)
2576
+ if (rootDirectory === undefined) {
2577
+ markUnsupported('bounded-read')
2578
+ return undefined
2579
+ }
2580
+
2581
+ return createV2BoundedReadTool({
2582
+ rootDirectory,
2583
+ projectID,
2584
+ getSession: (sessionID) => {
2585
+ if (typeof session.get !== 'function') throw new Error('session lookup unavailable')
2586
+ return session.get.call(session, { sessionID })
2587
+ },
2588
+ assertPermission: (request) => {
2589
+ if (typeof permission.assert !== 'function') throw new Error('permission API unavailable')
2590
+ return permission.assert.call(permission, request)
2591
+ },
2592
+ scanContent: async ({ content, agent, sessionID, callID }) => {
2593
+ try {
2594
+ const scan = await secretScanRunner({
2595
+ tool_name: BOUNDED_READ_TOOL,
2596
+ tool_input: { content },
2597
+ agent_id: agent,
2598
+ session_id: sessionID,
2599
+ })
2600
+ const decision = evaluateSecretScanResult(scan)
2601
+ if (decision.action === 'allow') return 'allow'
2602
+ const reason = decision.action === 'fail-closed' ? decision.reason : 'content-match'
2603
+ appendV2HookLog(
2604
+ `[SECRET SCAN] bounded read withheld session=${sessionID} callID=${callID} reason=${reason}`,
2605
+ )
2606
+ return decision.action === 'fail-closed' ? 'unavailable' : 'deny'
2607
+ } catch {
2608
+ appendV2HookLog(
2609
+ `[SECRET SCAN] bounded read withheld session=${sessionID} callID=${callID} reason=scanner-failure`,
2610
+ )
2611
+ return 'unavailable'
2612
+ }
2613
+ },
2614
+ })
2615
+ }
2616
+
2617
+ /** Cleanup function type. */
2618
+ type CleanupFn = () => void
2619
+
2620
+ /** Active cleanup handlers for the plugin lifecycle. */
2621
+ const activeCleanups: CleanupFn[] = []
2622
+
2623
+ export const plugin = define({
2624
+ id: 'pantheon-opencode',
2625
+
2626
+ async setup(context: PluginContext): Promise<void> {
2627
+ // ─── Phase 0: idle todo enforcer ─────────────────────────────────────
2628
+ // First, because the event subscription below can deliver `session.idle`
2629
+ // as soon as it starts: an enforcer installed after it would lose the
2630
+ // first idle of the process.
2631
+ //
2632
+ // Guarded, because an unguarded throw here would reject `setup()` and
2633
+ // remove every later registration with it. A degraded run is better
2634
+ // than none, and the degradation is reported instead of invisible.
2635
+ let idleEnforcer: TodoEnforcer | undefined
2636
+ try {
2637
+ idleEnforcer = installV2TodoEnforcer(context)
2638
+ } catch (error) {
2639
+ idleEnforcer = undefined
2640
+ idleTodoEnforcer = undefined
2641
+ markUnsupported('idle-todo-enforcer')
2642
+ if (!idleEnforcerFailureLogged) {
2643
+ idleEnforcerFailureLogged = true
2644
+ const reason = error instanceof Error ? error.message : String(error)
2645
+ appendV2HookLog(
2646
+ '[idle-todo-enforcer] construction failed; continuing without ' +
2647
+ 'idle continuation and todo context: ' +
2648
+ reason,
2649
+ )
2650
+ }
2651
+ }
2652
+
2653
+ // ─── Phase 1: V2 Transforms (isolated per-domain, best-effort) ────
2654
+ // Each transform registration is individually wrapped and settled via Promise.allSettled:
2655
+ // a rejection marks only that transform unsupported
2656
+ // and does not reject setup() or prevent later hook registrations.
2657
+ // See issue #92.
2658
+ //
2659
+ // Pantheon's Phase 1/config transform registrations cover agent, command,
2660
+ // and reference; ctx.tool.transform is attempted separately in Phase 2.
2661
+ // ctx.integration and ctx.skill are present on a live 2.0.22 host and neither
2662
+ // is registered here — that is a Pantheon scope choice, not a host gap.
2663
+ // ctx.catalog is the one domain the host does not provide.
2664
+ // Phase 1 registers against the SDK-typed `context.agent` / `.command` /
2665
+ // `.reference` directly; the host domains the SDK omits are reached only
2666
+ // through `hostDomains` (see the module header).
2667
+ const phase1Transforms: Array<{ feature: string; register: () => Promise<unknown> }> = [
2668
+ { feature: 'agent-transform', register: () => context.agent.transform(transformAgents) },
2669
+ {
2670
+ feature: 'command-transform',
2671
+ register: () => context.command.transform(transformCommands),
2672
+ },
2673
+ {
2674
+ feature: 'reference-transform',
2675
+ register: () => context.reference.transform(transformReferences),
2676
+ },
2677
+ ]
2678
+ const phase1Results = await Promise.allSettled(
2679
+ phase1Transforms.map((t) => Promise.resolve().then(() => t.register())),
2680
+ )
2681
+ phase1Results.forEach((result, index) => {
2682
+ // biome-ignore lint/style/noNonNullAssertion: index always in bounds — parallel arrays
2683
+ const feature = phase1Transforms[index]!.feature
2684
+ if (result.status === 'rejected') {
2685
+ markUnsupported(feature)
2686
+ }
2687
+ })
2688
+
2689
+ const subagentOrigins = new V2SubagentOriginRegistry()
2690
+ const boundedRead = await prepareV2BoundedRead(context).catch(() => undefined)
2691
+ if (boundedRead === undefined) markUnsupported('bounded-read')
2692
+
2693
+ // ─── Phase 2: V2 Permission Hook (best-effort) ───────────────────
2694
+ // Registered before the event subscription and session hooks so the
2695
+ // delegation matrix is enforced before any turn runs. Egress never depends
2696
+ // on this hook: the user-level config plus the host's own rules gate it.
2697
+ await registerV2PermissionHook(context, subagentOrigins).catch(() => false)
2698
+
2699
+ // ─── Phase 3: V2 Event Subscription (best-effort) ────────────────
2700
+ const eventCleanup = subscribeV2Events(context, boundedRead?.clearSession)
2701
+ if (eventCleanup) {
2702
+ activeCleanups.push(eventCleanup)
2703
+ } else {
2704
+ markUnsupported('event-stream')
2705
+ }
2706
+
2707
+ // ─── Phase 4: V2 Session Hooks (best-effort) ─────────────────────
2708
+ const sessionHooksRegistered = await registerV2SessionHooks(context).catch(() => false)
2709
+ if (!sessionHooksRegistered) {
2710
+ markUnsupported('session-hooks')
2711
+ }
2712
+
2713
+ // ─── Phase 5: V2 Tool Hooks (best-effort) ────────────────────────
2714
+ // The Jev runtime is built ONCE here and threaded to both consumers — the
2715
+ // tool registration (Phase 6) and the J1 risk-score observer inside the
2716
+ // execute.before hook — so `decide` and `permissionAssert` are bound to
2717
+ // their owning host domains exactly once. Pure construction over the host
2718
+ // domains: nothing is marked unsupported here; Phase 6 keeps that job.
2719
+ const jevRuntime = buildV2JevRuntime(hostDomains(context))
2720
+ const toolHookResult = await registerV2ToolHooks(
2721
+ context,
2722
+ subagentOrigins,
2723
+ boundedRead?.origins,
2724
+ jevRuntime,
2725
+ ).catch(() => ({ registered: false, beforeRegistered: false }))
2726
+ if (!toolHookResult.registered) {
2727
+ markUnsupported('tool-execute-hooks')
2728
+ }
2729
+
2730
+ // ─── Phase 6: V2 Tool Registration (best-effort) ─────────────────
2731
+ const boundedReadDefinition = toolHookResult.beforeRegistered
2732
+ ? boundedRead?.definition
2733
+ : undefined
2734
+ if (boundedRead !== undefined && boundedReadDefinition === undefined) {
2735
+ markUnsupported('bounded-read')
2736
+ }
2737
+ const toolsRegistered = await registerV2Tools(context, boundedReadDefinition, jevRuntime).catch(
2738
+ () => false,
2739
+ )
2740
+ if (!toolsRegistered) markUnsupported('tool-transform')
2741
+
2742
+ // ─── Phase 7: V2 Compaction Hook (best-effort) ───────────────────
2743
+ const compactionCtx = hostDomains(context).session
2744
+ if (compactionCtx?.hook) {
2745
+ // File-based goal store, constructed once: the compaction context needs
2746
+ // active goals per session, and the store needs no host API (same
2747
+ // `.pantheon/goals` directory V1 uses).
2748
+ const goalStore = new GoalStore({ dir: '.pantheon/goals' })
2749
+ // P9's record sink, created per registration (in-memory, bounded,
2750
+ // I/O-free) so one setup cannot observe another's records.
2751
+ const p9Sink = createTelemetrySink()
2752
+ p9TelemetrySink = p9Sink
2753
+ try {
2754
+ // 2.0.16 `SessionHooks` key is `compaction` (the migration doc maps
2755
+ // `experimental.session.compacting` → `ctx.session.hook("compaction")`).
2756
+ // `compacting` is not a valid key: the registry accepts any string and
2757
+ // silently drops unknown names, so the old name was a permanent no-op.
2758
+ // Proven by the canary's negative control.
2759
+ await compactionCtx.hook('compaction', async (event: unknown) => {
2760
+ try {
2761
+ // Opt-in lifetime proof for the host-backed hook canary
2762
+ // (tests/pantheon/plugin-hook-canary.test.mjs, MODE=real). It is
2763
+ // inert unless PANTHEON_HOOK_CANARY_LIFETIME_PROOF is set, so
2764
+ // production behaviour is unchanged. This exists because a rename to
2765
+ // `compacting` was a silent no-op for an unknown length of time: the
2766
+ // canary can now observe that THIS registration fired.
2767
+ if (process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF) {
2768
+ try {
2769
+ appendFileSync(
2770
+ process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF,
2771
+ 'plugin:session.hook:compaction\n',
2772
+ )
2773
+ } catch {
2774
+ // Proof is best-effort: never let instrumentation break the host.
2775
+ }
2776
+ }
2777
+
2778
+ // DCP dynamic context pruning (V2 only). This hook receives the
2779
+ // provider-bound array exactly before the summarization request,
2780
+ // and mutations are honored per request — the persisted session is
2781
+ // untouched. Apply the rules by default: it only changes what feeds
2782
+ // the summary. Never set `input.result`: the model must summarize
2783
+ // the pruned history, not be replaced by a canned summary.
2784
+ //
2785
+ // The host's compaction payload is
2786
+ // `{ session, agent, model, tools, system, messages, … }` — the id
2787
+ // is on `session.id`, NOT top-level `sessionID` (measured against
2788
+ // the 2.1.4 host; both spellings are accepted below).
2789
+ const payload = event as {
2790
+ sessionID?: unknown
2791
+ session?: { id?: unknown }
2792
+ messages?: unknown
2793
+ system?: unknown
2794
+ } | null
2795
+ const sessionID =
2796
+ typeof payload?.sessionID === 'string'
2797
+ ? payload.sessionID
2798
+ : typeof payload?.session?.id === 'string'
2799
+ ? payload.session.id
2800
+ : undefined
2801
+
2802
+ // P9 (compaction) shadow observation, on the MEASURED carrier only.
2803
+ // The 2.2.5 compaction payload carries a TOP-LEVEL `sessionID` and
2804
+ // no nested `session` object at all (PROBE-A, 11/11 runs), so the
2805
+ // event is handed to the adapter as-is and it reads
2806
+ // `payload.sessionID` — never `session.id`, which is absent there.
2807
+ // A payload that carries only a nested id therefore produces NO
2808
+ // decision (fail-closed) rather than being keyed by a carrier the
2809
+ // host was never observed to send. This runs BEFORE the pruner and
2810
+ // the context injection below, so `systemPartCount` describes the
2811
+ // host payload and not the blocks Pantheon appends; the adapter
2812
+ // clones what it reads and pushes nothing itself, so the injected
2813
+ // context is unchanged — shadow is the record, nothing else.
2814
+ // Child-session compaction is measured and needs no separate path:
2815
+ // PROBE-G §3.1 fired this hook on a real child 3/3 with the CHILD
2816
+ // sessionID at top level and the same payload shape (7 keys, no
2817
+ // nested `session`, `system` array of 4). Compaction with
2818
+ // `reason:"overflow"` was NOT inducible in 6 error shapes (PROBE-G
2819
+ // §3.2 — the host retried and completed, and the one
2820
+ // failure-recovery compaction was persisted as `reason:"auto"`), so
2821
+ // that path remains unmeasured and is not designed for here.
2822
+ try {
2823
+ evaluateCompactionMemoryPoint({ payload }, (record) => {
2824
+ p9Sink.emit({ ...record, mode: 'shadow' })
2825
+ })
2826
+ } catch {
2827
+ // Observation must never reach the compaction request.
2828
+ }
2829
+ const prunerConfig = resolveContextPrunerConfig(context.options)
2830
+ loadRuntimeOverrides()
2831
+ if (gateDisabled('gate-context-pruner')) {
2832
+ logPruneFailureOnce(
2833
+ sessionID,
2834
+ 'compaction',
2835
+ new Error('gate-context-pruner override'),
2836
+ )
2837
+ } else {
2838
+ const stats = pruneMessages(payload?.messages, prunerConfig, 'compaction')
2839
+ logContextPrune(stats, sessionID)
2840
+ logPruneShapeIssue(stats, sessionID, 'compaction')
2841
+ }
2842
+
2843
+ // Compaction context (V1 `experimental.session.compacting`
2844
+ // parity, #266). The SAME builder V1 uses — directive +
2845
+ // `<mission_context>` — pushed into the payload's `system` array,
2846
+ // which is the only text sink the V2 compaction hook exposes
2847
+ // (`context` is the session-hook name in V1, not a field here).
2848
+ //
2849
+ // The `<todo_context>` section is present only when setup built a real
2850
+ // enforcer (host session domain exposes the todo listing), and `<tool_ceiling>` has no V2 producer at all — both
2851
+ // reductions are declared in the capability seed instead of
2852
+ // silently missing.
2853
+ const blocks = await buildCompactionContext({
2854
+ ...(sessionID === undefined ? {} : { sessionID }),
2855
+ goals: {
2856
+ // Same gate V1 uses: the goal loop is disabled in this build,
2857
+ // so `<mission_context>` is omitted on both surfaces.
2858
+ enabled: GOAL_LOOP_DEFAULTS.enabled,
2859
+ list: (id: string) => goalStore.list(id),
2860
+ },
2861
+ ...(idleEnforcer === undefined
2862
+ ? {}
2863
+ : {
2864
+ todos: {
2865
+ // V1's own source: `TodoEnforcer.listPendingTodos`.
2866
+ enabled: todoEnforcerEnabledFromEnv(),
2867
+ list: (id: string) => idleEnforcer.listPendingTodos(id),
2868
+ },
2869
+ }),
2870
+ })
2871
+ if (blocks.length > 0 && !appendSystemBlocks(payload, blocks)) {
2872
+ // The payload carried no usable `system`. Diagnostic once per
2873
+ // process: a silent miss here would look like "no goals".
2874
+ if (!compactionChannelWarned) {
2875
+ compactionChannelWarned = true
2876
+ appendV2HookLog(
2877
+ '[compaction-context] payload.system is not a string or array; ' +
2878
+ 'compaction context could not be injected',
2879
+ )
2880
+ }
2881
+ }
2882
+ } catch (error) {
2883
+ // Fail-open: any unexpected shape or engine failure must not kill
2884
+ // the compaction request. One diagnostic line per session maximum.
2885
+ logPruneFailureOnce(
2886
+ (event as { sessionID?: unknown } | null)?.sessionID,
2887
+ 'compaction',
2888
+ error,
2889
+ )
2890
+ }
2891
+ })
2892
+ } catch {
2893
+ markUnsupported('compaction-hook')
2894
+ }
2895
+ } else {
2896
+ markUnsupported('compaction-hook')
2897
+ }
2898
+ },
2899
+ })
2900
+
2901
+ // ─── Cleanup and dispose ─────────────────────────────────────────────
2902
+
2903
+ /**
2904
+ * Cleanup — call from the host dispose lifecycle, tests, or the process
2905
+ * exit handler to tear down V2 event subscriptions.
2906
+ */
2907
+ export function v2Dispose(): void {
2908
+ for (const cleanup of activeCleanups) {
2909
+ try {
2910
+ cleanup()
2911
+ } catch {
2912
+ // Best-effort cleanup
2913
+ }
2914
+ }
2915
+ activeCleanups.length = 0
2916
+ }
2917
+
2918
+ /**
2919
+ * The current list of unsupported V2 features.
2920
+ *
2921
+ * Read by the installer and by `doctor` (both via the shared seed in
2922
+ * `src/pantheon/unsupported.mjs`) so the markers a user is shown are the
2923
+ * same ones this returns, rather than a hand-copied duplicate.
2924
+ *
2925
+ * This returns the LIVE array: the shared seed plus whatever `markUnsupported`
2926
+ * appended while this process talked to a real host.
2927
+ */
2928
+ export function getUnsupportedFeatures(): readonly string[] {
2929
+ return V2_UNSUPPORTED_FEATURES
555
2930
  }
556
2931
 
557
2932
  export default plugin