pantheon-opencode 1.6.0-beta.9 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.global.md +118 -0
- package/AGENTS.md +18 -168
- package/CHANGELOG.md +144 -365
- package/README.md +124 -607
- package/README.pt-BR.md +120 -345
- package/bin/pantheon-init.mjs +504 -141
- package/commands/pantheon-deepwork.md +14 -3
- package/commands/pantheon-vision.md +61 -12
- package/package.json +22 -13
- package/plugin.json +1 -1
- package/pyproject.toml +6 -2
- package/scripts/_pantheon_paths.py +24 -0
- package/scripts/build-agents-md.mjs +368 -69
- package/scripts/changelog-merge.mjs +161 -0
- package/scripts/check-plugin-v2-coverage.mjs +11 -8
- package/scripts/docs-check-changelog.mjs +204 -0
- package/scripts/docs-link-check.mjs +314 -0
- package/scripts/docs-media.mjs +157 -0
- package/scripts/doctor.mjs +850 -45
- package/scripts/install/agents-md.mjs +2 -2
- package/scripts/install/backup.mjs +648 -0
- package/scripts/install/cli-ui.mjs +303 -72
- package/scripts/install/component-selection.mjs +61 -0
- package/scripts/install/config-migration.mjs +583 -27
- package/scripts/install/exit-codes.mjs +26 -0
- package/scripts/install/file-inventory.mjs +555 -0
- package/scripts/install/health-check.mjs +31 -25
- package/scripts/install/interactive.mjs +99 -383
- package/scripts/install/interrupt.mjs +78 -0
- package/scripts/install/migrate.mjs +49 -25
- package/scripts/install/model-picker.mjs +218 -250
- package/scripts/install/opencode-state.mjs +91 -0
- package/scripts/install/opencode-version.mjs +83 -21
- package/scripts/install/opencode.mjs +1675 -187
- package/scripts/install/plan-artifact.mjs +517 -0
- package/scripts/install/plan.mjs +475 -0
- package/scripts/install/plugin.mjs +214 -27
- package/scripts/install/prompt-result.mjs +2 -0
- package/scripts/install/run-record.mjs +115 -0
- package/scripts/install/shared.mjs +256 -99
- package/scripts/install/state.mjs +63 -8
- package/scripts/install/strings.mjs +93 -8
- package/scripts/install/v2-capabilities.mjs +205 -0
- package/scripts/install/venv.mjs +90 -47
- package/scripts/install/verify.mjs +128 -0
- package/scripts/install/vision-prompt.mjs +173 -0
- package/scripts/install-mcp.mjs +2 -2
- package/scripts/manifest-inventory.mjs +49 -3
- package/scripts/mcp_persistence.py +1535 -1050
- package/scripts/memory_mcp.py +12 -843
- package/scripts/node-engine-policy.mjs +85 -0
- package/scripts/package-evidence.mjs +10 -2
- package/scripts/postinstall.mjs +26 -26
- package/scripts/probe-pantheon-cost.mjs +118 -19
- package/scripts/prune.mjs +9 -3
- package/scripts/reconcile.mjs +325 -0
- package/scripts/release-gates.mjs +687 -0
- package/scripts/restore.mjs +222 -0
- package/scripts/run-node-tests.mjs +24 -8
- package/scripts/sync-artifacts.mjs +19 -7
- package/scripts/sync-tui.mjs +5 -1
- package/scripts/test-opencode-v2-sandbox.sh +36 -123
- package/scripts/uninstall.mjs +369 -34
- package/scripts/update.mjs +164 -0
- package/scripts/validate-node-engine-policy.mjs +13 -0
- package/scripts/version-check.mjs +34 -1
- package/scripts/versioning.mjs +23 -3
- package/scripts/vision-status.mjs +682 -0
- package/skills-lock.json +8 -8
- package/src/agents/aphrodite.md +13 -10
- package/src/agents/apollo.md +4 -5
- package/src/agents/athena.md +74 -46
- package/src/agents/demeter.md +10 -7
- package/src/agents/gaia.md +0 -1
- package/src/agents/hephaestus.md +4 -3
- package/src/agents/hermes.md +10 -9
- package/src/agents/iris.md +6 -1
- package/src/agents/mnemosyne.md +10 -4
- package/src/agents/nyx.md +4 -4
- package/src/agents/prometheus.md +12 -11
- package/src/agents/talos.md +6 -0
- package/src/agents/zeus.md +84 -56
- package/src/instructions/agent-return-format.instructions.md +12 -41
- package/src/instructions/memory-protocol.instructions.md +5 -11
- package/src/instructions/test-economy.instructions.md +12 -0
- package/src/instructions/yagni.instructions.md +6 -15
- package/src/instructions/zeus-anti-stall.instructions.md +6 -6
- package/src/instructions/zeus-communication-rules.instructions.md +6 -6
- package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
- package/src/instructions/zeus-memory-operations.instructions.md +13 -7
- package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
- package/src/mcp/_pantheon_paths.py +24 -0
- package/src/mcp/mcp_codemap_module.py +86 -18
- package/src/mcp/mcp_persistence.py +1535 -1050
- package/src/mcp/memory_mcp.py +444 -94
- package/src/mcp/pantheon_vision.py +285 -41
- package/src/mcp/requirements-mcp.txt +6 -1
- package/src/mcp/requirements-vision.txt +1 -1
- package/src/pantheon/context-pruner.ts +541 -0
- package/src/pantheon/cost-command.ts +901 -60
- package/src/pantheon/delegation-enforce.ts +160 -23
- package/src/pantheon/goal-loop.ts +11 -8
- package/src/pantheon/guard-path.ts +162 -0
- package/src/pantheon/memory-context.ts +1017 -0
- package/src/pantheon/model-agents.ts +19 -0
- package/src/pantheon/model-command.ts +218 -56
- package/src/pantheon/model-pricing.ts +536 -0
- package/src/pantheon/presets.mjs +2 -0
- package/src/pantheon/task-result-guard.ts +50 -14
- package/src/pantheon/v2-bounded-read.ts +654 -0
- package/src/pantheon/v2-bridge.ts +27 -0
- package/src/pantheon/v2-delegation-enforce.ts +133 -6
- package/src/pantheon/v2-execute-after.ts +135 -24
- package/src/pantheon/v2-model-overrides.ts +275 -0
- package/src/pantheon/v2-shell-hooks.ts +260 -0
- package/src/pantheon/v2-tools.ts +89 -35
- package/src/pantheon/v2-unsupported.mjs +34 -7
- package/src/pantheon/v2-vision.ts +622 -0
- package/src/pantheon/vision-local.ts +531 -0
- package/src/pantheon/vision.ts +1166 -116
- package/src/plugin-v2.ts +1039 -171
- package/src/plugin.ts +37 -13
- package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +3742 -85
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +15 -15
- package/src/plugins/tui/package.json +7 -5
- package/src/plugins/tui/src/index-v2.tsx +4314 -50
- package/src/plugins/tui/tsconfig.typecheck.json +5 -0
- package/src/routing.yml +50 -5
- package/src/skills/agent-coordination/SKILL.md +7 -2
- package/src/skills/artifact-management/SKILL.md +5 -1
- package/src/skills/auto-continue/SKILL.md +14 -6
- package/src/skills/codemap/SKILL.md +1 -1
- package/src/skills/memory-bank/SKILL.md +21 -13
- package/src/skills/session-goal/SKILL.md +12 -22
- package/src/skills/spec-driven-development/SKILL.md +3 -1
- package/src/skills/worktrees/SKILL.md +30 -11
- package/scripts/probe-context-rehydrate.mjs +0 -263
package/src/plugin-v2.ts
CHANGED
|
@@ -2,9 +2,13 @@
|
|
|
2
2
|
* Pantheon V2 Plugin — full orchestration plugin for OpenCode V2.
|
|
3
3
|
*
|
|
4
4
|
* Registers:
|
|
5
|
-
* - 3 self-sufficient tools via V2 tool.transform (hashline_edit,
|
|
6
|
-
* pantheon_cost, pantheon_model
|
|
7
|
-
*
|
|
5
|
+
* - 3 unconditional self-sufficient tools via V2 tool.transform (hashline_edit,
|
|
6
|
+
* pantheon_cost, pantheon_model) 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
|
+
* The goal tools need V1 infrastructure and are absent from this surface.
|
|
8
12
|
* - 5 event subscriptions (session.created, idle, deleted, error, compacted)
|
|
9
13
|
* - Session hooks (prompt, context, compaction)
|
|
10
14
|
* - A tool `execute.before` hook that ENFORCES read-only sessions: the agent
|
|
@@ -26,16 +30,18 @@
|
|
|
26
30
|
* `execute` MUST resolve to a value carrying `output`. The host enforces the
|
|
27
31
|
* two as a pair — see `V2ToolDraft` for the exact contract.
|
|
28
32
|
*
|
|
29
|
-
* ## The
|
|
33
|
+
* ## The host domains the SDK types do not carry
|
|
30
34
|
*
|
|
31
35
|
* `@opencode-ai/plugin` 1.18.33 types `PluginContext` as exactly:
|
|
32
36
|
* options · agent · aisdk · catalog · command · integration · plugin ·
|
|
33
37
|
* reference · skill
|
|
34
|
-
* — no `tool`, `event`, `permission` or `session`.
|
|
35
|
-
*
|
|
36
|
-
*
|
|
38
|
+
* — no `tool`, `event`, `permission` or `session`. The pin does not carry
|
|
39
|
+
* them, and the `latest` release (`1.19.4`, 2026-10-22) restructures the
|
|
40
|
+
* package instead of typing them, so following the newest SDK release does
|
|
41
|
+
* not resolve this: it is a STRUCTURAL DECLARATION task, not a pin
|
|
42
|
+
* reconciliation.
|
|
37
43
|
*
|
|
38
|
-
* A live opencode 2.0.22 host DOES have
|
|
44
|
+
* A live opencode 2.0.22+ host DOES have these domains, with the shapes this module
|
|
39
45
|
* uses. Measured by `tests/canary/plugin-v2-tool-canary.test.mjs`, which loads
|
|
40
46
|
* this file through the real loader and records `Object.keys(ctx)` from inside
|
|
41
47
|
* the host:
|
|
@@ -62,7 +68,7 @@
|
|
|
62
68
|
* for the others. The cast is not a licence to assume: the canary above is what
|
|
63
69
|
* proves the domains exist on a real host, and it fails if they stop existing.
|
|
64
70
|
*
|
|
65
|
-
* If the SDK ever exposes these
|
|
71
|
+
* If the SDK ever exposes these host domains, replacing `hostDomains` with the real
|
|
66
72
|
* type is a one-line change. Do NOT make that change while 1.18.x lacks them.
|
|
67
73
|
*
|
|
68
74
|
* V2_UNSUPPORTED_FEATURES distinguishes adapter limitations from observed
|
|
@@ -72,6 +78,7 @@
|
|
|
72
78
|
*/
|
|
73
79
|
|
|
74
80
|
import { appendFileSync, mkdirSync } from 'node:fs'
|
|
81
|
+
import { realpath as realpathAsync } from 'node:fs/promises'
|
|
75
82
|
import path from 'node:path'
|
|
76
83
|
import { fileURLToPath } from 'node:url'
|
|
77
84
|
import type {
|
|
@@ -81,16 +88,54 @@ import type {
|
|
|
81
88
|
ReferenceDraft,
|
|
82
89
|
} from '@opencode-ai/plugin/v2/promise'
|
|
83
90
|
import { define } from '@opencode-ai/plugin/v2/promise'
|
|
91
|
+
import { buildCompactionContext } from './pantheon/compaction-context.ts'
|
|
92
|
+
import {
|
|
93
|
+
CONTEXT_PRUNER_CONFIG_KEYS,
|
|
94
|
+
describeContextPrunerConfigIssues,
|
|
95
|
+
type PruneSite,
|
|
96
|
+
type PruneStats,
|
|
97
|
+
pruneMessages,
|
|
98
|
+
resolveContextPrunerConfig,
|
|
99
|
+
} from './pantheon/context-pruner.ts'
|
|
84
100
|
import {
|
|
85
101
|
createEnforcementGuard,
|
|
102
|
+
normalizeDelegationAgent,
|
|
86
103
|
readOnlyRegistry,
|
|
87
104
|
syncReadOnlySession,
|
|
88
105
|
type ToolExecuteBeforeInput,
|
|
89
106
|
type ToolExecuteBeforeOutput,
|
|
107
|
+
zeusReadGuard,
|
|
90
108
|
} from './pantheon/delegation-enforce.ts'
|
|
109
|
+
import { GOAL_LOOP_DEFAULTS, GoalStore } from './pantheon/goal-loop.ts'
|
|
110
|
+
import { createGuardPathResolver } from './pantheon/guard-path.ts'
|
|
111
|
+
import {
|
|
112
|
+
applyMemoryInjection,
|
|
113
|
+
MemoryInjectionCache,
|
|
114
|
+
resolveMemoryInjectionConfig,
|
|
115
|
+
warnInvalidMemoryInjectionConfig,
|
|
116
|
+
} from './pantheon/memory-context.ts'
|
|
117
|
+
import { getSharedBoard } from './pantheon/shared-board.ts'
|
|
118
|
+
import {
|
|
119
|
+
TODO_ENFORCER_DEFAULTS,
|
|
120
|
+
TodoEnforcer,
|
|
121
|
+
type TodoEnforcerChild,
|
|
122
|
+
type TodoEnforcerClient,
|
|
123
|
+
type TodoEnforcerMessage,
|
|
124
|
+
type TodoLike,
|
|
125
|
+
todoEnforcerEnabledFromEnv,
|
|
126
|
+
} from './pantheon/todo-enforcer.ts'
|
|
91
127
|
import {
|
|
128
|
+
BOUNDED_READ_TOOL,
|
|
129
|
+
createV2BoundedReadTool,
|
|
130
|
+
type V2BoundedReadOriginRegistry,
|
|
131
|
+
} from './pantheon/v2-bounded-read.ts'
|
|
132
|
+
import {
|
|
133
|
+
createV2Bridge,
|
|
134
|
+
getRegisteredV2Bridge,
|
|
92
135
|
getV2BridgeFromContext,
|
|
136
|
+
injectBridge,
|
|
93
137
|
type PantheonV2Bridge,
|
|
138
|
+
registerV2Bridge,
|
|
94
139
|
type V2ContextLike,
|
|
95
140
|
} from './pantheon/v2-bridge.ts'
|
|
96
141
|
import {
|
|
@@ -98,11 +143,16 @@ import {
|
|
|
98
143
|
evaluateV2Delegation,
|
|
99
144
|
PANTHEON_AGENTS,
|
|
100
145
|
type V2PermissionEvent,
|
|
146
|
+
V2SubagentOriginRegistry,
|
|
101
147
|
v2ResourceTarget,
|
|
102
148
|
} from './pantheon/v2-delegation-enforce.ts'
|
|
103
149
|
import { createV2ExecuteAfter, resolveV2SandboxConfig } from './pantheon/v2-execute-after.ts'
|
|
150
|
+
import { applyV2ModelOverrides, readV2ModelConfiguration } from './pantheon/v2-model-overrides.ts'
|
|
151
|
+
import { createV2ShellHooks, type V2ShellRunner } from './pantheon/v2-shell-hooks.ts'
|
|
104
152
|
import { createV2ToolDefinitions, type V2ToolResult } from './pantheon/v2-tools.ts'
|
|
105
153
|
import { V2_UNSUPPORTED_FEATURE_SEED } from './pantheon/v2-unsupported.mjs'
|
|
154
|
+
import { buildV2VisionPromptContext, type V2VisionRuntime } from './pantheon/v2-vision.ts'
|
|
155
|
+
import { sanitizeVisionHistory } from './pantheon/vision.ts'
|
|
106
156
|
import { type HookPayload, type HookResult, runHook } from './plugins/hook-runner.ts'
|
|
107
157
|
|
|
108
158
|
// ─── Unsupported Features Registry ───────────────────────────────────────
|
|
@@ -197,6 +247,35 @@ function normalizeSystemToParts(system: unknown): unknown[] | null {
|
|
|
197
247
|
return system
|
|
198
248
|
}
|
|
199
249
|
|
|
250
|
+
/** Set once, so a payload without a `system` channel warns once per process. */
|
|
251
|
+
let compactionChannelWarned = false
|
|
252
|
+
|
|
253
|
+
/** Set once, so a failed bridge construction logs one line per process. */
|
|
254
|
+
let bridgeFailureLogged = false
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Append text blocks to a hook payload's `system` channel.
|
|
258
|
+
*
|
|
259
|
+
* Returns `false` when the payload carries no usable channel (absent, or a
|
|
260
|
+
* shape that is neither string nor array) — the caller decides whether that is
|
|
261
|
+
* worth a diagnostic. A bare-string `system` is replaced by its part array on
|
|
262
|
+
* the payload itself, because the host reads the property, not our copy.
|
|
263
|
+
*
|
|
264
|
+
* Used by the V2 compaction hook (#266) to inject the compaction context
|
|
265
|
+
* blocks V1 pushes into `output.context`.
|
|
266
|
+
*/
|
|
267
|
+
function appendSystemBlocks(
|
|
268
|
+
target: { system?: unknown } | null | undefined,
|
|
269
|
+
blocks: readonly string[],
|
|
270
|
+
): boolean {
|
|
271
|
+
if (target == null || blocks.length === 0) return false
|
|
272
|
+
const normalized = normalizeSystemToParts(target.system)
|
|
273
|
+
if (normalized == null) return false
|
|
274
|
+
if (typeof target.system === 'string') target.system = normalized
|
|
275
|
+
for (const block of blocks) normalized.push({ type: 'text', text: block } satisfies SystemPart)
|
|
276
|
+
return true
|
|
277
|
+
}
|
|
278
|
+
|
|
200
279
|
/**
|
|
201
280
|
* Add a feature to the unsupported list (idempotent).
|
|
202
281
|
*/
|
|
@@ -233,6 +312,7 @@ interface V2EventDomain {
|
|
|
233
312
|
* domain and the host may evolve independently.
|
|
234
313
|
*/
|
|
235
314
|
interface V2PermissionDomain {
|
|
315
|
+
assert?: (input: Record<string, unknown>) => Promise<unknown>
|
|
236
316
|
hook?: (
|
|
237
317
|
name: string,
|
|
238
318
|
handler: (event: unknown, output?: unknown) => void | Promise<void>,
|
|
@@ -250,12 +330,28 @@ interface V2SessionDomain {
|
|
|
250
330
|
get?: (input: { sessionID: string }) => Promise<unknown>
|
|
251
331
|
}
|
|
252
332
|
|
|
253
|
-
|
|
333
|
+
interface V2LocationDomain {
|
|
334
|
+
directory?: string
|
|
335
|
+
project?: { id?: string }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
interface V2ModelDomain {
|
|
339
|
+
list?: V2VisionRuntime['model']['list']
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
interface V2GenerateDomain {
|
|
343
|
+
text?: (input: { model: { providerID: string; id: string }; prompt: string }) => Promise<unknown>
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** `PluginContext` plus the host domains 1.18.x omits. See the module header. */
|
|
254
347
|
interface HostPluginContext extends PluginContext {
|
|
255
348
|
tool?: V2ToolDomain
|
|
256
349
|
event?: V2EventDomain
|
|
257
350
|
permission?: V2PermissionDomain
|
|
258
351
|
session?: V2SessionDomain
|
|
352
|
+
model?: V2ModelDomain
|
|
353
|
+
generate?: V2GenerateDomain
|
|
354
|
+
location?: V2LocationDomain
|
|
259
355
|
}
|
|
260
356
|
|
|
261
357
|
/**
|
|
@@ -287,18 +383,140 @@ let v1Bridge: PantheonV2Bridge | null = null
|
|
|
287
383
|
*/
|
|
288
384
|
export function setV2Bridge(bridge: PantheonV2Bridge): void {
|
|
289
385
|
v1Bridge = bridge
|
|
386
|
+
// Also publish process-wide so a V1 load that registers FIRST and a V2 load
|
|
387
|
+
// that resolves SECOND converge on one bridge (see v2-bridge.ts).
|
|
388
|
+
registerV2Bridge(bridge)
|
|
290
389
|
}
|
|
291
390
|
|
|
292
391
|
/**
|
|
293
|
-
* Get the V1 bridge, checking module-level first, then
|
|
392
|
+
* Get the V1 bridge, checking module-level first, then the process-wide
|
|
393
|
+
* registration, then ctx.options.
|
|
294
394
|
* Returns null when no bridge is available (V2 standalone mode).
|
|
295
395
|
*/
|
|
296
396
|
function resolveBridge(ctx?: V2ContextLike): PantheonV2Bridge | null {
|
|
297
397
|
if (v1Bridge != null) return v1Bridge
|
|
398
|
+
const registered = getRegisteredV2Bridge()
|
|
399
|
+
if (registered != null) {
|
|
400
|
+
v1Bridge = registered
|
|
401
|
+
return registered
|
|
402
|
+
}
|
|
298
403
|
if (ctx != null) return getV2BridgeFromContext(ctx)
|
|
299
404
|
return null
|
|
300
405
|
}
|
|
301
406
|
|
|
407
|
+
/**
|
|
408
|
+
* The subset of the host's `session` domain a `TodoEnforcerClient` needs.
|
|
409
|
+
*
|
|
410
|
+
* Declared structurally and checked at runtime instead of being added to
|
|
411
|
+
* {@link V2SessionDomain} on faith: the measured 2.1.4 host exposes
|
|
412
|
+
* `hook`/`get`/`list`/`create`/`remove`/`prompt`/`generate`/`interrupt` on that
|
|
413
|
+
* domain. Its `prompt` takes `{ sessionID, text }` and is a DIFFERENT call from
|
|
414
|
+
* V1's `promptAsync({ path, body: { agent?, model?, parts } })` — the enforcer's
|
|
415
|
+
* agent/model inheritance has no V2 counterpart — and whether it exposes
|
|
416
|
+
* `todo`/`messages`/`children` at all is not measured by the repository. The
|
|
417
|
+
* check below therefore requires the V1 shape exactly: a client built on a
|
|
418
|
+
* method that is absent (or on a same-named method with a different contract)
|
|
419
|
+
* would throw inside the enforcer's fail-open guards and leave idle
|
|
420
|
+
* continuation silently dead again — the exact defect this wiring closes.
|
|
421
|
+
*/
|
|
422
|
+
interface V2TodoSessionMethods {
|
|
423
|
+
todo?: (input: { path: { id: string } }) => Promise<unknown>
|
|
424
|
+
messages?: (input: { path: { id: string } }) => Promise<unknown>
|
|
425
|
+
children?: (input: { path: { id: string } }) => Promise<unknown>
|
|
426
|
+
promptAsync?: (input: { path: { id: string }; body: Record<string, unknown> }) => Promise<unknown>
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const V2_TODO_CLIENT_METHODS = ['todo', 'messages', 'children', 'promptAsync'] as const
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Adapt the host's `session` domain to the {@link TodoEnforcerClient} the V1
|
|
433
|
+
* enforcer instance expects, or `undefined` when the domain does not carry the
|
|
434
|
+
* four methods. The input shape is V1's (`{ path: { id } }`) because the
|
|
435
|
+
* enforcer is the V1 instance — this is an adapter, not a second enforcer.
|
|
436
|
+
*/
|
|
437
|
+
function createV2TodoEnforcerClient(
|
|
438
|
+
session: V2SessionDomain | undefined,
|
|
439
|
+
): TodoEnforcerClient | undefined {
|
|
440
|
+
if (session === undefined) return undefined
|
|
441
|
+
const methods = session as V2TodoSessionMethods
|
|
442
|
+
for (const method of V2_TODO_CLIENT_METHODS) {
|
|
443
|
+
if (typeof methods[method] !== 'function') return undefined
|
|
444
|
+
}
|
|
445
|
+
// Every method is present: the guard above is the only place absence is
|
|
446
|
+
// tolerated, so the assertions below cannot fire at runtime.
|
|
447
|
+
const todo = methods.todo as NonNullable<V2TodoSessionMethods['todo']>
|
|
448
|
+
const messages = methods.messages as NonNullable<V2TodoSessionMethods['messages']>
|
|
449
|
+
const children = methods.children as NonNullable<V2TodoSessionMethods['children']>
|
|
450
|
+
const promptAsync = methods.promptAsync as NonNullable<V2TodoSessionMethods['promptAsync']>
|
|
451
|
+
return {
|
|
452
|
+
session: {
|
|
453
|
+
todo: (input) => todo.call(session, input) as Promise<TodoLike[]>,
|
|
454
|
+
messages: (input) => messages.call(session, input) as Promise<TodoEnforcerMessage[]>,
|
|
455
|
+
children: (input) => children.call(session, input) as Promise<TodoEnforcerChild[]>,
|
|
456
|
+
promptAsync: (input) => promptAsync.call(session, input),
|
|
457
|
+
},
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Construct the V1→V2 bridge IN the V2 entry and publish it on both channels
|
|
463
|
+
* (issue #265).
|
|
464
|
+
*
|
|
465
|
+
* Before this, `setV2Bridge`/`injectBridge`/`createV2Bridge` had no production
|
|
466
|
+
* caller: `resolveBridge()` always returned null, so `onSessionIdle` reached a
|
|
467
|
+
* null enforcer and idle continuation never ran on any V2 install — including
|
|
468
|
+
* the V1+V2 co-load, because nothing had ever put a bridge in `ctx.options`
|
|
469
|
+
* either.
|
|
470
|
+
*
|
|
471
|
+
* What is genuinely constructible without a V1 `PluginInput`:
|
|
472
|
+
*
|
|
473
|
+
* - `board` — a process-wide singleton (`getSharedBoard`), the same instance
|
|
474
|
+
* V1 and the hooks plugin use.
|
|
475
|
+
* - `todoEnforcer` — the V1 class, fed by an adapter over the host's session
|
|
476
|
+
* domain. Present only when that domain exposes the four methods the
|
|
477
|
+
* enforcer uses; otherwise the reduction is marked (`idle-todo-enforcer`)
|
|
478
|
+
* and, because the marker is one a migrating user must be told about, it
|
|
479
|
+
* is also part of the static seed.
|
|
480
|
+
*
|
|
481
|
+
* Files in the bridge that need a V1 `client` (goal loop, vision handler) stay
|
|
482
|
+
* out: `goal-tools` already declares the goal surface absent, and the vision
|
|
483
|
+
* handler is V1-only.
|
|
484
|
+
*/
|
|
485
|
+
function installV2Bridge(context: PluginContext): TodoEnforcer | undefined {
|
|
486
|
+
// Co-load guard (#265 review): a bridge with an enforcer may already exist —
|
|
487
|
+
// registered by V1 in this process, or by an earlier V2 setup. Building a
|
|
488
|
+
// second enforcer would answer the same `session.idle` twice (V1's dispatcher
|
|
489
|
+
// and this plugin each inject a continuation prompt). Reuse, never overwrite.
|
|
490
|
+
const existing = resolveBridge(context)
|
|
491
|
+
if (existing?.todoEnforcer !== undefined) {
|
|
492
|
+
injectBridge(context, existing)
|
|
493
|
+
return existing.todoEnforcer
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const todoClient = createV2TodoEnforcerClient(hostDomains(context).session)
|
|
497
|
+
if (todoClient === undefined) markUnsupported('idle-todo-enforcer')
|
|
498
|
+
const board = getSharedBoard()
|
|
499
|
+
const todoEnforcer =
|
|
500
|
+
todoClient === undefined
|
|
501
|
+
? undefined
|
|
502
|
+
: new TodoEnforcer({
|
|
503
|
+
client: todoClient,
|
|
504
|
+
board,
|
|
505
|
+
options: { ...TODO_ENFORCER_DEFAULTS, enabled: todoEnforcerEnabledFromEnv() },
|
|
506
|
+
})
|
|
507
|
+
const bridge = createV2Bridge({ board, ...(todoEnforcer === undefined ? {} : { todoEnforcer }) })
|
|
508
|
+
// Two channels, both needed: `ctx.options` is what a handler holding the
|
|
509
|
+
// context reads (`resolveBridge(ctx)`), and the module-level reference is
|
|
510
|
+
// what the event handlers use, since they receive no context.
|
|
511
|
+
injectBridge(context, bridge)
|
|
512
|
+
setV2Bridge(bridge)
|
|
513
|
+
// Returned so the compaction hook can list the session's PENDING TODOS with
|
|
514
|
+
// the same instance — the `<todo_context>` half of V1's compaction blocks
|
|
515
|
+
// needs exactly `listPendingTodos`, and the host exposes no todo listing of
|
|
516
|
+
// its own.
|
|
517
|
+
return todoEnforcer
|
|
518
|
+
}
|
|
519
|
+
|
|
302
520
|
// ─── V2 Transform Functions ─────────────────────────────────────────────
|
|
303
521
|
|
|
304
522
|
function transformAgents(draft: AgentDraft): void {
|
|
@@ -324,6 +542,18 @@ function transformAgents(draft: AgentDraft): void {
|
|
|
324
542
|
markUnsupported('agent-transform-list')
|
|
325
543
|
return
|
|
326
544
|
}
|
|
545
|
+
try {
|
|
546
|
+
const modelConfiguration = readV2ModelConfiguration()
|
|
547
|
+
if (modelConfiguration.warnings.length > 0) {
|
|
548
|
+
// The V2 server PluginContext has no documented user-visible notification
|
|
549
|
+
// or logging channel; preserve the degradation for status diagnostics.
|
|
550
|
+
markUnsupported('agent-model-overrides')
|
|
551
|
+
}
|
|
552
|
+
applyV2ModelOverrides(draft, modelConfiguration.overrides)
|
|
553
|
+
} catch {
|
|
554
|
+
// Model configuration is optional. Preserve host models if it cannot be read.
|
|
555
|
+
markUnsupported('agent-model-overrides')
|
|
556
|
+
}
|
|
327
557
|
try {
|
|
328
558
|
for (const agent of agents) {
|
|
329
559
|
draft.update(agent.id, (current) => {
|
|
@@ -415,8 +645,12 @@ function transformReferences(draft: ReferenceDraft): void {
|
|
|
415
645
|
*
|
|
416
646
|
* Returns true if tools were registered, false if the API is unavailable.
|
|
417
647
|
*/
|
|
418
|
-
async function registerV2Tools(
|
|
419
|
-
|
|
648
|
+
async function registerV2Tools(
|
|
649
|
+
context: PluginContext,
|
|
650
|
+
boundedRead?: ReturnType<typeof createV2BoundedReadTool>['definition'],
|
|
651
|
+
): Promise<boolean> {
|
|
652
|
+
const host = hostDomains(context)
|
|
653
|
+
const toolCtx = host.tool
|
|
420
654
|
|
|
421
655
|
if (!toolCtx?.transform) {
|
|
422
656
|
return false
|
|
@@ -426,7 +660,12 @@ async function registerV2Tools(context: PluginContext): Promise<boolean> {
|
|
|
426
660
|
// Tool definitions carry their own `output` declaration; the draft requires
|
|
427
661
|
// it, and the host rejects a definition whose result shape cannot satisfy
|
|
428
662
|
// the declaration it makes.
|
|
429
|
-
const
|
|
663
|
+
const model = host.model
|
|
664
|
+
const visionReady = typeof model?.list === 'function'
|
|
665
|
+
if (!visionReady) markUnsupported('vision-tool')
|
|
666
|
+
const visionRuntime = visionReady ? ({ model } as V2VisionRuntime) : undefined
|
|
667
|
+
const toolDefs = createV2ToolDefinitions(visionRuntime)
|
|
668
|
+
if (boundedRead !== undefined) toolDefs.push(boundedRead)
|
|
430
669
|
|
|
431
670
|
await toolCtx.transform((draft: V2ToolDraft) => {
|
|
432
671
|
// Catalog grouping only. The host computes a tool's registration id as
|
|
@@ -466,7 +705,10 @@ async function registerV2Tools(context: PluginContext): Promise<boolean> {
|
|
|
466
705
|
*
|
|
467
706
|
* Returns a cleanup function, or undefined if the API is unavailable.
|
|
468
707
|
*/
|
|
469
|
-
function subscribeV2Events(
|
|
708
|
+
function subscribeV2Events(
|
|
709
|
+
context: PluginContext,
|
|
710
|
+
onTurnEnd?: (sessionID: string) => void,
|
|
711
|
+
): (() => void) | undefined {
|
|
470
712
|
const eventCtx = hostDomains(context).event
|
|
471
713
|
|
|
472
714
|
if (!eventCtx?.subscribe) {
|
|
@@ -479,6 +721,19 @@ function subscribeV2Events(context: PluginContext): (() => void) | undefined {
|
|
|
479
721
|
// biome-ignore lint/style/noNonNullAssertion: subscribe guaranteed by guard above
|
|
480
722
|
for await (const event of eventCtx.subscribe!({ signal: controller.signal })) {
|
|
481
723
|
await handleV2SessionEvent(event)
|
|
724
|
+
if (event.type === 'session.idle' || event.type === 'session.deleted') {
|
|
725
|
+
const properties = event.properties ?? {}
|
|
726
|
+
const info = properties.info
|
|
727
|
+
const infoID =
|
|
728
|
+
info !== null && typeof info === 'object' ? (info as { id?: unknown }).id : undefined
|
|
729
|
+
const sessionID =
|
|
730
|
+
typeof properties.sessionID === 'string'
|
|
731
|
+
? properties.sessionID
|
|
732
|
+
: typeof infoID === 'string'
|
|
733
|
+
? infoID
|
|
734
|
+
: undefined
|
|
735
|
+
if (sessionID) onTurnEnd?.(sessionID)
|
|
736
|
+
}
|
|
482
737
|
}
|
|
483
738
|
} catch (err: unknown) {
|
|
484
739
|
if (err instanceof Error && err.name === 'AbortError') return
|
|
@@ -516,48 +771,39 @@ async function handleV2SessionEvent(event: V2SessionEvent): Promise<void> {
|
|
|
516
771
|
}
|
|
517
772
|
|
|
518
773
|
/**
|
|
519
|
-
*
|
|
520
|
-
*
|
|
521
|
-
*
|
|
522
|
-
*
|
|
523
|
-
*
|
|
524
|
-
* THE V2 EVENT CARRIES THE SAME METADATA, so this is an UNWIRED seed, not an
|
|
525
|
-
* impossible one. The V2 SDK types `session.created` as
|
|
526
|
-
* `{ sessionID: string; info: Session }`, and `Session` declares
|
|
527
|
-
* `parentID?: string` (`@opencode-ai/sdk` v2 `gen/types.gen.d.ts`) — a superset
|
|
528
|
-
* of the two fields V1 reads on this exact event. Seeding here would be a copy
|
|
529
|
-
* of V1's line. An earlier revision of this comment claimed the metadata was
|
|
530
|
-
* absent from the V2 event; the SDK types refute that, so do not restore it.
|
|
531
|
-
*
|
|
532
|
-
* WHAT IS NOT MEASURED, in either direction: whether a live 2.0.22 host
|
|
533
|
-
* populates `info.parentID` on this event. The tool canary records
|
|
534
|
-
* `Object.keys(ctx)` from inside the host, not event payloads, so host
|
|
535
|
-
* population is UNVERIFIED. What is proven is only that the type carries the
|
|
536
|
-
* field and that no code path here reads it.
|
|
537
|
-
*
|
|
538
|
-
* The real asymmetry is the OTHER of V1's two seed sources. Besides this event,
|
|
539
|
-
* V1 runs a fail-open startup seed from `client.session.list()`
|
|
540
|
-
* (`seedRootSessionsInBackground`, `src/plugin.ts`) to cover sessions that
|
|
541
|
-
* predate plugin load, because opencode does not replay `session.created` for
|
|
542
|
-
* them. V2's `PluginContext` exposes no `client` at all — `options`, `agent`,
|
|
543
|
-
* `aisdk`, `catalog`, `command`, `integration`, `plugin`, `reference`, `skill`,
|
|
544
|
-
* and nothing else — so that enumeration has NO V2 EQUIVALENT. Wiring this
|
|
545
|
-
* handler would recover live sessions only, never resumed ones.
|
|
546
|
-
*
|
|
547
|
-
* And — more to the point — V1 is a separate plugin instance that is not loaded
|
|
548
|
-
* when only `plugin-v2` is configured, so on a V2-only install nothing seeds
|
|
549
|
-
* the hierarchy at all. Do not read the bridge check below as coverage: a
|
|
550
|
-
* non-null bridge means a host process that ALSO loaded V1, and V1 does the
|
|
551
|
-
* seeding itself.
|
|
552
|
-
*
|
|
553
|
-
* The unwired hierarchy seed is ONE of the two reasons the V2 enforcement guard
|
|
554
|
-
* is built without `isRootSession` / `isChildSession`; the other — and the one
|
|
555
|
-
* that would actually deny every `task()` call — is the absent
|
|
556
|
-
* `getSessionAgent`. See the `v2EnforcementGuard` comment below for both, and
|
|
557
|
-
* `docs/UPGRADING.md`, "Known limitation — V2 enforcement covers the
|
|
558
|
-
* blocked-tool list, not the V1 delegation matrix".
|
|
774
|
+
* Record the v2.0.29 lifecycle event in the opt-in F4A canary. Runtime events
|
|
775
|
+
* use a `{ id, created, type, data }` envelope; the child data carries
|
|
776
|
+
* `sessionID`, `parentID` and `agent`. Admission itself does not depend on this
|
|
777
|
+
* subscription: it checks the current permission source and `ctx.session.get`
|
|
778
|
+
* synchronously, so resumed roots and children use the same path.
|
|
559
779
|
*/
|
|
560
|
-
async function onSessionCreated(
|
|
780
|
+
async function onSessionCreated(event: V2SessionEvent): Promise<void> {
|
|
781
|
+
const payload = event as V2SessionEvent & Record<string, unknown>
|
|
782
|
+
const properties = event.properties ?? {}
|
|
783
|
+
const data =
|
|
784
|
+
event.data !== null && typeof event.data === 'object'
|
|
785
|
+
? (event.data as Record<string, unknown>)
|
|
786
|
+
: {}
|
|
787
|
+
const info = properties.info ?? data.info
|
|
788
|
+
const sessionInfo =
|
|
789
|
+
info !== null && typeof info === 'object' ? (info as Record<string, unknown>) : {}
|
|
790
|
+
writeV2AdmissionProof('session.created', {
|
|
791
|
+
eventKeys: Object.keys(payload),
|
|
792
|
+
propertyKeys: Object.keys(properties),
|
|
793
|
+
dataKeys: Object.keys(data),
|
|
794
|
+
infoKeys: Object.keys(sessionInfo),
|
|
795
|
+
id:
|
|
796
|
+
sessionInfo.id ??
|
|
797
|
+
sessionInfo.sessionID ??
|
|
798
|
+
data.id ??
|
|
799
|
+
data.sessionID ??
|
|
800
|
+
properties.id ??
|
|
801
|
+
properties.sessionID ??
|
|
802
|
+
payload.sessionID ??
|
|
803
|
+
null,
|
|
804
|
+
parentID: sessionInfo.parentID ?? data.parentID ?? properties.parentID ?? null,
|
|
805
|
+
agent: sessionInfo.agent ?? data.agent ?? properties.agent ?? null,
|
|
806
|
+
})
|
|
561
807
|
const _bridge = resolveBridge()
|
|
562
808
|
if (_bridge?.board != null) {
|
|
563
809
|
// Bridge present ⇒ this process also loaded V1, whose own event hook owns
|
|
@@ -566,10 +812,27 @@ async function onSessionCreated(_event: V2SessionEvent): Promise<void> {
|
|
|
566
812
|
}
|
|
567
813
|
|
|
568
814
|
async function onSessionIdle(_event: V2SessionEvent): Promise<void> {
|
|
569
|
-
//
|
|
570
|
-
//
|
|
571
|
-
//
|
|
572
|
-
//
|
|
815
|
+
// Temp-image sweep on the V2-only path: DELIBERATELY DEFERRED.
|
|
816
|
+
//
|
|
817
|
+
// V1 unlinks a session's temp images on `session.idle`/`session.deleted`
|
|
818
|
+
// (`cleanupSessionTempImages`, grace-guarded and refcounted). V2 cannot reuse
|
|
819
|
+
// it: `saveDataUrlImageSync` (the V2 materialization path) receives no session
|
|
820
|
+
// id, so there is no per-session `path → createdAt` map to sweep, and the
|
|
821
|
+
// content-hash temp dir is refcounted ONLY on the V1 path. The one reusable
|
|
822
|
+
// piece, `enforceTempFileCap`, is already invoked off every V2 save
|
|
823
|
+
// (`saveDataUrlImageSync`), so disk usage is bounded without an idle pass —
|
|
824
|
+
// re-running it here would be redundant, and a GLOBAL age-based unlink fired
|
|
825
|
+
// by one session's idle could delete a file another live session still
|
|
826
|
+
// references. Delivery is also best-effort: with no `ctx.event.subscribe`
|
|
827
|
+
// the stream is unsupported (`markUnsupported('event-stream')`) and no idle
|
|
828
|
+
// ever arrives. Implementing this safely needs V2-side session threading
|
|
829
|
+
// first; until then it stays deferred rather than approximated.
|
|
830
|
+
//
|
|
831
|
+
// Idle continuation — goal loop / todo enforcer dispatch. The bridge is
|
|
832
|
+
// constructed by THIS module in `installV2Bridge` (Phase 0) and holds the
|
|
833
|
+
// V1 TodoEnforcer instance when the host's session domain exposes the
|
|
834
|
+
// methods the enforcer uses. Before issue #265 nothing injected a bridge on
|
|
835
|
+
// the V2 path, so this call was a guaranteed no-op on every install.
|
|
573
836
|
const sessionID = _event.properties?.sessionID as string | undefined
|
|
574
837
|
if (!sessionID) return
|
|
575
838
|
const bridge = resolveBridge()
|
|
@@ -632,6 +895,7 @@ async function onSessionDeleted(event: V2SessionEvent): Promise<void> {
|
|
|
632
895
|
return
|
|
633
896
|
}
|
|
634
897
|
readOnlyRegistry.unregister(sessionID)
|
|
898
|
+
memoryInjectionCache.delete(sessionID)
|
|
635
899
|
}
|
|
636
900
|
|
|
637
901
|
/**
|
|
@@ -654,22 +918,130 @@ async function onSessionCompacted(_event: V2SessionEvent): Promise<void> {}
|
|
|
654
918
|
|
|
655
919
|
// ─── V2 Session Hooks ───────────────────────────────────────────────────
|
|
656
920
|
|
|
921
|
+
/**
|
|
922
|
+
* One-line prune stats entry through the existing hooks.log channel only when
|
|
923
|
+
* a pass actually rewrote something. Silent no-ops (below threshold, protected
|
|
924
|
+
* window, already-pruned) stay silent so a compaction does not add noise for
|
|
925
|
+
* every request.
|
|
926
|
+
*/
|
|
927
|
+
function logContextPrune(stats: PruneStats): void {
|
|
928
|
+
if (!stats.changed) return
|
|
929
|
+
appendV2HookLog(
|
|
930
|
+
`[context-pruner] site=${stats.site} messages=${stats.messagesTouched} ` +
|
|
931
|
+
`parts=${stats.partsPruned} est_tokens_saved=${stats.estimatedTokensSaved}`,
|
|
932
|
+
)
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* Fail-open diagnostics: at most ONE line per session, whatever the engine
|
|
937
|
+
* threw or however malformed the payload was. Bounded so a long-lived host
|
|
938
|
+
* cannot accumulate session ids forever.
|
|
939
|
+
*/
|
|
940
|
+
const pruneFailureSessions = new Set<string>()
|
|
941
|
+
const PRUNE_FAILURE_SESSIONS_MAX = 256
|
|
942
|
+
|
|
943
|
+
function logPruneFailureOnce(sessionID: unknown, site: PruneSite, error: unknown): void {
|
|
944
|
+
const session = typeof sessionID === 'string' && sessionID !== '' ? sessionID : ''
|
|
945
|
+
const key = session !== '' ? session : `${site}:unknown`
|
|
946
|
+
if (pruneFailureSessions.has(key)) return
|
|
947
|
+
if (pruneFailureSessions.size >= PRUNE_FAILURE_SESSIONS_MAX) pruneFailureSessions.clear()
|
|
948
|
+
pruneFailureSessions.add(key)
|
|
949
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
950
|
+
appendV2HookLog(`[context-pruner] failed open site=${site} session=${key}: ${message}`)
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* A compaction payload whose `messages` is absent or misnamed is a shape drift,
|
|
955
|
+
* not a normal no-op: the feature is always-on at that site, so silence would
|
|
956
|
+
* hide the drift forever. Report `not-array`/`malformed` with the same
|
|
957
|
+
* once-per-session channel as a thrown failure. The `context` caller invokes
|
|
958
|
+
* this only when the feature is enabled.
|
|
959
|
+
*/
|
|
960
|
+
function logPruneShapeIssue(stats: PruneStats, sessionID: unknown, site: PruneSite): void {
|
|
961
|
+
if (stats.skipReason !== 'not-array' && stats.skipReason !== 'malformed') return
|
|
962
|
+
const detail =
|
|
963
|
+
stats.skipReason === 'not-array'
|
|
964
|
+
? 'not-array: payload.messages is not an array; input left unchanged'
|
|
965
|
+
: 'malformed: unexpected message shape; input left unchanged'
|
|
966
|
+
logPruneFailureOnce(sessionID, site, new Error(detail))
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/**
|
|
970
|
+
* Config typos are otherwise invisible: `keepTurn: 7` resolves to the default 4
|
|
971
|
+
* and the operator believes it applied. Warn ONCE per process, name the
|
|
972
|
+
* ignored keys and the accepted keys, and keep the fail-open resolution.
|
|
973
|
+
*/
|
|
974
|
+
let contextPrunerConfigWarned = false
|
|
975
|
+
|
|
976
|
+
function warnContextPrunerConfigOnce(options: unknown): void {
|
|
977
|
+
if (contextPrunerConfigWarned) return
|
|
978
|
+
try {
|
|
979
|
+
const issues = describeContextPrunerConfigIssues(options)
|
|
980
|
+
if (issues.length === 0) return
|
|
981
|
+
contextPrunerConfigWarned = true
|
|
982
|
+
appendV2HookLog(
|
|
983
|
+
`[context-pruner] ignored invalid context_pruner config: ${issues.join('; ')}; ` +
|
|
984
|
+
`accepted keys: ${CONTEXT_PRUNER_CONFIG_KEYS.join(', ')}`,
|
|
985
|
+
)
|
|
986
|
+
} catch {
|
|
987
|
+
// A validator must never break setup; silence is the only safe fallback.
|
|
988
|
+
contextPrunerConfigWarned = true
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// ─── Ambient memory injection (opt-in, V2 context hook) ─────────────────
|
|
993
|
+
|
|
994
|
+
/**
|
|
995
|
+
* One payload per session, computed on the session's first request. Bounded by
|
|
996
|
+
* `MEMORY_CACHE_MAX_SESSIONS` inside the cache (FIFO), so a long-lived host
|
|
997
|
+
* cannot grow it without limit. The payload is built, rendered and logged by
|
|
998
|
+
* `memory-context.ts`; this module only supplies the hook wiring and the
|
|
999
|
+
* `hooks.log` channel.
|
|
1000
|
+
*/
|
|
1001
|
+
const memoryInjectionCache = new MemoryInjectionCache()
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* Empty description cache for {@link sanitizeVisionHistory}.
|
|
1005
|
+
*
|
|
1006
|
+
* V1 fills this from the vision handler (per-part text captured at
|
|
1007
|
+
* `chat.message` time). V2 has no equivalent cache, so the sanitizer falls back
|
|
1008
|
+
* to its own placeholder text for every image part — which is the contract that
|
|
1009
|
+
* matters: an image never reaches the provider as image content.
|
|
1010
|
+
*/
|
|
1011
|
+
const V2_VISION_HISTORY_TEXT: ReadonlyMap<string, ReadonlyMap<string, string>> = new Map()
|
|
1012
|
+
|
|
657
1013
|
/**
|
|
658
1014
|
* Register session hooks via V2 ctx.session.hook.
|
|
659
1015
|
*
|
|
660
1016
|
* The V2 session.hook API (when available) provides:
|
|
661
1017
|
* ctx.session.hook("prompt", handler) — message admission
|
|
662
1018
|
* ctx.session.hook("context", handler) — system context injection
|
|
1019
|
+
* ctx.session.hook("compaction", handler) — registered in setup Phase 7
|
|
663
1020
|
*
|
|
664
1021
|
* Returns true if any hooks were registered.
|
|
665
1022
|
*/
|
|
666
1023
|
async function registerV2SessionHooks(context: PluginContext): Promise<boolean> {
|
|
1024
|
+
// Config validity is independent of hook availability; warn before the early
|
|
1025
|
+
// return so a typo is visible even on a host that registers no session hook.
|
|
1026
|
+
warnContextPrunerConfigOnce(context.options)
|
|
1027
|
+
warnInvalidMemoryInjectionConfig(context.options, appendV2HookLog)
|
|
667
1028
|
const sessionCtx = hostDomains(context).session
|
|
668
1029
|
|
|
669
1030
|
if (!sessionCtx?.hook) {
|
|
670
1031
|
return false
|
|
671
1032
|
}
|
|
672
1033
|
|
|
1034
|
+
// Resolved once, mirroring `resolveV2SandboxConfig(context.options)`: the
|
|
1035
|
+
// per-request context prune is opt-in because it invalidates the provider
|
|
1036
|
+
// prompt cache and has no measured cost baseline. The compaction site below
|
|
1037
|
+
// applies the rules unconditionally.
|
|
1038
|
+
const prunerConfig = resolveContextPrunerConfig(context.options)
|
|
1039
|
+
|
|
1040
|
+
// Ambient memory injection is opt-in and default OFF: with `enabled: false`
|
|
1041
|
+
// this hook adds nothing, so `system` stays byte-identical to the policy-only
|
|
1042
|
+
// output. Resolved here (not per request) for the same reason as the pruner.
|
|
1043
|
+
const memoryConfig = resolveMemoryInjectionConfig(context.options)
|
|
1044
|
+
|
|
673
1045
|
let registered = false
|
|
674
1046
|
|
|
675
1047
|
try {
|
|
@@ -692,15 +1064,67 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
|
|
|
692
1064
|
// string entries to `{ type: 'text', text }` parts and append the
|
|
693
1065
|
// policy as a part. Junk entries are ignored; a non-array,
|
|
694
1066
|
// non-string system is left untouched. Never throws (fail-open).
|
|
695
|
-
const ctx = event as
|
|
1067
|
+
const ctx = event as
|
|
1068
|
+
| { system?: unknown; messages?: unknown; sessionID?: unknown }
|
|
1069
|
+
| null
|
|
1070
|
+
| undefined
|
|
696
1071
|
if (ctx == null) return
|
|
697
1072
|
const normalized = normalizeSystemToParts(ctx.system)
|
|
698
|
-
if (normalized
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
1073
|
+
if (normalized != null) {
|
|
1074
|
+
// A bare string is replaced by its part array; an array is mutated in
|
|
1075
|
+
// place (the host may read the original reference).
|
|
1076
|
+
if (typeof ctx.system === 'string') ctx.system = normalized
|
|
1077
|
+
if (!hasPolicyMarker(normalized)) {
|
|
1078
|
+
normalized.push({ type: 'text', text: POLICY } satisfies SystemPart)
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
// Opt-in ambient memory injection: the top-K memories relevant to the
|
|
1082
|
+
// session's first user message, computed once per session and re-added
|
|
1083
|
+
// verbatim on later requests. Deliberately OUTSIDE the block above: with
|
|
1084
|
+
// `enabled: true` and no usable `system` there is nowhere to push, and
|
|
1085
|
+
// the module reports `skip=no-system` once per session instead of the
|
|
1086
|
+
// feature going silently inert. Off by default, so this is the only
|
|
1087
|
+
// thing `enabled: false` skips.
|
|
1088
|
+
if (memoryConfig.enabled) {
|
|
1089
|
+
applyMemoryInjection(
|
|
1090
|
+
normalized ?? ctx.system,
|
|
1091
|
+
ctx.messages,
|
|
1092
|
+
ctx.sessionID,
|
|
1093
|
+
memoryConfig,
|
|
1094
|
+
memoryInjectionCache,
|
|
1095
|
+
appendV2HookLog,
|
|
1096
|
+
)
|
|
1097
|
+
}
|
|
1098
|
+
// Vision history sanitization (V1
|
|
1099
|
+
// `experimental.chat.messages.transform` parity, #266). Image parts are
|
|
1100
|
+
// replaced with their cached description, or with the same placeholder
|
|
1101
|
+
// V1 uses, BEFORE a text-only provider serializer can turn them into
|
|
1102
|
+
// `image_url` content. The host's `context` payload carries the
|
|
1103
|
+
// provider-bound `messages` array and honors mutations per request, so
|
|
1104
|
+
// this is the same seam V1's transform occupies.
|
|
1105
|
+
//
|
|
1106
|
+
// The description map is empty on V2 by construction: descriptions are
|
|
1107
|
+
// cached by the V1 vision handler, which has no V2 counterpart (V2
|
|
1108
|
+
// materializes the image and asks the model to call `vision_describe`).
|
|
1109
|
+
// Every image part therefore becomes the placeholder — the safety
|
|
1110
|
+
// property V1's transform exists for — never a raw image.
|
|
1111
|
+
try {
|
|
1112
|
+
sanitizeVisionHistory({ messages: ctx.messages }, V2_VISION_HISTORY_TEXT)
|
|
1113
|
+
} catch (error) {
|
|
1114
|
+
logPruneFailureOnce(ctx.sessionID, 'context', error)
|
|
1115
|
+
}
|
|
1116
|
+
// Opt-in DCP: same engine as the compaction site, but per-request
|
|
1117
|
+
// pruning invalidates the prompt cache, so it runs only when
|
|
1118
|
+
// `context_pruner.enabled` is explicitly true. Disabled = the hook is
|
|
1119
|
+
// byte-for-byte the previous behaviour.
|
|
1120
|
+
if (prunerConfig.enabled) {
|
|
1121
|
+
try {
|
|
1122
|
+
const stats = pruneMessages(ctx.messages, prunerConfig, 'context')
|
|
1123
|
+
logContextPrune(stats)
|
|
1124
|
+
logPruneShapeIssue(stats, ctx.sessionID, 'context')
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
logPruneFailureOnce(ctx.sessionID, 'context', error)
|
|
1127
|
+
}
|
|
704
1128
|
}
|
|
705
1129
|
} catch {
|
|
706
1130
|
// Fail-open: never throw to the host.
|
|
@@ -712,12 +1136,31 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
|
|
|
712
1136
|
}
|
|
713
1137
|
|
|
714
1138
|
try {
|
|
715
|
-
// "prompt" hook —
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
1139
|
+
// "prompt" hook — preserve attached image references and add model-visible
|
|
1140
|
+
// instructions so Zeus can inspect visual context and pass it to the
|
|
1141
|
+
// implementation specialist before editing.
|
|
1142
|
+
await sessionCtx.hook('prompt', (event: unknown) => {
|
|
1143
|
+
try {
|
|
1144
|
+
// 2.0.29 host payload: `{ sessionID, messageID, prompt: { text,
|
|
1145
|
+
// files, agents, skills }, metadata, delivery }`. The session id is
|
|
1146
|
+
// top-level (verified against the host's `SessionPrompt.prepare`), so a
|
|
1147
|
+
// data: attachment's panic-free moment also relays it to the MCP.
|
|
1148
|
+
const admission = event as {
|
|
1149
|
+
sessionID?: unknown
|
|
1150
|
+
prompt?: { text?: unknown; files?: unknown }
|
|
1151
|
+
} | null
|
|
1152
|
+
const prompt = admission?.prompt
|
|
1153
|
+
if (!prompt || typeof prompt.text !== 'string') return
|
|
1154
|
+
if (prompt.text.includes('<!-- pantheon-v2-visual-context -->')) return
|
|
1155
|
+
const sessionID =
|
|
1156
|
+
typeof admission?.sessionID === 'string' && admission.sessionID.trim() !== ''
|
|
1157
|
+
? admission.sessionID
|
|
1158
|
+
: undefined
|
|
1159
|
+
const visualContext = buildV2VisionPromptContext(prompt.files, prompt.text, sessionID)
|
|
1160
|
+
if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
|
|
1161
|
+
} catch {
|
|
1162
|
+
// Fail-open: malformed/unsupported prompt shapes must not block input.
|
|
1163
|
+
}
|
|
721
1164
|
})
|
|
722
1165
|
registered = true
|
|
723
1166
|
} catch {
|
|
@@ -826,6 +1269,93 @@ function appendV2HookLog(line: string): boolean {
|
|
|
826
1269
|
}
|
|
827
1270
|
}
|
|
828
1271
|
|
|
1272
|
+
// ─── BENCH Hook Timing (beta-10 latency slice, Phase 0) ────────────────
|
|
1273
|
+
|
|
1274
|
+
/**
|
|
1275
|
+
* BENCH INSTRUMENTATION — observation only, zero behavior change.
|
|
1276
|
+
*
|
|
1277
|
+
* The beta-10 latency slice measures the V2 tool hook chain. These helpers
|
|
1278
|
+
* record the start/end of `execute.before` and `execute.after` per tool call
|
|
1279
|
+
* and append one single-line `[bench]` entry per hook end to the EXISTING
|
|
1280
|
+
* hooks.log channel (same appendV2HookLog path as every other line: masked,
|
|
1281
|
+
* stamped, best-effort, never throwing). The lines are consumed by
|
|
1282
|
+
* bench/lib/hooklog.mjs.
|
|
1283
|
+
*
|
|
1284
|
+
* Deliberate properties:
|
|
1285
|
+
* - the log call happens in `finally`, so denied calls (read-only guard,
|
|
1286
|
+
* secret block) are timed too, and the denial still propagates unchanged
|
|
1287
|
+
* - the join key is the host callID (`event.id`); a TTL-bounded map prunes
|
|
1288
|
+
* stale entries so a background/never-after call cannot leak memory
|
|
1289
|
+
* - `since_before_ms=unavailable` when no before record exists — the bench
|
|
1290
|
+
* contract never lets "unavailable" be encoded as 0
|
|
1291
|
+
*/
|
|
1292
|
+
|
|
1293
|
+
/** Entries older than this are pruned (a task tool result may never fire after). */
|
|
1294
|
+
const BENCH_TIMING_TTL_MS = 5 * 60_000
|
|
1295
|
+
/** Hard cap — mirrors the V1 delegationStarts bound. */
|
|
1296
|
+
const BENCH_TIMING_MAX = 256
|
|
1297
|
+
|
|
1298
|
+
const benchTimings = new Map<string, number>()
|
|
1299
|
+
|
|
1300
|
+
function pruneBenchTimings(now: number): void {
|
|
1301
|
+
for (const [callID, startedAt] of benchTimings) {
|
|
1302
|
+
if (now - startedAt > BENCH_TIMING_TTL_MS) benchTimings.delete(callID)
|
|
1303
|
+
}
|
|
1304
|
+
while (benchTimings.size >= BENCH_TIMING_MAX) {
|
|
1305
|
+
let oldestID: string | null = null
|
|
1306
|
+
let oldestAt = Number.POSITIVE_INFINITY
|
|
1307
|
+
for (const [id, at] of benchTimings) {
|
|
1308
|
+
if (at < oldestAt) {
|
|
1309
|
+
oldestAt = at
|
|
1310
|
+
oldestID = id
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
if (oldestID === null) break
|
|
1314
|
+
benchTimings.delete(oldestID)
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/** Read `{tool, id}` off a V2 tool event without assuming its exact shape. */
|
|
1319
|
+
function benchEventIdentity(event: unknown): { tool: string; callID: string } {
|
|
1320
|
+
if (event === null || typeof event !== 'object') return { tool: '', callID: '' }
|
|
1321
|
+
const payload = event as { tool?: unknown; id?: unknown }
|
|
1322
|
+
return {
|
|
1323
|
+
tool: typeof payload.tool === 'string' ? payload.tool : '',
|
|
1324
|
+
callID: typeof payload.id === 'string' ? payload.id : '',
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
/**
|
|
1329
|
+
* Append one `[bench]` timing line for a finished hook phase. Best-effort and
|
|
1330
|
+
* exception-free by construction (appendV2HookLog never throws).
|
|
1331
|
+
*/
|
|
1332
|
+
function logBenchHookTiming(phase: 'before' | 'after', event: unknown, startedAt: number): void {
|
|
1333
|
+
try {
|
|
1334
|
+
const { tool, callID } = benchEventIdentity(event)
|
|
1335
|
+
const endedAt = Date.now()
|
|
1336
|
+
if (phase === 'before') {
|
|
1337
|
+
if (callID !== '') {
|
|
1338
|
+
benchTimings.set(callID, startedAt)
|
|
1339
|
+
pruneBenchTimings(startedAt)
|
|
1340
|
+
}
|
|
1341
|
+
appendV2HookLog(
|
|
1342
|
+
`[bench] tool.execute.before end tool=${tool} callID=${callID} ` +
|
|
1343
|
+
`started_at=${new Date(startedAt).toISOString()} duration_ms=${endedAt - startedAt}`,
|
|
1344
|
+
)
|
|
1345
|
+
return
|
|
1346
|
+
}
|
|
1347
|
+
const beforeAt = callID !== '' ? benchTimings.get(callID) : undefined
|
|
1348
|
+
if (beforeAt !== undefined) benchTimings.delete(callID)
|
|
1349
|
+
const sinceBefore = beforeAt === undefined ? 'unavailable' : String(endedAt - beforeAt)
|
|
1350
|
+
appendV2HookLog(
|
|
1351
|
+
`[bench] tool.execute.after end tool=${tool} callID=${callID} ` +
|
|
1352
|
+
`duration_ms=${endedAt - startedAt} since_before_ms=${sinceBefore}`,
|
|
1353
|
+
)
|
|
1354
|
+
} catch {
|
|
1355
|
+
// Instrumentation must never affect the hook chain.
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
|
|
829
1359
|
// ─── V2 Secret-Scan Verdict ─────────────────────────────────────────────
|
|
830
1360
|
|
|
831
1361
|
/**
|
|
@@ -941,6 +1471,7 @@ export function setV2SecretScanRunnerForTests(runner: SecretScanRunner | null):
|
|
|
941
1471
|
interface V2ToolExecuteBeforeEvent {
|
|
942
1472
|
tool?: unknown
|
|
943
1473
|
sessionID?: unknown
|
|
1474
|
+
messageID?: unknown
|
|
944
1475
|
agent?: unknown
|
|
945
1476
|
id?: unknown
|
|
946
1477
|
input?: unknown
|
|
@@ -986,9 +1517,20 @@ interface V2ToolExecuteBeforeEvent {
|
|
|
986
1517
|
*
|
|
987
1518
|
* Omitting all three skips the branch wholesale: the guard only enters it when
|
|
988
1519
|
* `options?.isRootSession !== undefined`. `task` is still denied inside a
|
|
989
|
-
* read-only session via the blocked-tool list, so depth-2
|
|
990
|
-
* apollo/gaia
|
|
991
|
-
*
|
|
1520
|
+
* read-only session via the blocked-tool list, so the read-only half of depth-2
|
|
1521
|
+
* holds for apollo/gaia.
|
|
1522
|
+
*
|
|
1523
|
+
* The caller/target half is NOT this guard's job on V2, and that is a division
|
|
1524
|
+
* of labour rather than a gap: V2 delegates through the native `subagent` tool
|
|
1525
|
+
* and its `permission.hook('evaluate')` handler, which calls
|
|
1526
|
+
* `evaluateV2Delegation` — the matrix (zeus → anyone; athena/hermes → apollo)
|
|
1527
|
+
* plus the same depth-2 rule, expressed as "a caller session that carries a
|
|
1528
|
+
* `parentID` is denied". Both are proved in
|
|
1529
|
+
* tests/pantheon/plugin-v2-contract.test.ts and
|
|
1530
|
+
* tests/pantheon/v2-delegation-enforce.test.ts.
|
|
1531
|
+
*
|
|
1532
|
+
* The Zeus read guard is a SEPARATE call in the same `execute.before` handler
|
|
1533
|
+
* (issue #264), fed from the same event `agent`; it is not part of this guard.
|
|
992
1534
|
*/
|
|
993
1535
|
const v2EnforcementGuard = createEnforcementGuard({
|
|
994
1536
|
getReadOnlySessions: () => readOnlyRegistry.sessionIDs(),
|
|
@@ -1028,6 +1570,35 @@ function adaptV2ExecuteBeforeEvent(event: unknown): {
|
|
|
1028
1570
|
}
|
|
1029
1571
|
}
|
|
1030
1572
|
|
|
1573
|
+
/**
|
|
1574
|
+
* Test seam — override (or, with `null`, restore) the V2 shell-hook runner.
|
|
1575
|
+
*
|
|
1576
|
+
* Exported only for tests/pantheon/plugin-v2-contract.test.ts, which asserts
|
|
1577
|
+
* that the REGISTERED `execute.before`/`execute.after` handlers invoke the
|
|
1578
|
+
* formatter and the delegation audit scripts. Spawning the real scripts would
|
|
1579
|
+
* make the assertion depend on the shell, not on the wiring; the scripts
|
|
1580
|
+
* themselves are covered by tests/pantheon/v2-shell-hooks.test.ts.
|
|
1581
|
+
*/
|
|
1582
|
+
export function setV2ShellRunnerForTests(runner: V2ShellRunner | null): void {
|
|
1583
|
+
shellRunnerOverride = runner ?? undefined
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
let shellRunnerOverride: V2ShellRunner | undefined
|
|
1587
|
+
|
|
1588
|
+
/**
|
|
1589
|
+
* Test seam — clear the module-level bridge AND the process-wide registration.
|
|
1590
|
+
*
|
|
1591
|
+
* Exported only for tests/pantheon/plugin-v2-contract.test.ts. The co-load guard
|
|
1592
|
+
* makes `installV2Bridge` reuse an existing bridge (so V1's enforcer is never
|
|
1593
|
+
* duplicated), which means a test that asserts the CONSTRUCTION path has to
|
|
1594
|
+
* start from "no bridge". Production has no caller: a process keeps its bridge
|
|
1595
|
+
* for its lifetime.
|
|
1596
|
+
*/
|
|
1597
|
+
export function resetV2BridgeForTests(): void {
|
|
1598
|
+
v1Bridge = null
|
|
1599
|
+
registerV2Bridge(null)
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1031
1602
|
/**
|
|
1032
1603
|
* Register tool execution hooks via V2 ctx.tool.hook.
|
|
1033
1604
|
*
|
|
@@ -1037,14 +1608,34 @@ function adaptV2ExecuteBeforeEvent(event: unknown): {
|
|
|
1037
1608
|
*
|
|
1038
1609
|
* Returns true if any hooks were registered.
|
|
1039
1610
|
*/
|
|
1040
|
-
async function registerV2ToolHooks(
|
|
1041
|
-
|
|
1611
|
+
async function registerV2ToolHooks(
|
|
1612
|
+
context: PluginContext,
|
|
1613
|
+
subagentOrigins: V2SubagentOriginRegistry,
|
|
1614
|
+
boundedReadOrigins?: V2BoundedReadOriginRegistry,
|
|
1615
|
+
): Promise<{ registered: boolean; beforeRegistered: boolean }> {
|
|
1616
|
+
const host = hostDomains(context)
|
|
1617
|
+
const toolCtx = host.tool
|
|
1042
1618
|
|
|
1043
1619
|
if (!toolCtx?.hook) {
|
|
1044
|
-
return false
|
|
1620
|
+
return { registered: false, beforeRegistered: false }
|
|
1045
1621
|
}
|
|
1046
1622
|
|
|
1623
|
+
// V1 shell-hook parity (#266): formatter on every after-event, delegation
|
|
1624
|
+
// audit start/stop. Both scripts are environment-independent, so they are
|
|
1625
|
+
// invoked through the same runner the secret scan uses.
|
|
1626
|
+
const shellHooks = createV2ShellHooks({
|
|
1627
|
+
...(shellRunnerOverride === undefined ? {} : { run: shellRunnerOverride }),
|
|
1628
|
+
onUnkeyed: appendV2HookLog,
|
|
1629
|
+
})
|
|
1630
|
+
|
|
1631
|
+
// Symlink resolution for the Zeus read guard (#272). The predicate is pure,
|
|
1632
|
+
// so the filesystem work happens at this call site, rooted at the project
|
|
1633
|
+
// directory the host reports. Same mechanism as V1's (src/plugin.ts) so the
|
|
1634
|
+
// two registration paths stay consistent.
|
|
1635
|
+
const resolveGuardPath = createGuardPathResolver(host.location?.directory || process.cwd())
|
|
1636
|
+
|
|
1047
1637
|
let registered = false
|
|
1638
|
+
let beforeRegistered = false
|
|
1048
1639
|
|
|
1049
1640
|
try {
|
|
1050
1641
|
// "execute.before" — read-only enforcement. Throwing from this handler
|
|
@@ -1058,65 +1649,111 @@ async function registerV2ToolHooks(context: PluginContext): Promise<boolean> {
|
|
|
1058
1649
|
// here; without it the tools registered by registerV2Tools would be a live
|
|
1059
1650
|
// write path in every session, including read-only ones.
|
|
1060
1651
|
await toolCtx.hook('execute.before', async (event: unknown) => {
|
|
1652
|
+
const benchStartedAt = Date.now()
|
|
1061
1653
|
const { input, output, agent } = adaptV2ExecuteBeforeEvent(event)
|
|
1062
|
-
// V2's equivalent of V1's `chat.params` trigger: the host puts the active
|
|
1063
|
-
// agent on the event itself, so registering here needs no separate hook
|
|
1064
|
-
// and no session→agent map. A non-read-only (or absent) agent revokes the
|
|
1065
|
-
// registration, which also covers an in-session agent switch.
|
|
1066
|
-
syncReadOnlySession(readOnlyRegistry, input.sessionID, agent)
|
|
1067
|
-
// Deliberately OUTSIDE the try/catch below: a read-only denial must keep
|
|
1068
|
-
// propagating to the host, not be swallowed as a scanner failure.
|
|
1069
|
-
await v2EnforcementGuard(input, output)
|
|
1070
|
-
|
|
1071
|
-
// High-confidence secret scan (scripts/hooks/scan-secrets.sh). This is the
|
|
1072
|
-
// ONLY hard block on the V2 surface, and it exists here — rather than via
|
|
1073
|
-
// `src/plugins/pantheon-hooks.ts` — because that module is a separate
|
|
1074
|
-
// plugin that is never loaded on a V2-only install: opencode.json
|
|
1075
|
-
// `plugins` declares only `src/plugin-v2`. V1's scan-secrets block was
|
|
1076
|
-
// therefore inert by construction, not by misconfiguration.
|
|
1077
|
-
//
|
|
1078
|
-
// exit 0 → allow. exit 1 with a valid scanner report → advisory, logged
|
|
1079
|
-
// only. exit 2 (high-confidence match) → deny. A scanner that does NOT
|
|
1080
|
-
// produce a trustworthy verdict — missing/unexecutable script, timeout,
|
|
1081
|
-
// killed child, spawn/serialization failure, malformed or unexpected
|
|
1082
|
-
// output — is fail-CLOSED: this pending tool call is denied, the session
|
|
1083
|
-
// is not. (runHook resolves a structured result instead of rejecting, so
|
|
1084
|
-
// the exit-code-only reading below cannot lean on an exception.)
|
|
1085
|
-
let blockError: Error | null = null
|
|
1086
1654
|
try {
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1655
|
+
// V2's equivalent of V1's `chat.params` trigger: the host puts the active
|
|
1656
|
+
// agent on the event itself, so registering here needs no separate hook
|
|
1657
|
+
// and no session→agent map. A non-read-only (or absent) agent revokes the
|
|
1658
|
+
// registration, which also covers an in-session agent switch.
|
|
1659
|
+
syncReadOnlySession(readOnlyRegistry, input.sessionID, agent)
|
|
1660
|
+
// Zeus read guard (issue #264). V1 wires this from its `chat.params`
|
|
1661
|
+
// session→agent map (`src/plugin.ts`); V2 has no such map because the
|
|
1662
|
+
// host puts the active agent on THIS event, so the guard is fed from
|
|
1663
|
+
// the event's `agent` field — the same identity the read-only
|
|
1664
|
+
// registry above already trusts.
|
|
1665
|
+
//
|
|
1666
|
+
// Fail-closed on casing: `zeusReadGuard` compares the agent with an
|
|
1667
|
+
// exact `!== 'zeus'`, so a host that reports `Zeus` would silently
|
|
1668
|
+
// disable the guard. Normalizing through the shared
|
|
1669
|
+
// `normalizeDelegationAgent` keeps the comparison meaningful without
|
|
1670
|
+
// changing the predicate V1 uses.
|
|
1671
|
+
//
|
|
1672
|
+
// Runs BEFORE the read-only guard, matching V1's chain order. Both
|
|
1673
|
+
// throw to deny; neither is inside the scanner's try/catch, so a
|
|
1674
|
+
// denial keeps propagating to the host. The resolver is V1's too:
|
|
1675
|
+
// every TARGET path is also checked in its SYMLINK-RESOLVED form
|
|
1676
|
+
// (#272), and a resolution failure denies.
|
|
1677
|
+
zeusReadGuard(input.tool, output.args, normalizeDelegationAgent(agent), resolveGuardPath)
|
|
1678
|
+
// Deliberately OUTSIDE the try/catch below: a read-only denial must keep
|
|
1679
|
+
// propagating to the host, not be swallowed as a scanner failure.
|
|
1680
|
+
await v2EnforcementGuard(input, output)
|
|
1681
|
+
|
|
1682
|
+
// High-confidence secret scan (scripts/hooks/scan-secrets.sh). This is the
|
|
1683
|
+
// ONLY hard block on the V2 surface, and it exists here — rather than via
|
|
1684
|
+
// `src/plugins/pantheon-hooks.ts` — because that module is a separate
|
|
1685
|
+
// plugin that is never loaded on a V2-only install: opencode.json
|
|
1686
|
+
// `plugins` declares only `src/plugin-v2`. V1's scan-secrets block was
|
|
1687
|
+
// therefore inert by construction, not by misconfiguration.
|
|
1688
|
+
//
|
|
1689
|
+
// exit 0 → allow. exit 1 with a valid scanner report → advisory, logged
|
|
1690
|
+
// only. exit 2 (high-confidence match) → deny. A scanner that does NOT
|
|
1691
|
+
// produce a trustworthy verdict — missing/unexecutable script, timeout,
|
|
1692
|
+
// killed child, spawn/serialization failure, malformed or unexpected
|
|
1693
|
+
// output — is fail-CLOSED: this pending tool call is denied, the session
|
|
1694
|
+
// is not. (runHook resolves a structured result instead of rejecting, so
|
|
1695
|
+
// the exit-code-only reading below cannot lean on an exception.)
|
|
1696
|
+
let blockError: Error | null = null
|
|
1697
|
+
try {
|
|
1698
|
+
const payload: HookPayload = {
|
|
1699
|
+
tool_name: input.tool,
|
|
1700
|
+
tool_input: output.args ?? {},
|
|
1701
|
+
agent_id: typeof agent === 'string' ? agent : '',
|
|
1702
|
+
session_id: input.sessionID,
|
|
1703
|
+
}
|
|
1704
|
+
const scan = await secretScanRunner(payload)
|
|
1705
|
+
const decision = evaluateSecretScanResult(scan)
|
|
1706
|
+
if (decision.action === 'block') {
|
|
1707
|
+
appendV2HookLog(SECRET_BLOCK_MESSAGE)
|
|
1708
|
+
appendV2HookLog(scan.stderr)
|
|
1709
|
+
blockError = new Error(SECRET_BLOCK_MESSAGE)
|
|
1710
|
+
} else if (decision.action === 'advisory') {
|
|
1711
|
+
// Advisory: log only, never block.
|
|
1712
|
+
appendV2HookLog(scan.stderr)
|
|
1713
|
+
} else if (decision.action === 'fail-closed') {
|
|
1714
|
+
// Sanitized failure category only — never the scanner's raw stderr,
|
|
1715
|
+
// which on a failure path is unverified and may carry the very
|
|
1716
|
+
// payload the scan exists to keep out of logs.
|
|
1717
|
+
appendV2HookLog(`${SECRET_SCAN_UNAVAILABLE_MESSAGE} (${decision.reason})`)
|
|
1718
|
+
blockError = new Error(SECRET_SCAN_UNAVAILABLE_MESSAGE)
|
|
1719
|
+
}
|
|
1720
|
+
} catch {
|
|
1721
|
+
// The runner is contracted to resolve a structured result, so this only
|
|
1722
|
+
// guards an unexpected throw (including a future change to the runner).
|
|
1723
|
+
// A scanner that cannot run is fail-CLOSED: deny this call rather than
|
|
1724
|
+
// let it through with no scan at all.
|
|
1725
|
+
appendV2HookLog(SECRET_SCAN_UNAVAILABLE_MESSAGE)
|
|
1107
1726
|
blockError = new Error(SECRET_SCAN_UNAVAILABLE_MESSAGE)
|
|
1108
1727
|
}
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1728
|
+
if (blockError !== null) throw blockError
|
|
1729
|
+
const boundedReadOrigin = boundedReadOrigins?.capture(event)
|
|
1730
|
+
const eventTool = (event as V2ToolExecuteBeforeEvent | null)?.tool
|
|
1731
|
+
if (eventTool === BOUNDED_READ_TOOL && boundedReadOrigin === undefined) {
|
|
1732
|
+
throw new Error('BOUND_READ_UNAUTHORIZED')
|
|
1733
|
+
}
|
|
1734
|
+
if (boundedReadOrigin !== undefined) {
|
|
1735
|
+
writeV2AdmissionProof('tool.execute.before bounded-read', {
|
|
1736
|
+
sessionID: boundedReadOrigin.sessionID,
|
|
1737
|
+
messageID: boundedReadOrigin.messageID,
|
|
1738
|
+
callID: boundedReadOrigin.callID,
|
|
1739
|
+
agent: boundedReadOrigin.agent,
|
|
1740
|
+
})
|
|
1741
|
+
}
|
|
1742
|
+
const origin = subagentOrigins.capture(event)
|
|
1743
|
+
if (origin !== undefined) {
|
|
1744
|
+
writeV2AdmissionProof('tool.execute.before', { ...origin })
|
|
1745
|
+
}
|
|
1746
|
+
// Delegation audit START record (#266). Deliberately AFTER every guard
|
|
1747
|
+
// and the secret scan: a denied call must not leave a start record with
|
|
1748
|
+
// no matching stop. The formatter/stop halves run in `execute.after`.
|
|
1749
|
+
await shellHooks.before(event)
|
|
1750
|
+
} finally {
|
|
1751
|
+
// BENCH instrumentation — observation only; runs on the deny paths too.
|
|
1752
|
+
logBenchHookTiming('before', event, benchStartedAt)
|
|
1116
1753
|
}
|
|
1117
|
-
if (blockError !== null) throw blockError
|
|
1118
1754
|
})
|
|
1119
1755
|
registered = true
|
|
1756
|
+
beforeRegistered = true
|
|
1120
1757
|
} catch {
|
|
1121
1758
|
// Tool before-hook not supported
|
|
1122
1759
|
}
|
|
@@ -1134,13 +1771,28 @@ async function registerV2ToolHooks(context: PluginContext): Promise<boolean> {
|
|
|
1134
1771
|
const v2ExecuteAfter = createV2ExecuteAfter({
|
|
1135
1772
|
sandbox: resolveV2SandboxConfig(context.options),
|
|
1136
1773
|
})
|
|
1137
|
-
await toolCtx.hook('execute.after', (event: unknown) =>
|
|
1774
|
+
await toolCtx.hook('execute.after', async (event: unknown) => {
|
|
1775
|
+
const benchStartedAt = Date.now()
|
|
1776
|
+
try {
|
|
1777
|
+
subagentOrigins.forget(event)
|
|
1778
|
+
boundedReadOrigins?.forget(event)
|
|
1779
|
+
await v2ExecuteAfter(event)
|
|
1780
|
+
// Formatter + delegation audit STOP (#266). Awaited for the same
|
|
1781
|
+
// reason V1 awaits it: the log record should exist before the tool
|
|
1782
|
+
// result is surfaced. Failures are swallowed inside the module.
|
|
1783
|
+
await shellHooks.after(event)
|
|
1784
|
+
} finally {
|
|
1785
|
+
// BENCH instrumentation — observation only; the awaited call means the
|
|
1786
|
+
// duration covers the whole parity chain, not just its dispatch.
|
|
1787
|
+
logBenchHookTiming('after', event, benchStartedAt)
|
|
1788
|
+
}
|
|
1789
|
+
})
|
|
1138
1790
|
registered = true
|
|
1139
1791
|
} catch {
|
|
1140
1792
|
// Tool after-hook not supported
|
|
1141
1793
|
}
|
|
1142
1794
|
|
|
1143
|
-
return registered
|
|
1795
|
+
return { registered, beforeRegistered }
|
|
1144
1796
|
}
|
|
1145
1797
|
|
|
1146
1798
|
// ─── V2 Permission Hook ─────────────────────────────────────────────────
|
|
@@ -1155,7 +1807,10 @@ async function registerV2ToolHooks(context: PluginContext): Promise<boolean> {
|
|
|
1155
1807
|
*
|
|
1156
1808
|
* Returns true if the hook was registered.
|
|
1157
1809
|
*/
|
|
1158
|
-
async function registerV2PermissionHook(
|
|
1810
|
+
async function registerV2PermissionHook(
|
|
1811
|
+
context: PluginContext,
|
|
1812
|
+
subagentOrigins: V2SubagentOriginRegistry,
|
|
1813
|
+
): Promise<boolean> {
|
|
1159
1814
|
const domains = hostDomains(context)
|
|
1160
1815
|
const permCtx = domains.permission
|
|
1161
1816
|
|
|
@@ -1168,6 +1823,9 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1168
1823
|
await permCtx.hook('evaluate', async (rawEvent: unknown) => {
|
|
1169
1824
|
const event = rawEvent as V2PermissionEvent | null
|
|
1170
1825
|
const effectBefore = event?.effect
|
|
1826
|
+
let origin: ReturnType<V2SubagentOriginRegistry['consume']>
|
|
1827
|
+
let decision: string | null = null
|
|
1828
|
+
let callerSessionParentID: unknown
|
|
1171
1829
|
const writeProof = (): void => {
|
|
1172
1830
|
const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF
|
|
1173
1831
|
if (!proofPath || !event || !Array.isArray(event.resources)) return
|
|
@@ -1175,13 +1833,18 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1175
1833
|
appendFileSync(
|
|
1176
1834
|
proofPath,
|
|
1177
1835
|
`permission.evaluate ${JSON.stringify({
|
|
1836
|
+
action: event.action,
|
|
1178
1837
|
resources: event.resources,
|
|
1179
1838
|
agent: event.agent,
|
|
1180
1839
|
sessionID: event.sessionID,
|
|
1840
|
+
callerSessionParentID: callerSessionParentID ?? null,
|
|
1841
|
+
source: event.source,
|
|
1842
|
+
matchedOrigin: origin ?? null,
|
|
1843
|
+
decision,
|
|
1181
1844
|
effect: event.effect,
|
|
1182
1845
|
message: event.message,
|
|
1183
|
-
eventFields: ['resources', 'agent', 'sessionID', 'effect'].filter(
|
|
1184
|
-
Object.hasOwn(event, key),
|
|
1846
|
+
eventFields: ['action', 'resources', 'agent', 'sessionID', 'source', 'effect'].filter(
|
|
1847
|
+
(key) => Object.hasOwn(event, key),
|
|
1185
1848
|
),
|
|
1186
1849
|
effectBefore: effectBefore ?? null,
|
|
1187
1850
|
effectAfter: event.effect ?? null,
|
|
@@ -1227,6 +1890,11 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1227
1890
|
const hasPantheonTarget = targets.some((target) => PANTHEON_AGENTS.has(target ?? ''))
|
|
1228
1891
|
let session: AuthoritativeSession | undefined
|
|
1229
1892
|
if (hasPantheonTarget) {
|
|
1893
|
+
origin = subagentOrigins.consume(event)
|
|
1894
|
+
if (origin === undefined) {
|
|
1895
|
+
deny('matching host subagent tool origin is missing or stale')
|
|
1896
|
+
return
|
|
1897
|
+
}
|
|
1230
1898
|
const sessionID = typeof event.sessionID === 'string' ? event.sessionID.trim() : ''
|
|
1231
1899
|
if (!sessionID) {
|
|
1232
1900
|
deny('caller session ID is missing')
|
|
@@ -1255,11 +1923,12 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1255
1923
|
return
|
|
1256
1924
|
}
|
|
1257
1925
|
session = retrieved as AuthoritativeSession
|
|
1926
|
+
callerSessionParentID = session.parentID
|
|
1258
1927
|
}
|
|
1259
1928
|
|
|
1260
1929
|
// Native-only resources remain under host policy. If a Pantheon target
|
|
1261
1930
|
// appears anywhere, the shared policy evaluates the complete resource set.
|
|
1262
|
-
|
|
1931
|
+
decision = evaluateV2Delegation(event, session, event.effect, origin)
|
|
1263
1932
|
if (decision === 'deny') deny('caller or target is not allowed by delegation policy')
|
|
1264
1933
|
else writeProof()
|
|
1265
1934
|
})
|
|
@@ -1302,6 +1971,83 @@ export type { V2ToolDef, V2ToolResult } from './pantheon/v2-tools.ts'
|
|
|
1302
1971
|
interface V2SessionEvent {
|
|
1303
1972
|
type: string
|
|
1304
1973
|
properties?: Record<string, unknown>
|
|
1974
|
+
data?: unknown
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
/** Opt-in trace used by the isolated F4A canary; never logs prompts or inputs. */
|
|
1978
|
+
function writeV2AdmissionProof(label: string, detail: Record<string, unknown>): void {
|
|
1979
|
+
const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF
|
|
1980
|
+
if (!proofPath) return
|
|
1981
|
+
try {
|
|
1982
|
+
appendFileSync(proofPath, `${label} ${JSON.stringify(detail)}\n`)
|
|
1983
|
+
} catch {
|
|
1984
|
+
// Proof is best-effort and must not affect admission behavior.
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
async function prepareV2BoundedRead(
|
|
1989
|
+
context: PluginContext,
|
|
1990
|
+
): Promise<ReturnType<typeof createV2BoundedReadTool> | undefined> {
|
|
1991
|
+
const host = hostDomains(context)
|
|
1992
|
+
const directory = host.location?.directory
|
|
1993
|
+
const projectID = host.location?.project?.id
|
|
1994
|
+
const session = host.session
|
|
1995
|
+
const permission = host.permission
|
|
1996
|
+
if (
|
|
1997
|
+
typeof directory !== 'string' ||
|
|
1998
|
+
directory.trim() === '' ||
|
|
1999
|
+
typeof projectID !== 'string' ||
|
|
2000
|
+
projectID.trim() === '' ||
|
|
2001
|
+
typeof session?.get !== 'function' ||
|
|
2002
|
+
typeof permission?.assert !== 'function' ||
|
|
2003
|
+
typeof host.event?.subscribe !== 'function' ||
|
|
2004
|
+
typeof host.tool?.transform !== 'function' ||
|
|
2005
|
+
typeof host.tool?.hook !== 'function'
|
|
2006
|
+
) {
|
|
2007
|
+
markUnsupported('bounded-read')
|
|
2008
|
+
return undefined
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
const rootDirectory = await realpathAsync(directory).catch(() => undefined)
|
|
2012
|
+
if (rootDirectory === undefined) {
|
|
2013
|
+
markUnsupported('bounded-read')
|
|
2014
|
+
return undefined
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
return createV2BoundedReadTool({
|
|
2018
|
+
rootDirectory,
|
|
2019
|
+
projectID,
|
|
2020
|
+
getSession: (sessionID) => {
|
|
2021
|
+
if (typeof session.get !== 'function') throw new Error('session lookup unavailable')
|
|
2022
|
+
return session.get.call(session, { sessionID })
|
|
2023
|
+
},
|
|
2024
|
+
assertPermission: (request) => {
|
|
2025
|
+
if (typeof permission.assert !== 'function') throw new Error('permission API unavailable')
|
|
2026
|
+
return permission.assert.call(permission, request)
|
|
2027
|
+
},
|
|
2028
|
+
scanContent: async ({ content, agent, sessionID, callID }) => {
|
|
2029
|
+
try {
|
|
2030
|
+
const scan = await secretScanRunner({
|
|
2031
|
+
tool_name: BOUNDED_READ_TOOL,
|
|
2032
|
+
tool_input: { content },
|
|
2033
|
+
agent_id: agent,
|
|
2034
|
+
session_id: sessionID,
|
|
2035
|
+
})
|
|
2036
|
+
const decision = evaluateSecretScanResult(scan)
|
|
2037
|
+
if (decision.action === 'allow') return 'allow'
|
|
2038
|
+
const reason = decision.action === 'fail-closed' ? decision.reason : 'content-match'
|
|
2039
|
+
appendV2HookLog(
|
|
2040
|
+
`[SECRET SCAN] bounded read withheld session=${sessionID} callID=${callID} reason=${reason}`,
|
|
2041
|
+
)
|
|
2042
|
+
return decision.action === 'fail-closed' ? 'unavailable' : 'deny'
|
|
2043
|
+
} catch {
|
|
2044
|
+
appendV2HookLog(
|
|
2045
|
+
`[SECRET SCAN] bounded read withheld session=${sessionID} callID=${callID} reason=scanner-failure`,
|
|
2046
|
+
)
|
|
2047
|
+
return 'unavailable'
|
|
2048
|
+
}
|
|
2049
|
+
},
|
|
2050
|
+
})
|
|
1305
2051
|
}
|
|
1306
2052
|
|
|
1307
2053
|
/** Cleanup function type. */
|
|
@@ -1314,6 +2060,39 @@ export const plugin = define({
|
|
|
1314
2060
|
id: 'pantheon-opencode-v2',
|
|
1315
2061
|
|
|
1316
2062
|
async setup(context: PluginContext): Promise<void> {
|
|
2063
|
+
// ─── Phase 0: V1→V2 bridge (issue #265) ────────────────────────────
|
|
2064
|
+
// First, because the event subscription below can deliver `session.idle`
|
|
2065
|
+
// as soon as it starts: a bridge installed after it would lose the first
|
|
2066
|
+
// idle of the process. Constructing it here is what makes
|
|
2067
|
+
// `resolveBridge()` non-null on a V2 install — before this, the factory
|
|
2068
|
+
// and the injector had no production call site at all.
|
|
2069
|
+
//
|
|
2070
|
+
// The returned enforcer (when the host session domain supports it) is the
|
|
2071
|
+
// single instance: Phase 7 asks it for pending todos and the idle path asks
|
|
2072
|
+
// it to continue, so there are never two.
|
|
2073
|
+
//
|
|
2074
|
+
// Guarded, because this phase is the only one that MUTATES the context:
|
|
2075
|
+
// `injectBridge` writes `ctx.options`, and an unguarded throw here would
|
|
2076
|
+
// reject `setup()` and remove every later registration with it — the read
|
|
2077
|
+
// guard, the secret scan and all tools. A degraded run is far better than a
|
|
2078
|
+
// plugin that registers nothing, and the degradation is reported (`v1-bridge`
|
|
2079
|
+
// in the live unsupported list) instead of being invisible.
|
|
2080
|
+
let idleEnforcer: TodoEnforcer | undefined
|
|
2081
|
+
try {
|
|
2082
|
+
idleEnforcer = installV2Bridge(context)
|
|
2083
|
+
} catch (error) {
|
|
2084
|
+
idleEnforcer = undefined
|
|
2085
|
+
markUnsupported('v1-bridge')
|
|
2086
|
+
if (!bridgeFailureLogged) {
|
|
2087
|
+
bridgeFailureLogged = true
|
|
2088
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
2089
|
+
appendV2HookLog(
|
|
2090
|
+
`[v1-bridge] construction failed; continuing without a bridge ` +
|
|
2091
|
+
`(idle continuation and todo context unavailable): ${reason}`,
|
|
2092
|
+
)
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
|
|
1317
2096
|
// ─── Phase 1: V2 Transforms (isolated per-domain, best-effort) ────
|
|
1318
2097
|
// Each transform registration is individually wrapped and settled via Promise.allSettled:
|
|
1319
2098
|
// a rejection marks only that transform unsupported
|
|
@@ -1326,7 +2105,7 @@ export const plugin = define({
|
|
|
1326
2105
|
// is registered here — that is a Pantheon scope choice, not a host gap.
|
|
1327
2106
|
// ctx.catalog is the one domain the host does not provide.
|
|
1328
2107
|
// Phase 1 registers against the SDK-typed `context.agent` / `.command` /
|
|
1329
|
-
// `.reference` directly; the
|
|
2108
|
+
// `.reference` directly; the host domains the SDK omits are reached only
|
|
1330
2109
|
// through `hostDomains` (see the module header).
|
|
1331
2110
|
const phase1Transforms: Array<{ feature: string; register: () => Promise<unknown> }> = [
|
|
1332
2111
|
{ feature: 'agent-transform', register: () => context.agent.transform(transformAgents) },
|
|
@@ -1350,66 +2129,155 @@ export const plugin = define({
|
|
|
1350
2129
|
}
|
|
1351
2130
|
})
|
|
1352
2131
|
|
|
1353
|
-
|
|
1354
|
-
const
|
|
1355
|
-
if (
|
|
1356
|
-
markUnsupported('tool-transform')
|
|
1357
|
-
}
|
|
2132
|
+
const subagentOrigins = new V2SubagentOriginRegistry()
|
|
2133
|
+
const boundedRead = await prepareV2BoundedRead(context).catch(() => undefined)
|
|
2134
|
+
if (boundedRead === undefined) markUnsupported('bounded-read')
|
|
1358
2135
|
|
|
1359
|
-
// ─── Phase
|
|
1360
|
-
const eventCleanup = subscribeV2Events(context)
|
|
2136
|
+
// ─── Phase 2: V2 Event Subscription (best-effort) ────────────────
|
|
2137
|
+
const eventCleanup = subscribeV2Events(context, boundedRead?.clearSession)
|
|
1361
2138
|
if (eventCleanup) {
|
|
1362
2139
|
activeCleanups.push(eventCleanup)
|
|
1363
2140
|
} else {
|
|
1364
2141
|
markUnsupported('event-stream')
|
|
1365
2142
|
}
|
|
1366
2143
|
|
|
1367
|
-
// ─── Phase
|
|
2144
|
+
// ─── Phase 3: V2 Session Hooks (best-effort) ─────────────────────
|
|
1368
2145
|
const sessionHooksRegistered = await registerV2SessionHooks(context).catch(() => false)
|
|
1369
2146
|
if (!sessionHooksRegistered) {
|
|
1370
2147
|
markUnsupported('session-hooks')
|
|
1371
2148
|
}
|
|
1372
2149
|
|
|
1373
|
-
// ─── Phase
|
|
1374
|
-
const
|
|
1375
|
-
|
|
2150
|
+
// ─── Phase 4: V2 Tool Hooks (best-effort) ────────────────────────
|
|
2151
|
+
const toolHookResult = await registerV2ToolHooks(
|
|
2152
|
+
context,
|
|
2153
|
+
subagentOrigins,
|
|
2154
|
+
boundedRead?.origins,
|
|
2155
|
+
).catch(() => ({ registered: false, beforeRegistered: false }))
|
|
2156
|
+
if (!toolHookResult.registered) {
|
|
1376
2157
|
markUnsupported('tool-execute-hooks')
|
|
1377
2158
|
}
|
|
1378
2159
|
|
|
2160
|
+
// ─── Phase 5: V2 Tool Registration (best-effort) ─────────────────
|
|
2161
|
+
const boundedReadDefinition = toolHookResult.beforeRegistered
|
|
2162
|
+
? boundedRead?.definition
|
|
2163
|
+
: undefined
|
|
2164
|
+
if (boundedRead !== undefined && boundedReadDefinition === undefined) {
|
|
2165
|
+
markUnsupported('bounded-read')
|
|
2166
|
+
}
|
|
2167
|
+
const toolsRegistered = await registerV2Tools(context, boundedReadDefinition).catch(() => false)
|
|
2168
|
+
if (!toolsRegistered) markUnsupported('tool-transform')
|
|
2169
|
+
|
|
1379
2170
|
// ─── Phase 6: V2 Permission Hook (best-effort) ───────────────────
|
|
1380
|
-
await registerV2PermissionHook(context).catch(() => false)
|
|
2171
|
+
await registerV2PermissionHook(context, subagentOrigins).catch(() => false)
|
|
1381
2172
|
|
|
1382
2173
|
// ─── Phase 7: V2 Compaction Hook (best-effort) ───────────────────
|
|
1383
2174
|
const compactionCtx = hostDomains(context).session
|
|
1384
2175
|
if (compactionCtx?.hook) {
|
|
2176
|
+
// File-based goal store, constructed once: the compaction context needs
|
|
2177
|
+
// active goals per session, and the store needs no host API (same
|
|
2178
|
+
// `.pantheon/goals` directory V1 uses).
|
|
2179
|
+
const goalStore = new GoalStore({ dir: '.pantheon/goals' })
|
|
1385
2180
|
try {
|
|
1386
2181
|
// 2.0.16 `SessionHooks` key is `compaction` (the migration doc maps
|
|
1387
2182
|
// `experimental.session.compacting` → `ctx.session.hook("compaction")`).
|
|
1388
2183
|
// `compacting` is not a valid key: the registry accepts any string and
|
|
1389
2184
|
// silently drops unknown names, so the old name was a permanent no-op.
|
|
1390
2185
|
// Proven by the canary's negative control.
|
|
1391
|
-
await compactionCtx.hook('compaction', (
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
'plugin-v2:session.hook:compaction\n',
|
|
1409
|
-
)
|
|
1410
|
-
} catch {
|
|
1411
|
-
// Proof is best-effort: never let instrumentation break the host.
|
|
2186
|
+
await compactionCtx.hook('compaction', async (event: unknown) => {
|
|
2187
|
+
try {
|
|
2188
|
+
// Opt-in lifetime proof for the host-backed hook canary
|
|
2189
|
+
// (tests/pantheon/plugin-v2-hook-canary.test.mjs, MODE=real). It is
|
|
2190
|
+
// inert unless PANTHEON_HOOK_CANARY_LIFETIME_PROOF is set, so
|
|
2191
|
+
// production behaviour is unchanged. This exists because a rename to
|
|
2192
|
+
// `compacting` was a silent no-op for an unknown length of time: the
|
|
2193
|
+
// canary can now observe that THIS registration fired.
|
|
2194
|
+
if (process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF) {
|
|
2195
|
+
try {
|
|
2196
|
+
appendFileSync(
|
|
2197
|
+
process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF,
|
|
2198
|
+
'plugin-v2:session.hook:compaction\n',
|
|
2199
|
+
)
|
|
2200
|
+
} catch {
|
|
2201
|
+
// Proof is best-effort: never let instrumentation break the host.
|
|
2202
|
+
}
|
|
1412
2203
|
}
|
|
2204
|
+
|
|
2205
|
+
// DCP dynamic context pruning (V2 only). This hook receives the
|
|
2206
|
+
// provider-bound array exactly before the summarization request,
|
|
2207
|
+
// and mutations are honored per request — the persisted session is
|
|
2208
|
+
// untouched. Apply the rules by default: it only changes what feeds
|
|
2209
|
+
// the summary. Never set `input.result`: the model must summarize
|
|
2210
|
+
// the pruned history, not be replaced by a canned summary.
|
|
2211
|
+
//
|
|
2212
|
+
// The host's compaction payload is
|
|
2213
|
+
// `{ session, agent, model, tools, system, messages, … }` — the id
|
|
2214
|
+
// is on `session.id`, NOT top-level `sessionID` (measured against
|
|
2215
|
+
// the 2.1.4 host; both spellings are accepted below).
|
|
2216
|
+
const payload = event as {
|
|
2217
|
+
sessionID?: unknown
|
|
2218
|
+
session?: { id?: unknown }
|
|
2219
|
+
messages?: unknown
|
|
2220
|
+
system?: unknown
|
|
2221
|
+
} | null
|
|
2222
|
+
const sessionID =
|
|
2223
|
+
typeof payload?.sessionID === 'string'
|
|
2224
|
+
? payload.sessionID
|
|
2225
|
+
: typeof payload?.session?.id === 'string'
|
|
2226
|
+
? payload.session.id
|
|
2227
|
+
: undefined
|
|
2228
|
+
const prunerConfig = resolveContextPrunerConfig(context.options)
|
|
2229
|
+
const stats = pruneMessages(payload?.messages, prunerConfig, 'compaction')
|
|
2230
|
+
logContextPrune(stats)
|
|
2231
|
+
logPruneShapeIssue(stats, sessionID, 'compaction')
|
|
2232
|
+
|
|
2233
|
+
// Compaction context (V1 `experimental.session.compacting`
|
|
2234
|
+
// parity, #266). The SAME builder V1 uses — directive +
|
|
2235
|
+
// `<mission_context>` — pushed into the payload's `system` array,
|
|
2236
|
+
// which is the only text sink the V2 compaction hook exposes
|
|
2237
|
+
// (`context` is the session-hook name in V1, not a field here).
|
|
2238
|
+
//
|
|
2239
|
+
// The `<todo_context>` section is present only when the bridge
|
|
2240
|
+
// built a real enforcer (host session domain exposes the todo
|
|
2241
|
+
// listing), and `<tool_ceiling>` has no V2 producer at all — both
|
|
2242
|
+
// reductions are declared in the capability seed instead of
|
|
2243
|
+
// silently missing.
|
|
2244
|
+
const blocks = await buildCompactionContext({
|
|
2245
|
+
...(sessionID === undefined ? {} : { sessionID }),
|
|
2246
|
+
goals: {
|
|
2247
|
+
// Same gate V1 uses: the goal loop is disabled in this build,
|
|
2248
|
+
// so `<mission_context>` is omitted on both surfaces.
|
|
2249
|
+
enabled: GOAL_LOOP_DEFAULTS.enabled,
|
|
2250
|
+
list: (id: string) => goalStore.list(id),
|
|
2251
|
+
},
|
|
2252
|
+
...(idleEnforcer === undefined
|
|
2253
|
+
? {}
|
|
2254
|
+
: {
|
|
2255
|
+
todos: {
|
|
2256
|
+
// V1's own source: `TodoEnforcer.listPendingTodos`.
|
|
2257
|
+
enabled: todoEnforcerEnabledFromEnv(),
|
|
2258
|
+
list: (id: string) => idleEnforcer.listPendingTodos(id),
|
|
2259
|
+
},
|
|
2260
|
+
}),
|
|
2261
|
+
})
|
|
2262
|
+
if (blocks.length > 0 && !appendSystemBlocks(payload, blocks)) {
|
|
2263
|
+
// The payload carried no usable `system`. Diagnostic once per
|
|
2264
|
+
// process: a silent miss here would look like "no goals".
|
|
2265
|
+
if (!compactionChannelWarned) {
|
|
2266
|
+
compactionChannelWarned = true
|
|
2267
|
+
appendV2HookLog(
|
|
2268
|
+
'[compaction-context] payload.system is not a string or array; ' +
|
|
2269
|
+
'compaction context could not be injected',
|
|
2270
|
+
)
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
} catch (error) {
|
|
2274
|
+
// Fail-open: any unexpected shape or engine failure must not kill
|
|
2275
|
+
// the compaction request. One diagnostic line per session maximum.
|
|
2276
|
+
logPruneFailureOnce(
|
|
2277
|
+
(event as { sessionID?: unknown } | null)?.sessionID,
|
|
2278
|
+
'compaction',
|
|
2279
|
+
error,
|
|
2280
|
+
)
|
|
1413
2281
|
}
|
|
1414
2282
|
})
|
|
1415
2283
|
} catch {
|