pantheon-opencode 1.7.0 → 2.0.0-beta.2

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