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