pantheon-opencode 1.6.0-beta.8 → 1.6.0
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 +126 -346
- package/README.md +83 -608
- package/README.pt-BR.md +120 -345
- package/bin/pantheon-init.mjs +366 -132
- package/commands/pantheon-audit.md +7 -1
- package/commands/pantheon-consolidate.md +1 -1
- package/commands/pantheon-deepwork.md +14 -3
- package/commands/pantheon-focus.md +17 -0
- package/commands/pantheon-vision.md +61 -12
- package/package.json +19 -11
- 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 +828 -40
- 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 +78 -383
- package/scripts/install/migrate.mjs +49 -25
- package/scripts/install/model-picker.mjs +218 -250
- package/scripts/install/opencode-version.mjs +83 -21
- package/scripts/install/opencode.mjs +1465 -180
- package/scripts/install/plan-artifact.mjs +517 -0
- package/scripts/install/plan.mjs +475 -0
- package/scripts/install/plugin.mjs +251 -30
- package/scripts/install/prompt-result.mjs +2 -0
- package/scripts/install/shared.mjs +256 -99
- package/scripts/install/state.mjs +63 -8
- package/scripts/install/strings.mjs +60 -4
- 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 +682 -0
- package/scripts/restore.mjs +222 -0
- package/scripts/run-node-tests.mjs +24 -8
- package/scripts/sync-artifacts.mjs +20 -7
- package/scripts/sync-tui.mjs +29 -4
- 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 +14 -15
- 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 +5 -0
- package/src/pantheon/context-pruner.ts +541 -0
- package/src/pantheon/cost-command.ts +814 -60
- package/src/pantheon/goal-loop.ts +11 -8
- 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 +640 -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-tools.ts +89 -35
- package/src/pantheon/v2-unsupported.mjs +2 -3
- package/src/pantheon/v2-vision.ts +622 -0
- package/src/pantheon/vision-local.ts +531 -0
- package/src/pantheon/vision.ts +1160 -115
- package/src/plugin-v2.ts +654 -162
- package/src/plugin.ts +15 -11
- package/src/plugins/tui/dist/tui-v2.d.ts +1036 -0
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -0
- package/src/plugins/tui/dist/tui-v2.js +3808 -0
- package/src/plugins/tui/dist/tui-v2.js.map +1 -0
- package/src/plugins/tui/dist/tui.js +4 -4
- package/src/plugins/tui/index-v2.ts +6 -0
- package/src/plugins/tui/package-lock.json +5416 -1297
- package/src/plugins/tui/package.json +14 -10
- package/src/plugins/tui/src/index-v2.tsx +4372 -0
- package/src/plugins/tui/src/index.tsx +3 -3
- package/src/plugins/tui/src/opencode-v2.d.ts +13 -0
- package/src/plugins/tui/tsconfig.typecheck.json +5 -0
- package/src/plugins/tui/tsdown.config.ts +2 -2
- package/src/plugins/tui/tui-v2.ts +2 -0
- package/src/plugins/tui/tui.ts +3 -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 +14 -15
- 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,6 +88,14 @@ 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 {
|
|
92
|
+
CONTEXT_PRUNER_CONFIG_KEYS,
|
|
93
|
+
describeContextPrunerConfigIssues,
|
|
94
|
+
type PruneSite,
|
|
95
|
+
type PruneStats,
|
|
96
|
+
pruneMessages,
|
|
97
|
+
resolveContextPrunerConfig,
|
|
98
|
+
} from './pantheon/context-pruner.ts'
|
|
84
99
|
import {
|
|
85
100
|
createEnforcementGuard,
|
|
86
101
|
readOnlyRegistry,
|
|
@@ -88,6 +103,17 @@ import {
|
|
|
88
103
|
type ToolExecuteBeforeInput,
|
|
89
104
|
type ToolExecuteBeforeOutput,
|
|
90
105
|
} from './pantheon/delegation-enforce.ts'
|
|
106
|
+
import {
|
|
107
|
+
applyMemoryInjection,
|
|
108
|
+
MemoryInjectionCache,
|
|
109
|
+
resolveMemoryInjectionConfig,
|
|
110
|
+
warnInvalidMemoryInjectionConfig,
|
|
111
|
+
} from './pantheon/memory-context.ts'
|
|
112
|
+
import {
|
|
113
|
+
BOUNDED_READ_TOOL,
|
|
114
|
+
createV2BoundedReadTool,
|
|
115
|
+
type V2BoundedReadOriginRegistry,
|
|
116
|
+
} from './pantheon/v2-bounded-read.ts'
|
|
91
117
|
import {
|
|
92
118
|
getV2BridgeFromContext,
|
|
93
119
|
type PantheonV2Bridge,
|
|
@@ -98,11 +124,14 @@ import {
|
|
|
98
124
|
evaluateV2Delegation,
|
|
99
125
|
PANTHEON_AGENTS,
|
|
100
126
|
type V2PermissionEvent,
|
|
127
|
+
V2SubagentOriginRegistry,
|
|
101
128
|
v2ResourceTarget,
|
|
102
129
|
} from './pantheon/v2-delegation-enforce.ts'
|
|
103
130
|
import { createV2ExecuteAfter, resolveV2SandboxConfig } from './pantheon/v2-execute-after.ts'
|
|
131
|
+
import { applyV2ModelOverrides, readV2ModelConfiguration } from './pantheon/v2-model-overrides.ts'
|
|
104
132
|
import { createV2ToolDefinitions, type V2ToolResult } from './pantheon/v2-tools.ts'
|
|
105
133
|
import { V2_UNSUPPORTED_FEATURE_SEED } from './pantheon/v2-unsupported.mjs'
|
|
134
|
+
import { buildV2VisionPromptContext, type V2VisionRuntime } from './pantheon/v2-vision.ts'
|
|
106
135
|
import { type HookPayload, type HookResult, runHook } from './plugins/hook-runner.ts'
|
|
107
136
|
|
|
108
137
|
// ─── Unsupported Features Registry ───────────────────────────────────────
|
|
@@ -233,6 +262,7 @@ interface V2EventDomain {
|
|
|
233
262
|
* domain and the host may evolve independently.
|
|
234
263
|
*/
|
|
235
264
|
interface V2PermissionDomain {
|
|
265
|
+
assert?: (input: Record<string, unknown>) => Promise<unknown>
|
|
236
266
|
hook?: (
|
|
237
267
|
name: string,
|
|
238
268
|
handler: (event: unknown, output?: unknown) => void | Promise<void>,
|
|
@@ -250,12 +280,28 @@ interface V2SessionDomain {
|
|
|
250
280
|
get?: (input: { sessionID: string }) => Promise<unknown>
|
|
251
281
|
}
|
|
252
282
|
|
|
253
|
-
|
|
283
|
+
interface V2LocationDomain {
|
|
284
|
+
directory?: string
|
|
285
|
+
project?: { id?: string }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
interface V2ModelDomain {
|
|
289
|
+
list?: V2VisionRuntime['model']['list']
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
interface V2GenerateDomain {
|
|
293
|
+
text?: (input: { model: { providerID: string; id: string }; prompt: string }) => Promise<unknown>
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** `PluginContext` plus the host domains 1.18.x omits. See the module header. */
|
|
254
297
|
interface HostPluginContext extends PluginContext {
|
|
255
298
|
tool?: V2ToolDomain
|
|
256
299
|
event?: V2EventDomain
|
|
257
300
|
permission?: V2PermissionDomain
|
|
258
301
|
session?: V2SessionDomain
|
|
302
|
+
model?: V2ModelDomain
|
|
303
|
+
generate?: V2GenerateDomain
|
|
304
|
+
location?: V2LocationDomain
|
|
259
305
|
}
|
|
260
306
|
|
|
261
307
|
/**
|
|
@@ -324,6 +370,18 @@ function transformAgents(draft: AgentDraft): void {
|
|
|
324
370
|
markUnsupported('agent-transform-list')
|
|
325
371
|
return
|
|
326
372
|
}
|
|
373
|
+
try {
|
|
374
|
+
const modelConfiguration = readV2ModelConfiguration()
|
|
375
|
+
if (modelConfiguration.warnings.length > 0) {
|
|
376
|
+
// The V2 server PluginContext has no documented user-visible notification
|
|
377
|
+
// or logging channel; preserve the degradation for status diagnostics.
|
|
378
|
+
markUnsupported('agent-model-overrides')
|
|
379
|
+
}
|
|
380
|
+
applyV2ModelOverrides(draft, modelConfiguration.overrides)
|
|
381
|
+
} catch {
|
|
382
|
+
// Model configuration is optional. Preserve host models if it cannot be read.
|
|
383
|
+
markUnsupported('agent-model-overrides')
|
|
384
|
+
}
|
|
327
385
|
try {
|
|
328
386
|
for (const agent of agents) {
|
|
329
387
|
draft.update(agent.id, (current) => {
|
|
@@ -415,8 +473,12 @@ function transformReferences(draft: ReferenceDraft): void {
|
|
|
415
473
|
*
|
|
416
474
|
* Returns true if tools were registered, false if the API is unavailable.
|
|
417
475
|
*/
|
|
418
|
-
async function registerV2Tools(
|
|
419
|
-
|
|
476
|
+
async function registerV2Tools(
|
|
477
|
+
context: PluginContext,
|
|
478
|
+
boundedRead?: ReturnType<typeof createV2BoundedReadTool>['definition'],
|
|
479
|
+
): Promise<boolean> {
|
|
480
|
+
const host = hostDomains(context)
|
|
481
|
+
const toolCtx = host.tool
|
|
420
482
|
|
|
421
483
|
if (!toolCtx?.transform) {
|
|
422
484
|
return false
|
|
@@ -426,7 +488,12 @@ async function registerV2Tools(context: PluginContext): Promise<boolean> {
|
|
|
426
488
|
// Tool definitions carry their own `output` declaration; the draft requires
|
|
427
489
|
// it, and the host rejects a definition whose result shape cannot satisfy
|
|
428
490
|
// the declaration it makes.
|
|
429
|
-
const
|
|
491
|
+
const model = host.model
|
|
492
|
+
const visionReady = typeof model?.list === 'function'
|
|
493
|
+
if (!visionReady) markUnsupported('vision-tool')
|
|
494
|
+
const visionRuntime = visionReady ? ({ model } as V2VisionRuntime) : undefined
|
|
495
|
+
const toolDefs = createV2ToolDefinitions(visionRuntime)
|
|
496
|
+
if (boundedRead !== undefined) toolDefs.push(boundedRead)
|
|
430
497
|
|
|
431
498
|
await toolCtx.transform((draft: V2ToolDraft) => {
|
|
432
499
|
// Catalog grouping only. The host computes a tool's registration id as
|
|
@@ -466,7 +533,10 @@ async function registerV2Tools(context: PluginContext): Promise<boolean> {
|
|
|
466
533
|
*
|
|
467
534
|
* Returns a cleanup function, or undefined if the API is unavailable.
|
|
468
535
|
*/
|
|
469
|
-
function subscribeV2Events(
|
|
536
|
+
function subscribeV2Events(
|
|
537
|
+
context: PluginContext,
|
|
538
|
+
onTurnEnd?: (sessionID: string) => void,
|
|
539
|
+
): (() => void) | undefined {
|
|
470
540
|
const eventCtx = hostDomains(context).event
|
|
471
541
|
|
|
472
542
|
if (!eventCtx?.subscribe) {
|
|
@@ -479,6 +549,19 @@ function subscribeV2Events(context: PluginContext): (() => void) | undefined {
|
|
|
479
549
|
// biome-ignore lint/style/noNonNullAssertion: subscribe guaranteed by guard above
|
|
480
550
|
for await (const event of eventCtx.subscribe!({ signal: controller.signal })) {
|
|
481
551
|
await handleV2SessionEvent(event)
|
|
552
|
+
if (event.type === 'session.idle' || event.type === 'session.deleted') {
|
|
553
|
+
const properties = event.properties ?? {}
|
|
554
|
+
const info = properties.info
|
|
555
|
+
const infoID =
|
|
556
|
+
info !== null && typeof info === 'object' ? (info as { id?: unknown }).id : undefined
|
|
557
|
+
const sessionID =
|
|
558
|
+
typeof properties.sessionID === 'string'
|
|
559
|
+
? properties.sessionID
|
|
560
|
+
: typeof infoID === 'string'
|
|
561
|
+
? infoID
|
|
562
|
+
: undefined
|
|
563
|
+
if (sessionID) onTurnEnd?.(sessionID)
|
|
564
|
+
}
|
|
482
565
|
}
|
|
483
566
|
} catch (err: unknown) {
|
|
484
567
|
if (err instanceof Error && err.name === 'AbortError') return
|
|
@@ -516,48 +599,39 @@ async function handleV2SessionEvent(event: V2SessionEvent): Promise<void> {
|
|
|
516
599
|
}
|
|
517
600
|
|
|
518
601
|
/**
|
|
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".
|
|
602
|
+
* Record the v2.0.29 lifecycle event in the opt-in F4A canary. Runtime events
|
|
603
|
+
* use a `{ id, created, type, data }` envelope; the child data carries
|
|
604
|
+
* `sessionID`, `parentID` and `agent`. Admission itself does not depend on this
|
|
605
|
+
* subscription: it checks the current permission source and `ctx.session.get`
|
|
606
|
+
* synchronously, so resumed roots and children use the same path.
|
|
559
607
|
*/
|
|
560
|
-
async function onSessionCreated(
|
|
608
|
+
async function onSessionCreated(event: V2SessionEvent): Promise<void> {
|
|
609
|
+
const payload = event as V2SessionEvent & Record<string, unknown>
|
|
610
|
+
const properties = event.properties ?? {}
|
|
611
|
+
const data =
|
|
612
|
+
event.data !== null && typeof event.data === 'object'
|
|
613
|
+
? (event.data as Record<string, unknown>)
|
|
614
|
+
: {}
|
|
615
|
+
const info = properties.info ?? data.info
|
|
616
|
+
const sessionInfo =
|
|
617
|
+
info !== null && typeof info === 'object' ? (info as Record<string, unknown>) : {}
|
|
618
|
+
writeV2AdmissionProof('session.created', {
|
|
619
|
+
eventKeys: Object.keys(payload),
|
|
620
|
+
propertyKeys: Object.keys(properties),
|
|
621
|
+
dataKeys: Object.keys(data),
|
|
622
|
+
infoKeys: Object.keys(sessionInfo),
|
|
623
|
+
id:
|
|
624
|
+
sessionInfo.id ??
|
|
625
|
+
sessionInfo.sessionID ??
|
|
626
|
+
data.id ??
|
|
627
|
+
data.sessionID ??
|
|
628
|
+
properties.id ??
|
|
629
|
+
properties.sessionID ??
|
|
630
|
+
payload.sessionID ??
|
|
631
|
+
null,
|
|
632
|
+
parentID: sessionInfo.parentID ?? data.parentID ?? properties.parentID ?? null,
|
|
633
|
+
agent: sessionInfo.agent ?? data.agent ?? properties.agent ?? null,
|
|
634
|
+
})
|
|
561
635
|
const _bridge = resolveBridge()
|
|
562
636
|
if (_bridge?.board != null) {
|
|
563
637
|
// Bridge present ⇒ this process also loaded V1, whose own event hook owns
|
|
@@ -566,6 +640,22 @@ async function onSessionCreated(_event: V2SessionEvent): Promise<void> {
|
|
|
566
640
|
}
|
|
567
641
|
|
|
568
642
|
async function onSessionIdle(_event: V2SessionEvent): Promise<void> {
|
|
643
|
+
// Temp-image sweep on the V2-only path: DELIBERATELY DEFERRED.
|
|
644
|
+
//
|
|
645
|
+
// V1 unlinks a session's temp images on `session.idle`/`session.deleted`
|
|
646
|
+
// (`cleanupSessionTempImages`, grace-guarded and refcounted). V2 cannot reuse
|
|
647
|
+
// it: `saveDataUrlImageSync` (the V2 materialization path) receives no session
|
|
648
|
+
// id, so there is no per-session `path → createdAt` map to sweep, and the
|
|
649
|
+
// content-hash temp dir is refcounted ONLY on the V1 path. The one reusable
|
|
650
|
+
// piece, `enforceTempFileCap`, is already invoked off every V2 save
|
|
651
|
+
// (`saveDataUrlImageSync`), so disk usage is bounded without an idle pass —
|
|
652
|
+
// re-running it here would be redundant, and a GLOBAL age-based unlink fired
|
|
653
|
+
// by one session's idle could delete a file another live session still
|
|
654
|
+
// references. Delivery is also best-effort: with no `ctx.event.subscribe`
|
|
655
|
+
// the stream is unsupported (`markUnsupported('event-stream')`) and no idle
|
|
656
|
+
// ever arrives. Implementing this safely needs V2-side session threading
|
|
657
|
+
// first; until then it stays deferred rather than approximated.
|
|
658
|
+
//
|
|
569
659
|
// Idle continuation — goal loop / todo enforcer dispatch. This one really
|
|
570
660
|
// does delegate: `bridge.todoEnforcer` is the V1 enforcer instance, reached
|
|
571
661
|
// only in a process that also loaded V1. On a V2-only install the bridge
|
|
@@ -632,6 +722,7 @@ async function onSessionDeleted(event: V2SessionEvent): Promise<void> {
|
|
|
632
722
|
return
|
|
633
723
|
}
|
|
634
724
|
readOnlyRegistry.unregister(sessionID)
|
|
725
|
+
memoryInjectionCache.delete(sessionID)
|
|
635
726
|
}
|
|
636
727
|
|
|
637
728
|
/**
|
|
@@ -654,22 +745,120 @@ async function onSessionCompacted(_event: V2SessionEvent): Promise<void> {}
|
|
|
654
745
|
|
|
655
746
|
// ─── V2 Session Hooks ───────────────────────────────────────────────────
|
|
656
747
|
|
|
748
|
+
/**
|
|
749
|
+
* One-line prune stats entry through the existing hooks.log channel only when
|
|
750
|
+
* a pass actually rewrote something. Silent no-ops (below threshold, protected
|
|
751
|
+
* window, already-pruned) stay silent so a compaction does not add noise for
|
|
752
|
+
* every request.
|
|
753
|
+
*/
|
|
754
|
+
function logContextPrune(stats: PruneStats): void {
|
|
755
|
+
if (!stats.changed) return
|
|
756
|
+
appendV2HookLog(
|
|
757
|
+
`[context-pruner] site=${stats.site} messages=${stats.messagesTouched} ` +
|
|
758
|
+
`parts=${stats.partsPruned} est_tokens_saved=${stats.estimatedTokensSaved}`,
|
|
759
|
+
)
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Fail-open diagnostics: at most ONE line per session, whatever the engine
|
|
764
|
+
* threw or however malformed the payload was. Bounded so a long-lived host
|
|
765
|
+
* cannot accumulate session ids forever.
|
|
766
|
+
*/
|
|
767
|
+
const pruneFailureSessions = new Set<string>()
|
|
768
|
+
const PRUNE_FAILURE_SESSIONS_MAX = 256
|
|
769
|
+
|
|
770
|
+
function logPruneFailureOnce(sessionID: unknown, site: PruneSite, error: unknown): void {
|
|
771
|
+
const session = typeof sessionID === 'string' && sessionID !== '' ? sessionID : ''
|
|
772
|
+
const key = session !== '' ? session : `${site}:unknown`
|
|
773
|
+
if (pruneFailureSessions.has(key)) return
|
|
774
|
+
if (pruneFailureSessions.size >= PRUNE_FAILURE_SESSIONS_MAX) pruneFailureSessions.clear()
|
|
775
|
+
pruneFailureSessions.add(key)
|
|
776
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
777
|
+
appendV2HookLog(`[context-pruner] failed open site=${site} session=${key}: ${message}`)
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* A compaction payload whose `messages` is absent or misnamed is a shape drift,
|
|
782
|
+
* not a normal no-op: the feature is always-on at that site, so silence would
|
|
783
|
+
* hide the drift forever. Report `not-array`/`malformed` with the same
|
|
784
|
+
* once-per-session channel as a thrown failure. The `context` caller invokes
|
|
785
|
+
* this only when the feature is enabled.
|
|
786
|
+
*/
|
|
787
|
+
function logPruneShapeIssue(stats: PruneStats, sessionID: unknown, site: PruneSite): void {
|
|
788
|
+
if (stats.skipReason !== 'not-array' && stats.skipReason !== 'malformed') return
|
|
789
|
+
const detail =
|
|
790
|
+
stats.skipReason === 'not-array'
|
|
791
|
+
? 'not-array: payload.messages is not an array; input left unchanged'
|
|
792
|
+
: 'malformed: unexpected message shape; input left unchanged'
|
|
793
|
+
logPruneFailureOnce(sessionID, site, new Error(detail))
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* Config typos are otherwise invisible: `keepTurn: 7` resolves to the default 4
|
|
798
|
+
* and the operator believes it applied. Warn ONCE per process, name the
|
|
799
|
+
* ignored keys and the accepted keys, and keep the fail-open resolution.
|
|
800
|
+
*/
|
|
801
|
+
let contextPrunerConfigWarned = false
|
|
802
|
+
|
|
803
|
+
function warnContextPrunerConfigOnce(options: unknown): void {
|
|
804
|
+
if (contextPrunerConfigWarned) return
|
|
805
|
+
try {
|
|
806
|
+
const issues = describeContextPrunerConfigIssues(options)
|
|
807
|
+
if (issues.length === 0) return
|
|
808
|
+
contextPrunerConfigWarned = true
|
|
809
|
+
appendV2HookLog(
|
|
810
|
+
`[context-pruner] ignored invalid context_pruner config: ${issues.join('; ')}; ` +
|
|
811
|
+
`accepted keys: ${CONTEXT_PRUNER_CONFIG_KEYS.join(', ')}`,
|
|
812
|
+
)
|
|
813
|
+
} catch {
|
|
814
|
+
// A validator must never break setup; silence is the only safe fallback.
|
|
815
|
+
contextPrunerConfigWarned = true
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// ─── Ambient memory injection (opt-in, V2 context hook) ─────────────────
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* One payload per session, computed on the session's first request. Bounded by
|
|
823
|
+
* `MEMORY_CACHE_MAX_SESSIONS` inside the cache (FIFO), so a long-lived host
|
|
824
|
+
* cannot grow it without limit. The payload is built, rendered and logged by
|
|
825
|
+
* `memory-context.ts`; this module only supplies the hook wiring and the
|
|
826
|
+
* `hooks.log` channel.
|
|
827
|
+
*/
|
|
828
|
+
const memoryInjectionCache = new MemoryInjectionCache()
|
|
829
|
+
|
|
657
830
|
/**
|
|
658
831
|
* Register session hooks via V2 ctx.session.hook.
|
|
659
832
|
*
|
|
660
833
|
* The V2 session.hook API (when available) provides:
|
|
661
834
|
* ctx.session.hook("prompt", handler) — message admission
|
|
662
835
|
* ctx.session.hook("context", handler) — system context injection
|
|
836
|
+
* ctx.session.hook("compaction", handler) — registered in setup Phase 7
|
|
663
837
|
*
|
|
664
838
|
* Returns true if any hooks were registered.
|
|
665
839
|
*/
|
|
666
840
|
async function registerV2SessionHooks(context: PluginContext): Promise<boolean> {
|
|
841
|
+
// Config validity is independent of hook availability; warn before the early
|
|
842
|
+
// return so a typo is visible even on a host that registers no session hook.
|
|
843
|
+
warnContextPrunerConfigOnce(context.options)
|
|
844
|
+
warnInvalidMemoryInjectionConfig(context.options, appendV2HookLog)
|
|
667
845
|
const sessionCtx = hostDomains(context).session
|
|
668
846
|
|
|
669
847
|
if (!sessionCtx?.hook) {
|
|
670
848
|
return false
|
|
671
849
|
}
|
|
672
850
|
|
|
851
|
+
// Resolved once, mirroring `resolveV2SandboxConfig(context.options)`: the
|
|
852
|
+
// per-request context prune is opt-in because it invalidates the provider
|
|
853
|
+
// prompt cache and has no measured cost baseline. The compaction site below
|
|
854
|
+
// applies the rules unconditionally.
|
|
855
|
+
const prunerConfig = resolveContextPrunerConfig(context.options)
|
|
856
|
+
|
|
857
|
+
// Ambient memory injection is opt-in and default OFF: with `enabled: false`
|
|
858
|
+
// this hook adds nothing, so `system` stays byte-identical to the policy-only
|
|
859
|
+
// output. Resolved here (not per request) for the same reason as the pruner.
|
|
860
|
+
const memoryConfig = resolveMemoryInjectionConfig(context.options)
|
|
861
|
+
|
|
673
862
|
let registered = false
|
|
674
863
|
|
|
675
864
|
try {
|
|
@@ -692,15 +881,49 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
|
|
|
692
881
|
// string entries to `{ type: 'text', text }` parts and append the
|
|
693
882
|
// policy as a part. Junk entries are ignored; a non-array,
|
|
694
883
|
// non-string system is left untouched. Never throws (fail-open).
|
|
695
|
-
const ctx = event as
|
|
884
|
+
const ctx = event as
|
|
885
|
+
| { system?: unknown; messages?: unknown; sessionID?: unknown }
|
|
886
|
+
| null
|
|
887
|
+
| undefined
|
|
696
888
|
if (ctx == null) return
|
|
697
889
|
const normalized = normalizeSystemToParts(ctx.system)
|
|
698
|
-
if (normalized
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
890
|
+
if (normalized != null) {
|
|
891
|
+
// A bare string is replaced by its part array; an array is mutated in
|
|
892
|
+
// place (the host may read the original reference).
|
|
893
|
+
if (typeof ctx.system === 'string') ctx.system = normalized
|
|
894
|
+
if (!hasPolicyMarker(normalized)) {
|
|
895
|
+
normalized.push({ type: 'text', text: POLICY } satisfies SystemPart)
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
// Opt-in ambient memory injection: the top-K memories relevant to the
|
|
899
|
+
// session's first user message, computed once per session and re-added
|
|
900
|
+
// verbatim on later requests. Deliberately OUTSIDE the block above: with
|
|
901
|
+
// `enabled: true` and no usable `system` there is nowhere to push, and
|
|
902
|
+
// the module reports `skip=no-system` once per session instead of the
|
|
903
|
+
// feature going silently inert. Off by default, so this is the only
|
|
904
|
+
// thing `enabled: false` skips.
|
|
905
|
+
if (memoryConfig.enabled) {
|
|
906
|
+
applyMemoryInjection(
|
|
907
|
+
normalized ?? ctx.system,
|
|
908
|
+
ctx.messages,
|
|
909
|
+
ctx.sessionID,
|
|
910
|
+
memoryConfig,
|
|
911
|
+
memoryInjectionCache,
|
|
912
|
+
appendV2HookLog,
|
|
913
|
+
)
|
|
914
|
+
}
|
|
915
|
+
// Opt-in DCP: same engine as the compaction site, but per-request
|
|
916
|
+
// pruning invalidates the prompt cache, so it runs only when
|
|
917
|
+
// `context_pruner.enabled` is explicitly true. Disabled = the hook is
|
|
918
|
+
// byte-for-byte the previous behaviour.
|
|
919
|
+
if (prunerConfig.enabled) {
|
|
920
|
+
try {
|
|
921
|
+
const stats = pruneMessages(ctx.messages, prunerConfig, 'context')
|
|
922
|
+
logContextPrune(stats)
|
|
923
|
+
logPruneShapeIssue(stats, ctx.sessionID, 'context')
|
|
924
|
+
} catch (error) {
|
|
925
|
+
logPruneFailureOnce(ctx.sessionID, 'context', error)
|
|
926
|
+
}
|
|
704
927
|
}
|
|
705
928
|
} catch {
|
|
706
929
|
// Fail-open: never throw to the host.
|
|
@@ -712,12 +935,31 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
|
|
|
712
935
|
}
|
|
713
936
|
|
|
714
937
|
try {
|
|
715
|
-
// "prompt" hook —
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
938
|
+
// "prompt" hook — preserve attached image references and add model-visible
|
|
939
|
+
// instructions so Zeus can inspect visual context and pass it to the
|
|
940
|
+
// implementation specialist before editing.
|
|
941
|
+
await sessionCtx.hook('prompt', (event: unknown) => {
|
|
942
|
+
try {
|
|
943
|
+
// 2.0.29 host payload: `{ sessionID, messageID, prompt: { text,
|
|
944
|
+
// files, agents, skills }, metadata, delivery }`. The session id is
|
|
945
|
+
// top-level (verified against the host's `SessionPrompt.prepare`), so a
|
|
946
|
+
// data: attachment's panic-free moment also relays it to the MCP.
|
|
947
|
+
const admission = event as {
|
|
948
|
+
sessionID?: unknown
|
|
949
|
+
prompt?: { text?: unknown; files?: unknown }
|
|
950
|
+
} | null
|
|
951
|
+
const prompt = admission?.prompt
|
|
952
|
+
if (!prompt || typeof prompt.text !== 'string') return
|
|
953
|
+
if (prompt.text.includes('<!-- pantheon-v2-visual-context -->')) return
|
|
954
|
+
const sessionID =
|
|
955
|
+
typeof admission?.sessionID === 'string' && admission.sessionID.trim() !== ''
|
|
956
|
+
? admission.sessionID
|
|
957
|
+
: undefined
|
|
958
|
+
const visualContext = buildV2VisionPromptContext(prompt.files, prompt.text, sessionID)
|
|
959
|
+
if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
|
|
960
|
+
} catch {
|
|
961
|
+
// Fail-open: malformed/unsupported prompt shapes must not block input.
|
|
962
|
+
}
|
|
721
963
|
})
|
|
722
964
|
registered = true
|
|
723
965
|
} catch {
|
|
@@ -826,6 +1068,93 @@ function appendV2HookLog(line: string): boolean {
|
|
|
826
1068
|
}
|
|
827
1069
|
}
|
|
828
1070
|
|
|
1071
|
+
// ─── BENCH Hook Timing (beta-10 latency slice, Phase 0) ────────────────
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* BENCH INSTRUMENTATION — observation only, zero behavior change.
|
|
1075
|
+
*
|
|
1076
|
+
* The beta-10 latency slice measures the V2 tool hook chain. These helpers
|
|
1077
|
+
* record the start/end of `execute.before` and `execute.after` per tool call
|
|
1078
|
+
* and append one single-line `[bench]` entry per hook end to the EXISTING
|
|
1079
|
+
* hooks.log channel (same appendV2HookLog path as every other line: masked,
|
|
1080
|
+
* stamped, best-effort, never throwing). The lines are consumed by
|
|
1081
|
+
* bench/lib/hooklog.mjs.
|
|
1082
|
+
*
|
|
1083
|
+
* Deliberate properties:
|
|
1084
|
+
* - the log call happens in `finally`, so denied calls (read-only guard,
|
|
1085
|
+
* secret block) are timed too, and the denial still propagates unchanged
|
|
1086
|
+
* - the join key is the host callID (`event.id`); a TTL-bounded map prunes
|
|
1087
|
+
* stale entries so a background/never-after call cannot leak memory
|
|
1088
|
+
* - `since_before_ms=unavailable` when no before record exists — the bench
|
|
1089
|
+
* contract never lets "unavailable" be encoded as 0
|
|
1090
|
+
*/
|
|
1091
|
+
|
|
1092
|
+
/** Entries older than this are pruned (a task tool result may never fire after). */
|
|
1093
|
+
const BENCH_TIMING_TTL_MS = 5 * 60_000
|
|
1094
|
+
/** Hard cap — mirrors the V1 delegationStarts bound. */
|
|
1095
|
+
const BENCH_TIMING_MAX = 256
|
|
1096
|
+
|
|
1097
|
+
const benchTimings = new Map<string, number>()
|
|
1098
|
+
|
|
1099
|
+
function pruneBenchTimings(now: number): void {
|
|
1100
|
+
for (const [callID, startedAt] of benchTimings) {
|
|
1101
|
+
if (now - startedAt > BENCH_TIMING_TTL_MS) benchTimings.delete(callID)
|
|
1102
|
+
}
|
|
1103
|
+
while (benchTimings.size >= BENCH_TIMING_MAX) {
|
|
1104
|
+
let oldestID: string | null = null
|
|
1105
|
+
let oldestAt = Number.POSITIVE_INFINITY
|
|
1106
|
+
for (const [id, at] of benchTimings) {
|
|
1107
|
+
if (at < oldestAt) {
|
|
1108
|
+
oldestAt = at
|
|
1109
|
+
oldestID = id
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
if (oldestID === null) break
|
|
1113
|
+
benchTimings.delete(oldestID)
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/** Read `{tool, id}` off a V2 tool event without assuming its exact shape. */
|
|
1118
|
+
function benchEventIdentity(event: unknown): { tool: string; callID: string } {
|
|
1119
|
+
if (event === null || typeof event !== 'object') return { tool: '', callID: '' }
|
|
1120
|
+
const payload = event as { tool?: unknown; id?: unknown }
|
|
1121
|
+
return {
|
|
1122
|
+
tool: typeof payload.tool === 'string' ? payload.tool : '',
|
|
1123
|
+
callID: typeof payload.id === 'string' ? payload.id : '',
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/**
|
|
1128
|
+
* Append one `[bench]` timing line for a finished hook phase. Best-effort and
|
|
1129
|
+
* exception-free by construction (appendV2HookLog never throws).
|
|
1130
|
+
*/
|
|
1131
|
+
function logBenchHookTiming(phase: 'before' | 'after', event: unknown, startedAt: number): void {
|
|
1132
|
+
try {
|
|
1133
|
+
const { tool, callID } = benchEventIdentity(event)
|
|
1134
|
+
const endedAt = Date.now()
|
|
1135
|
+
if (phase === 'before') {
|
|
1136
|
+
if (callID !== '') {
|
|
1137
|
+
benchTimings.set(callID, startedAt)
|
|
1138
|
+
pruneBenchTimings(startedAt)
|
|
1139
|
+
}
|
|
1140
|
+
appendV2HookLog(
|
|
1141
|
+
`[bench] tool.execute.before end tool=${tool} callID=${callID} ` +
|
|
1142
|
+
`started_at=${new Date(startedAt).toISOString()} duration_ms=${endedAt - startedAt}`,
|
|
1143
|
+
)
|
|
1144
|
+
return
|
|
1145
|
+
}
|
|
1146
|
+
const beforeAt = callID !== '' ? benchTimings.get(callID) : undefined
|
|
1147
|
+
if (beforeAt !== undefined) benchTimings.delete(callID)
|
|
1148
|
+
const sinceBefore = beforeAt === undefined ? 'unavailable' : String(endedAt - beforeAt)
|
|
1149
|
+
appendV2HookLog(
|
|
1150
|
+
`[bench] tool.execute.after end tool=${tool} callID=${callID} ` +
|
|
1151
|
+
`duration_ms=${endedAt - startedAt} since_before_ms=${sinceBefore}`,
|
|
1152
|
+
)
|
|
1153
|
+
} catch {
|
|
1154
|
+
// Instrumentation must never affect the hook chain.
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
|
|
829
1158
|
// ─── V2 Secret-Scan Verdict ─────────────────────────────────────────────
|
|
830
1159
|
|
|
831
1160
|
/**
|
|
@@ -941,6 +1270,7 @@ export function setV2SecretScanRunnerForTests(runner: SecretScanRunner | null):
|
|
|
941
1270
|
interface V2ToolExecuteBeforeEvent {
|
|
942
1271
|
tool?: unknown
|
|
943
1272
|
sessionID?: unknown
|
|
1273
|
+
messageID?: unknown
|
|
944
1274
|
agent?: unknown
|
|
945
1275
|
id?: unknown
|
|
946
1276
|
input?: unknown
|
|
@@ -1037,14 +1367,19 @@ function adaptV2ExecuteBeforeEvent(event: unknown): {
|
|
|
1037
1367
|
*
|
|
1038
1368
|
* Returns true if any hooks were registered.
|
|
1039
1369
|
*/
|
|
1040
|
-
async function registerV2ToolHooks(
|
|
1370
|
+
async function registerV2ToolHooks(
|
|
1371
|
+
context: PluginContext,
|
|
1372
|
+
subagentOrigins: V2SubagentOriginRegistry,
|
|
1373
|
+
boundedReadOrigins?: V2BoundedReadOriginRegistry,
|
|
1374
|
+
): Promise<{ registered: boolean; beforeRegistered: boolean }> {
|
|
1041
1375
|
const toolCtx = hostDomains(context).tool
|
|
1042
1376
|
|
|
1043
1377
|
if (!toolCtx?.hook) {
|
|
1044
|
-
return false
|
|
1378
|
+
return { registered: false, beforeRegistered: false }
|
|
1045
1379
|
}
|
|
1046
1380
|
|
|
1047
1381
|
let registered = false
|
|
1382
|
+
let beforeRegistered = false
|
|
1048
1383
|
|
|
1049
1384
|
try {
|
|
1050
1385
|
// "execute.before" — read-only enforcement. Throwing from this handler
|
|
@@ -1058,65 +1393,89 @@ async function registerV2ToolHooks(context: PluginContext): Promise<boolean> {
|
|
|
1058
1393
|
// here; without it the tools registered by registerV2Tools would be a live
|
|
1059
1394
|
// write path in every session, including read-only ones.
|
|
1060
1395
|
await toolCtx.hook('execute.before', async (event: unknown) => {
|
|
1396
|
+
const benchStartedAt = Date.now()
|
|
1061
1397
|
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
1398
|
try {
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1399
|
+
// V2's equivalent of V1's `chat.params` trigger: the host puts the active
|
|
1400
|
+
// agent on the event itself, so registering here needs no separate hook
|
|
1401
|
+
// and no session→agent map. A non-read-only (or absent) agent revokes the
|
|
1402
|
+
// registration, which also covers an in-session agent switch.
|
|
1403
|
+
syncReadOnlySession(readOnlyRegistry, input.sessionID, agent)
|
|
1404
|
+
// Deliberately OUTSIDE the try/catch below: a read-only denial must keep
|
|
1405
|
+
// propagating to the host, not be swallowed as a scanner failure.
|
|
1406
|
+
await v2EnforcementGuard(input, output)
|
|
1407
|
+
|
|
1408
|
+
// High-confidence secret scan (scripts/hooks/scan-secrets.sh). This is the
|
|
1409
|
+
// ONLY hard block on the V2 surface, and it exists here — rather than via
|
|
1410
|
+
// `src/plugins/pantheon-hooks.ts` — because that module is a separate
|
|
1411
|
+
// plugin that is never loaded on a V2-only install: opencode.json
|
|
1412
|
+
// `plugins` declares only `src/plugin-v2`. V1's scan-secrets block was
|
|
1413
|
+
// therefore inert by construction, not by misconfiguration.
|
|
1414
|
+
//
|
|
1415
|
+
// exit 0 → allow. exit 1 with a valid scanner report → advisory, logged
|
|
1416
|
+
// only. exit 2 (high-confidence match) → deny. A scanner that does NOT
|
|
1417
|
+
// produce a trustworthy verdict — missing/unexecutable script, timeout,
|
|
1418
|
+
// killed child, spawn/serialization failure, malformed or unexpected
|
|
1419
|
+
// output — is fail-CLOSED: this pending tool call is denied, the session
|
|
1420
|
+
// is not. (runHook resolves a structured result instead of rejecting, so
|
|
1421
|
+
// the exit-code-only reading below cannot lean on an exception.)
|
|
1422
|
+
let blockError: Error | null = null
|
|
1423
|
+
try {
|
|
1424
|
+
const payload: HookPayload = {
|
|
1425
|
+
tool_name: input.tool,
|
|
1426
|
+
tool_input: output.args ?? {},
|
|
1427
|
+
agent_id: typeof agent === 'string' ? agent : '',
|
|
1428
|
+
session_id: input.sessionID,
|
|
1429
|
+
}
|
|
1430
|
+
const scan = await secretScanRunner(payload)
|
|
1431
|
+
const decision = evaluateSecretScanResult(scan)
|
|
1432
|
+
if (decision.action === 'block') {
|
|
1433
|
+
appendV2HookLog(SECRET_BLOCK_MESSAGE)
|
|
1434
|
+
appendV2HookLog(scan.stderr)
|
|
1435
|
+
blockError = new Error(SECRET_BLOCK_MESSAGE)
|
|
1436
|
+
} else if (decision.action === 'advisory') {
|
|
1437
|
+
// Advisory: log only, never block.
|
|
1438
|
+
appendV2HookLog(scan.stderr)
|
|
1439
|
+
} else if (decision.action === 'fail-closed') {
|
|
1440
|
+
// Sanitized failure category only — never the scanner's raw stderr,
|
|
1441
|
+
// which on a failure path is unverified and may carry the very
|
|
1442
|
+
// payload the scan exists to keep out of logs.
|
|
1443
|
+
appendV2HookLog(`${SECRET_SCAN_UNAVAILABLE_MESSAGE} (${decision.reason})`)
|
|
1444
|
+
blockError = new Error(SECRET_SCAN_UNAVAILABLE_MESSAGE)
|
|
1445
|
+
}
|
|
1446
|
+
} catch {
|
|
1447
|
+
// The runner is contracted to resolve a structured result, so this only
|
|
1448
|
+
// guards an unexpected throw (including a future change to the runner).
|
|
1449
|
+
// A scanner that cannot run is fail-CLOSED: deny this call rather than
|
|
1450
|
+
// let it through with no scan at all.
|
|
1451
|
+
appendV2HookLog(SECRET_SCAN_UNAVAILABLE_MESSAGE)
|
|
1107
1452
|
blockError = new Error(SECRET_SCAN_UNAVAILABLE_MESSAGE)
|
|
1108
1453
|
}
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1454
|
+
if (blockError !== null) throw blockError
|
|
1455
|
+
const boundedReadOrigin = boundedReadOrigins?.capture(event)
|
|
1456
|
+
const eventTool = (event as V2ToolExecuteBeforeEvent | null)?.tool
|
|
1457
|
+
if (eventTool === BOUNDED_READ_TOOL && boundedReadOrigin === undefined) {
|
|
1458
|
+
throw new Error('BOUND_READ_UNAUTHORIZED')
|
|
1459
|
+
}
|
|
1460
|
+
if (boundedReadOrigin !== undefined) {
|
|
1461
|
+
writeV2AdmissionProof('tool.execute.before bounded-read', {
|
|
1462
|
+
sessionID: boundedReadOrigin.sessionID,
|
|
1463
|
+
messageID: boundedReadOrigin.messageID,
|
|
1464
|
+
callID: boundedReadOrigin.callID,
|
|
1465
|
+
agent: boundedReadOrigin.agent,
|
|
1466
|
+
})
|
|
1467
|
+
}
|
|
1468
|
+
const origin = subagentOrigins.capture(event)
|
|
1469
|
+
if (origin !== undefined) {
|
|
1470
|
+
writeV2AdmissionProof('tool.execute.before', { ...origin })
|
|
1471
|
+
}
|
|
1472
|
+
} finally {
|
|
1473
|
+
// BENCH instrumentation — observation only; runs on the deny paths too.
|
|
1474
|
+
logBenchHookTiming('before', event, benchStartedAt)
|
|
1116
1475
|
}
|
|
1117
|
-
if (blockError !== null) throw blockError
|
|
1118
1476
|
})
|
|
1119
1477
|
registered = true
|
|
1478
|
+
beforeRegistered = true
|
|
1120
1479
|
} catch {
|
|
1121
1480
|
// Tool before-hook not supported
|
|
1122
1481
|
}
|
|
@@ -1134,13 +1493,24 @@ async function registerV2ToolHooks(context: PluginContext): Promise<boolean> {
|
|
|
1134
1493
|
const v2ExecuteAfter = createV2ExecuteAfter({
|
|
1135
1494
|
sandbox: resolveV2SandboxConfig(context.options),
|
|
1136
1495
|
})
|
|
1137
|
-
await toolCtx.hook('execute.after', (event: unknown) =>
|
|
1496
|
+
await toolCtx.hook('execute.after', async (event: unknown) => {
|
|
1497
|
+
const benchStartedAt = Date.now()
|
|
1498
|
+
try {
|
|
1499
|
+
subagentOrigins.forget(event)
|
|
1500
|
+
boundedReadOrigins?.forget(event)
|
|
1501
|
+
await v2ExecuteAfter(event)
|
|
1502
|
+
} finally {
|
|
1503
|
+
// BENCH instrumentation — observation only; the awaited call means the
|
|
1504
|
+
// duration covers the whole parity chain, not just its dispatch.
|
|
1505
|
+
logBenchHookTiming('after', event, benchStartedAt)
|
|
1506
|
+
}
|
|
1507
|
+
})
|
|
1138
1508
|
registered = true
|
|
1139
1509
|
} catch {
|
|
1140
1510
|
// Tool after-hook not supported
|
|
1141
1511
|
}
|
|
1142
1512
|
|
|
1143
|
-
return registered
|
|
1513
|
+
return { registered, beforeRegistered }
|
|
1144
1514
|
}
|
|
1145
1515
|
|
|
1146
1516
|
// ─── V2 Permission Hook ─────────────────────────────────────────────────
|
|
@@ -1155,7 +1525,10 @@ async function registerV2ToolHooks(context: PluginContext): Promise<boolean> {
|
|
|
1155
1525
|
*
|
|
1156
1526
|
* Returns true if the hook was registered.
|
|
1157
1527
|
*/
|
|
1158
|
-
async function registerV2PermissionHook(
|
|
1528
|
+
async function registerV2PermissionHook(
|
|
1529
|
+
context: PluginContext,
|
|
1530
|
+
subagentOrigins: V2SubagentOriginRegistry,
|
|
1531
|
+
): Promise<boolean> {
|
|
1159
1532
|
const domains = hostDomains(context)
|
|
1160
1533
|
const permCtx = domains.permission
|
|
1161
1534
|
|
|
@@ -1168,6 +1541,9 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1168
1541
|
await permCtx.hook('evaluate', async (rawEvent: unknown) => {
|
|
1169
1542
|
const event = rawEvent as V2PermissionEvent | null
|
|
1170
1543
|
const effectBefore = event?.effect
|
|
1544
|
+
let origin: ReturnType<V2SubagentOriginRegistry['consume']>
|
|
1545
|
+
let decision: string | null = null
|
|
1546
|
+
let callerSessionParentID: unknown
|
|
1171
1547
|
const writeProof = (): void => {
|
|
1172
1548
|
const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF
|
|
1173
1549
|
if (!proofPath || !event || !Array.isArray(event.resources)) return
|
|
@@ -1175,13 +1551,18 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1175
1551
|
appendFileSync(
|
|
1176
1552
|
proofPath,
|
|
1177
1553
|
`permission.evaluate ${JSON.stringify({
|
|
1554
|
+
action: event.action,
|
|
1178
1555
|
resources: event.resources,
|
|
1179
1556
|
agent: event.agent,
|
|
1180
1557
|
sessionID: event.sessionID,
|
|
1558
|
+
callerSessionParentID: callerSessionParentID ?? null,
|
|
1559
|
+
source: event.source,
|
|
1560
|
+
matchedOrigin: origin ?? null,
|
|
1561
|
+
decision,
|
|
1181
1562
|
effect: event.effect,
|
|
1182
1563
|
message: event.message,
|
|
1183
|
-
eventFields: ['resources', 'agent', 'sessionID', 'effect'].filter(
|
|
1184
|
-
Object.hasOwn(event, key),
|
|
1564
|
+
eventFields: ['action', 'resources', 'agent', 'sessionID', 'source', 'effect'].filter(
|
|
1565
|
+
(key) => Object.hasOwn(event, key),
|
|
1185
1566
|
),
|
|
1186
1567
|
effectBefore: effectBefore ?? null,
|
|
1187
1568
|
effectAfter: event.effect ?? null,
|
|
@@ -1227,6 +1608,11 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1227
1608
|
const hasPantheonTarget = targets.some((target) => PANTHEON_AGENTS.has(target ?? ''))
|
|
1228
1609
|
let session: AuthoritativeSession | undefined
|
|
1229
1610
|
if (hasPantheonTarget) {
|
|
1611
|
+
origin = subagentOrigins.consume(event)
|
|
1612
|
+
if (origin === undefined) {
|
|
1613
|
+
deny('matching host subagent tool origin is missing or stale')
|
|
1614
|
+
return
|
|
1615
|
+
}
|
|
1230
1616
|
const sessionID = typeof event.sessionID === 'string' ? event.sessionID.trim() : ''
|
|
1231
1617
|
if (!sessionID) {
|
|
1232
1618
|
deny('caller session ID is missing')
|
|
@@ -1255,11 +1641,12 @@ async function registerV2PermissionHook(context: PluginContext): Promise<boolean
|
|
|
1255
1641
|
return
|
|
1256
1642
|
}
|
|
1257
1643
|
session = retrieved as AuthoritativeSession
|
|
1644
|
+
callerSessionParentID = session.parentID
|
|
1258
1645
|
}
|
|
1259
1646
|
|
|
1260
1647
|
// Native-only resources remain under host policy. If a Pantheon target
|
|
1261
1648
|
// appears anywhere, the shared policy evaluates the complete resource set.
|
|
1262
|
-
|
|
1649
|
+
decision = evaluateV2Delegation(event, session, event.effect, origin)
|
|
1263
1650
|
if (decision === 'deny') deny('caller or target is not allowed by delegation policy')
|
|
1264
1651
|
else writeProof()
|
|
1265
1652
|
})
|
|
@@ -1302,6 +1689,83 @@ export type { V2ToolDef, V2ToolResult } from './pantheon/v2-tools.ts'
|
|
|
1302
1689
|
interface V2SessionEvent {
|
|
1303
1690
|
type: string
|
|
1304
1691
|
properties?: Record<string, unknown>
|
|
1692
|
+
data?: unknown
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
/** Opt-in trace used by the isolated F4A canary; never logs prompts or inputs. */
|
|
1696
|
+
function writeV2AdmissionProof(label: string, detail: Record<string, unknown>): void {
|
|
1697
|
+
const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF
|
|
1698
|
+
if (!proofPath) return
|
|
1699
|
+
try {
|
|
1700
|
+
appendFileSync(proofPath, `${label} ${JSON.stringify(detail)}\n`)
|
|
1701
|
+
} catch {
|
|
1702
|
+
// Proof is best-effort and must not affect admission behavior.
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
async function prepareV2BoundedRead(
|
|
1707
|
+
context: PluginContext,
|
|
1708
|
+
): Promise<ReturnType<typeof createV2BoundedReadTool> | undefined> {
|
|
1709
|
+
const host = hostDomains(context)
|
|
1710
|
+
const directory = host.location?.directory
|
|
1711
|
+
const projectID = host.location?.project?.id
|
|
1712
|
+
const session = host.session
|
|
1713
|
+
const permission = host.permission
|
|
1714
|
+
if (
|
|
1715
|
+
typeof directory !== 'string' ||
|
|
1716
|
+
directory.trim() === '' ||
|
|
1717
|
+
typeof projectID !== 'string' ||
|
|
1718
|
+
projectID.trim() === '' ||
|
|
1719
|
+
typeof session?.get !== 'function' ||
|
|
1720
|
+
typeof permission?.assert !== 'function' ||
|
|
1721
|
+
typeof host.event?.subscribe !== 'function' ||
|
|
1722
|
+
typeof host.tool?.transform !== 'function' ||
|
|
1723
|
+
typeof host.tool?.hook !== 'function'
|
|
1724
|
+
) {
|
|
1725
|
+
markUnsupported('bounded-read')
|
|
1726
|
+
return undefined
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
const rootDirectory = await realpathAsync(directory).catch(() => undefined)
|
|
1730
|
+
if (rootDirectory === undefined) {
|
|
1731
|
+
markUnsupported('bounded-read')
|
|
1732
|
+
return undefined
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
return createV2BoundedReadTool({
|
|
1736
|
+
rootDirectory,
|
|
1737
|
+
projectID,
|
|
1738
|
+
getSession: (sessionID) => {
|
|
1739
|
+
if (typeof session.get !== 'function') throw new Error('session lookup unavailable')
|
|
1740
|
+
return session.get.call(session, { sessionID })
|
|
1741
|
+
},
|
|
1742
|
+
assertPermission: (request) => {
|
|
1743
|
+
if (typeof permission.assert !== 'function') throw new Error('permission API unavailable')
|
|
1744
|
+
return permission.assert.call(permission, request)
|
|
1745
|
+
},
|
|
1746
|
+
scanContent: async ({ content, agent, sessionID, callID }) => {
|
|
1747
|
+
try {
|
|
1748
|
+
const scan = await secretScanRunner({
|
|
1749
|
+
tool_name: BOUNDED_READ_TOOL,
|
|
1750
|
+
tool_input: { content },
|
|
1751
|
+
agent_id: agent,
|
|
1752
|
+
session_id: sessionID,
|
|
1753
|
+
})
|
|
1754
|
+
const decision = evaluateSecretScanResult(scan)
|
|
1755
|
+
if (decision.action === 'allow') return 'allow'
|
|
1756
|
+
const reason = decision.action === 'fail-closed' ? decision.reason : 'content-match'
|
|
1757
|
+
appendV2HookLog(
|
|
1758
|
+
`[SECRET SCAN] bounded read withheld session=${sessionID} callID=${callID} reason=${reason}`,
|
|
1759
|
+
)
|
|
1760
|
+
return decision.action === 'fail-closed' ? 'unavailable' : 'deny'
|
|
1761
|
+
} catch {
|
|
1762
|
+
appendV2HookLog(
|
|
1763
|
+
`[SECRET SCAN] bounded read withheld session=${sessionID} callID=${callID} reason=scanner-failure`,
|
|
1764
|
+
)
|
|
1765
|
+
return 'unavailable'
|
|
1766
|
+
}
|
|
1767
|
+
},
|
|
1768
|
+
})
|
|
1305
1769
|
}
|
|
1306
1770
|
|
|
1307
1771
|
/** Cleanup function type. */
|
|
@@ -1326,7 +1790,7 @@ export const plugin = define({
|
|
|
1326
1790
|
// is registered here — that is a Pantheon scope choice, not a host gap.
|
|
1327
1791
|
// ctx.catalog is the one domain the host does not provide.
|
|
1328
1792
|
// Phase 1 registers against the SDK-typed `context.agent` / `.command` /
|
|
1329
|
-
// `.reference` directly; the
|
|
1793
|
+
// `.reference` directly; the host domains the SDK omits are reached only
|
|
1330
1794
|
// through `hostDomains` (see the module header).
|
|
1331
1795
|
const phase1Transforms: Array<{ feature: string; register: () => Promise<unknown> }> = [
|
|
1332
1796
|
{ feature: 'agent-transform', register: () => context.agent.transform(transformAgents) },
|
|
@@ -1350,34 +1814,46 @@ export const plugin = define({
|
|
|
1350
1814
|
}
|
|
1351
1815
|
})
|
|
1352
1816
|
|
|
1353
|
-
|
|
1354
|
-
const
|
|
1355
|
-
if (
|
|
1356
|
-
markUnsupported('tool-transform')
|
|
1357
|
-
}
|
|
1817
|
+
const subagentOrigins = new V2SubagentOriginRegistry()
|
|
1818
|
+
const boundedRead = await prepareV2BoundedRead(context).catch(() => undefined)
|
|
1819
|
+
if (boundedRead === undefined) markUnsupported('bounded-read')
|
|
1358
1820
|
|
|
1359
|
-
// ─── Phase
|
|
1360
|
-
const eventCleanup = subscribeV2Events(context)
|
|
1821
|
+
// ─── Phase 2: V2 Event Subscription (best-effort) ────────────────
|
|
1822
|
+
const eventCleanup = subscribeV2Events(context, boundedRead?.clearSession)
|
|
1361
1823
|
if (eventCleanup) {
|
|
1362
1824
|
activeCleanups.push(eventCleanup)
|
|
1363
1825
|
} else {
|
|
1364
1826
|
markUnsupported('event-stream')
|
|
1365
1827
|
}
|
|
1366
1828
|
|
|
1367
|
-
// ─── Phase
|
|
1829
|
+
// ─── Phase 3: V2 Session Hooks (best-effort) ─────────────────────
|
|
1368
1830
|
const sessionHooksRegistered = await registerV2SessionHooks(context).catch(() => false)
|
|
1369
1831
|
if (!sessionHooksRegistered) {
|
|
1370
1832
|
markUnsupported('session-hooks')
|
|
1371
1833
|
}
|
|
1372
1834
|
|
|
1373
|
-
// ─── Phase
|
|
1374
|
-
const
|
|
1375
|
-
|
|
1835
|
+
// ─── Phase 4: V2 Tool Hooks (best-effort) ────────────────────────
|
|
1836
|
+
const toolHookResult = await registerV2ToolHooks(
|
|
1837
|
+
context,
|
|
1838
|
+
subagentOrigins,
|
|
1839
|
+
boundedRead?.origins,
|
|
1840
|
+
).catch(() => ({ registered: false, beforeRegistered: false }))
|
|
1841
|
+
if (!toolHookResult.registered) {
|
|
1376
1842
|
markUnsupported('tool-execute-hooks')
|
|
1377
1843
|
}
|
|
1378
1844
|
|
|
1845
|
+
// ─── Phase 5: V2 Tool Registration (best-effort) ─────────────────
|
|
1846
|
+
const boundedReadDefinition = toolHookResult.beforeRegistered
|
|
1847
|
+
? boundedRead?.definition
|
|
1848
|
+
: undefined
|
|
1849
|
+
if (boundedRead !== undefined && boundedReadDefinition === undefined) {
|
|
1850
|
+
markUnsupported('bounded-read')
|
|
1851
|
+
}
|
|
1852
|
+
const toolsRegistered = await registerV2Tools(context, boundedReadDefinition).catch(() => false)
|
|
1853
|
+
if (!toolsRegistered) markUnsupported('tool-transform')
|
|
1854
|
+
|
|
1379
1855
|
// ─── Phase 6: V2 Permission Hook (best-effort) ───────────────────
|
|
1380
|
-
await registerV2PermissionHook(context).catch(() => false)
|
|
1856
|
+
await registerV2PermissionHook(context, subagentOrigins).catch(() => false)
|
|
1381
1857
|
|
|
1382
1858
|
// ─── Phase 7: V2 Compaction Hook (best-effort) ───────────────────
|
|
1383
1859
|
const compactionCtx = hostDomains(context).session
|
|
@@ -1388,28 +1864,44 @@ export const plugin = define({
|
|
|
1388
1864
|
// `compacting` is not a valid key: the registry accepts any string and
|
|
1389
1865
|
// silently drops unknown names, so the old name was a permanent no-op.
|
|
1390
1866
|
// 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.
|
|
1867
|
+
await compactionCtx.hook('compaction', (event: unknown) => {
|
|
1868
|
+
try {
|
|
1869
|
+
// Opt-in lifetime proof for the host-backed hook canary
|
|
1870
|
+
// (tests/pantheon/plugin-v2-hook-canary.test.mjs, MODE=real). It is
|
|
1871
|
+
// inert unless PANTHEON_HOOK_CANARY_LIFETIME_PROOF is set, so
|
|
1872
|
+
// production behaviour is unchanged. This exists because a rename to
|
|
1873
|
+
// `compacting` was a silent no-op for an unknown length of time: the
|
|
1874
|
+
// canary can now observe that THIS registration fired.
|
|
1875
|
+
if (process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF) {
|
|
1876
|
+
try {
|
|
1877
|
+
appendFileSync(
|
|
1878
|
+
process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF,
|
|
1879
|
+
'plugin-v2:session.hook:compaction\n',
|
|
1880
|
+
)
|
|
1881
|
+
} catch {
|
|
1882
|
+
// Proof is best-effort: never let instrumentation break the host.
|
|
1883
|
+
}
|
|
1412
1884
|
}
|
|
1885
|
+
|
|
1886
|
+
// DCP dynamic context pruning (V2 only). This hook receives the
|
|
1887
|
+
// provider-bound array exactly before the summarization request,
|
|
1888
|
+
// and mutations are honored per request — the persisted session is
|
|
1889
|
+
// untouched. Apply the rules by default: it only changes what feeds
|
|
1890
|
+
// the summary. Never set `input.result`: the model must summarize
|
|
1891
|
+
// the pruned history, not be replaced by a canned summary.
|
|
1892
|
+
const payload = event as { sessionID?: unknown; messages?: unknown } | null | undefined
|
|
1893
|
+
const prunerConfig = resolveContextPrunerConfig(context.options)
|
|
1894
|
+
const stats = pruneMessages(payload?.messages, prunerConfig, 'compaction')
|
|
1895
|
+
logContextPrune(stats)
|
|
1896
|
+
logPruneShapeIssue(stats, payload?.sessionID, 'compaction')
|
|
1897
|
+
} catch (error) {
|
|
1898
|
+
// Fail-open: any unexpected shape or engine failure must not kill
|
|
1899
|
+
// the compaction request. One diagnostic line per session maximum.
|
|
1900
|
+
logPruneFailureOnce(
|
|
1901
|
+
(event as { sessionID?: unknown } | null)?.sessionID,
|
|
1902
|
+
'compaction',
|
|
1903
|
+
error,
|
|
1904
|
+
)
|
|
1413
1905
|
}
|
|
1414
1906
|
})
|
|
1415
1907
|
} catch {
|