pantheon-opencode 1.6.0 → 1.6.2-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +45 -0
  4. package/README.md +122 -6
  5. package/README.pt-BR.md +14 -9
  6. package/bin/pantheon-init.mjs +255 -39
  7. package/package.json +8 -6
  8. package/plugin.json +1 -1
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +1 -1
  11. package/scripts/doctor.mjs +231 -46
  12. package/scripts/install/agents-md.mjs +2 -1
  13. package/scripts/install/config-migration.mjs +344 -393
  14. package/scripts/install/config-paths.mjs +15 -0
  15. package/scripts/install/interactive.mjs +30 -9
  16. package/scripts/install/interrupt.mjs +78 -0
  17. package/scripts/install/mcp-permissions.mjs +164 -0
  18. package/scripts/install/opencode-state.mjs +91 -0
  19. package/scripts/install/opencode-version.mjs +31 -13
  20. package/scripts/install/opencode-wildcard.mjs +106 -0
  21. package/scripts/install/opencode.mjs +508 -108
  22. package/scripts/install/plan-artifact.mjs +12 -1
  23. package/scripts/install/plugin.mjs +17 -1
  24. package/scripts/install/run-record.mjs +115 -0
  25. package/scripts/install/strings.mjs +35 -6
  26. package/scripts/install/v2-capabilities.mjs +204 -0
  27. package/scripts/package-evidence.mjs +1 -0
  28. package/scripts/release-gates.mjs +7 -2
  29. package/scripts/sandbox-env.sh +174 -0
  30. package/scripts/setup-v2-config.mjs +1703 -0
  31. package/scripts/setup.mjs +415 -0
  32. package/scripts/sync-tui.mjs +9 -1
  33. package/scripts/test-opencode-v2-sandbox.sh +438 -151
  34. package/scripts/update-skills-lock.mjs +30 -0
  35. package/skills-lock.json +10 -10
  36. package/src/agents/aphrodite.md +5 -2
  37. package/src/agents/apollo.md +5 -0
  38. package/src/agents/athena.md +6 -1
  39. package/src/agents/demeter.md +5 -1
  40. package/src/agents/gaia.md +4 -0
  41. package/src/agents/hephaestus.md +6 -1
  42. package/src/agents/hermes.md +6 -3
  43. package/src/agents/iris.md +5 -1
  44. package/src/agents/mnemosyne.md +20 -50
  45. package/src/agents/nyx.md +5 -1
  46. package/src/agents/prometheus.md +4 -0
  47. package/src/agents/talos.md +4 -0
  48. package/src/agents/themis.md +4 -0
  49. package/src/agents/zeus.md +9 -3
  50. package/src/instructions/agent-return-format.instructions.md +1 -1
  51. package/src/instructions/memory-protocol.instructions.md +3 -3
  52. package/src/instructions/test-economy.instructions.md +6 -6
  53. package/src/mcp/pantheon_vision.py +37 -36
  54. package/src/mcp/requirements-mcp.txt +1 -1
  55. package/src/mcp/requirements-vision.txt +1 -1
  56. package/src/pantheon/cost-command.ts +127 -40
  57. package/src/pantheon/delegation-enforce.ts +160 -23
  58. package/src/pantheon/guard-path.ts +162 -0
  59. package/src/pantheon/v2-bounded-read.ts +15 -1
  60. package/src/pantheon/v2-bridge.ts +27 -0
  61. package/src/pantheon/v2-shell-hooks.ts +260 -0
  62. package/src/pantheon/v2-unsupported.mjs +32 -4
  63. package/src/pantheon/v2-vision.ts +34 -29
  64. package/src/pantheon/vision.ts +49 -11
  65. package/src/plugin-v2.ts +413 -60
  66. package/src/plugin.ts +22 -2
  67. package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
  68. package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
  69. package/src/plugins/tui/dist/quota-adapters.js +1142 -0
  70. package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
  71. package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
  72. package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
  73. package/src/plugins/tui/dist/quota-cli.js +184 -0
  74. package/src/plugins/tui/dist/quota-cli.js.map +1 -0
  75. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +390 -0
  76. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +1 -0
  77. package/src/plugins/tui/dist/server-v2.d.ts +14 -0
  78. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  79. package/src/plugins/tui/dist/server-v2.js +673 -0
  80. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  81. package/src/plugins/tui/dist/tui-v2.d.ts +247 -52
  82. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  83. package/src/plugins/tui/dist/tui-v2.js +2492 -529
  84. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  85. package/src/plugins/tui/dist/tui.js +1 -1
  86. package/src/plugins/tui/index-v2.ts +3 -6
  87. package/src/plugins/tui/package-lock.json +11 -11
  88. package/src/plugins/tui/package.json +6 -4
  89. package/src/plugins/tui/src/context-gauge.ts +59 -0
  90. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
  91. package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
  92. package/src/plugins/tui/src/index-v2.tsx +199 -240
  93. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  94. package/src/plugins/tui/src/quota-adapters.ts +1598 -0
  95. package/src/plugins/tui/src/quota-cli.ts +237 -0
  96. package/src/plugins/tui/src/quota-rpc.ts +209 -0
  97. package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
  98. package/src/plugins/tui/src/quota-v2.tsx +986 -0
  99. package/src/plugins/tui/src/server-v2.ts +841 -0
  100. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  101. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  102. package/src/plugins/tui/tsdown.config.ts +8 -1
  103. package/src/routing.yml +72 -13
  104. package/src/skills/README.md +4 -0
  105. package/src/skills/agent-coordination/SKILL.md +0 -3
  106. package/src/skills/artifact-management/SKILL.md +0 -3
  107. package/src/skills/auto-continue/SKILL.md +0 -3
  108. package/src/skills/code-review-checklist/SKILL.md +0 -3
  109. package/src/skills/context-compression/SKILL.md +0 -3
  110. package/src/skills/memory-bank/SKILL.md +6 -28
  111. package/src/skills/session-goal/SKILL.md +0 -3
  112. package/src/skills/simplify/SKILL.md +5 -4
  113. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  114. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  115. package/src/pantheon/memory-context.ts +0 -1017
package/src/plugin-v2.ts CHANGED
@@ -88,6 +88,7 @@ import type {
88
88
  ReferenceDraft,
89
89
  } from '@opencode-ai/plugin/v2/promise'
90
90
  import { define } from '@opencode-ai/plugin/v2/promise'
91
+ import { buildCompactionContext } from './pantheon/compaction-context.ts'
91
92
  import {
92
93
  CONTEXT_PRUNER_CONFIG_KEYS,
93
94
  describeContextPrunerConfigIssues,
@@ -98,25 +99,37 @@ import {
98
99
  } from './pantheon/context-pruner.ts'
99
100
  import {
100
101
  createEnforcementGuard,
102
+ normalizeDelegationAgent,
101
103
  readOnlyRegistry,
102
104
  syncReadOnlySession,
103
105
  type ToolExecuteBeforeInput,
104
106
  type ToolExecuteBeforeOutput,
107
+ zeusReadGuard,
105
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 { getSharedBoard } from './pantheon/shared-board.ts'
106
112
  import {
107
- applyMemoryInjection,
108
- MemoryInjectionCache,
109
- resolveMemoryInjectionConfig,
110
- warnInvalidMemoryInjectionConfig,
111
- } from './pantheon/memory-context.ts'
113
+ TODO_ENFORCER_DEFAULTS,
114
+ TodoEnforcer,
115
+ type TodoEnforcerChild,
116
+ type TodoEnforcerClient,
117
+ type TodoEnforcerMessage,
118
+ type TodoLike,
119
+ todoEnforcerEnabledFromEnv,
120
+ } from './pantheon/todo-enforcer.ts'
112
121
  import {
113
122
  BOUNDED_READ_TOOL,
114
123
  createV2BoundedReadTool,
115
124
  type V2BoundedReadOriginRegistry,
116
125
  } from './pantheon/v2-bounded-read.ts'
117
126
  import {
127
+ createV2Bridge,
128
+ getRegisteredV2Bridge,
118
129
  getV2BridgeFromContext,
130
+ injectBridge,
119
131
  type PantheonV2Bridge,
132
+ registerV2Bridge,
120
133
  type V2ContextLike,
121
134
  } from './pantheon/v2-bridge.ts'
122
135
  import {
@@ -129,9 +142,11 @@ import {
129
142
  } from './pantheon/v2-delegation-enforce.ts'
130
143
  import { createV2ExecuteAfter, resolveV2SandboxConfig } from './pantheon/v2-execute-after.ts'
131
144
  import { applyV2ModelOverrides, readV2ModelConfiguration } from './pantheon/v2-model-overrides.ts'
145
+ import { createV2ShellHooks, type V2ShellRunner } from './pantheon/v2-shell-hooks.ts'
132
146
  import { createV2ToolDefinitions, type V2ToolResult } from './pantheon/v2-tools.ts'
133
147
  import { V2_UNSUPPORTED_FEATURE_SEED } from './pantheon/v2-unsupported.mjs'
134
148
  import { buildV2VisionPromptContext, type V2VisionRuntime } from './pantheon/v2-vision.ts'
149
+ import { sanitizeVisionHistory } from './pantheon/vision.ts'
135
150
  import { type HookPayload, type HookResult, runHook } from './plugins/hook-runner.ts'
136
151
 
137
152
  // ─── Unsupported Features Registry ───────────────────────────────────────
@@ -226,6 +241,35 @@ function normalizeSystemToParts(system: unknown): unknown[] | null {
226
241
  return system
227
242
  }
228
243
 
244
+ /** Set once, so a payload without a `system` channel warns once per process. */
245
+ let compactionChannelWarned = false
246
+
247
+ /** Set once, so a failed bridge construction logs one line per process. */
248
+ let bridgeFailureLogged = false
249
+
250
+ /**
251
+ * Append text blocks to a hook payload's `system` channel.
252
+ *
253
+ * Returns `false` when the payload carries no usable channel (absent, or a
254
+ * shape that is neither string nor array) — the caller decides whether that is
255
+ * worth a diagnostic. A bare-string `system` is replaced by its part array on
256
+ * the payload itself, because the host reads the property, not our copy.
257
+ *
258
+ * Used by the V2 compaction hook (#266) to inject the compaction context
259
+ * blocks V1 pushes into `output.context`.
260
+ */
261
+ function appendSystemBlocks(
262
+ target: { system?: unknown } | null | undefined,
263
+ blocks: readonly string[],
264
+ ): boolean {
265
+ if (target == null || blocks.length === 0) return false
266
+ const normalized = normalizeSystemToParts(target.system)
267
+ if (normalized == null) return false
268
+ if (typeof target.system === 'string') target.system = normalized
269
+ for (const block of blocks) normalized.push({ type: 'text', text: block } satisfies SystemPart)
270
+ return true
271
+ }
272
+
229
273
  /**
230
274
  * Add a feature to the unsupported list (idempotent).
231
275
  */
@@ -333,18 +377,140 @@ let v1Bridge: PantheonV2Bridge | null = null
333
377
  */
334
378
  export function setV2Bridge(bridge: PantheonV2Bridge): void {
335
379
  v1Bridge = bridge
380
+ // Also publish process-wide so a V1 load that registers FIRST and a V2 load
381
+ // that resolves SECOND converge on one bridge (see v2-bridge.ts).
382
+ registerV2Bridge(bridge)
336
383
  }
337
384
 
338
385
  /**
339
- * Get the V1 bridge, checking module-level first, then ctx.options.
386
+ * Get the V1 bridge, checking module-level first, then the process-wide
387
+ * registration, then ctx.options.
340
388
  * Returns null when no bridge is available (V2 standalone mode).
341
389
  */
342
390
  function resolveBridge(ctx?: V2ContextLike): PantheonV2Bridge | null {
343
391
  if (v1Bridge != null) return v1Bridge
392
+ const registered = getRegisteredV2Bridge()
393
+ if (registered != null) {
394
+ v1Bridge = registered
395
+ return registered
396
+ }
344
397
  if (ctx != null) return getV2BridgeFromContext(ctx)
345
398
  return null
346
399
  }
347
400
 
401
+ /**
402
+ * The subset of the host's `session` domain a `TodoEnforcerClient` needs.
403
+ *
404
+ * Declared structurally and checked at runtime instead of being added to
405
+ * {@link V2SessionDomain} on faith: the measured 2.1.4 host exposes
406
+ * `hook`/`get`/`list`/`create`/`remove`/`prompt`/`generate`/`interrupt` on that
407
+ * domain. Its `prompt` takes `{ sessionID, text }` and is a DIFFERENT call from
408
+ * V1's `promptAsync({ path, body: { agent?, model?, parts } })` — the enforcer's
409
+ * agent/model inheritance has no V2 counterpart — and whether it exposes
410
+ * `todo`/`messages`/`children` at all is not measured by the repository. The
411
+ * check below therefore requires the V1 shape exactly: a client built on a
412
+ * method that is absent (or on a same-named method with a different contract)
413
+ * would throw inside the enforcer's fail-open guards and leave idle
414
+ * continuation silently dead again — the exact defect this wiring closes.
415
+ */
416
+ interface V2TodoSessionMethods {
417
+ todo?: (input: { path: { id: string } }) => Promise<unknown>
418
+ messages?: (input: { path: { id: string } }) => Promise<unknown>
419
+ children?: (input: { path: { id: string } }) => Promise<unknown>
420
+ promptAsync?: (input: { path: { id: string }; body: Record<string, unknown> }) => Promise<unknown>
421
+ }
422
+
423
+ const V2_TODO_CLIENT_METHODS = ['todo', 'messages', 'children', 'promptAsync'] as const
424
+
425
+ /**
426
+ * Adapt the host's `session` domain to the {@link TodoEnforcerClient} the V1
427
+ * enforcer instance expects, or `undefined` when the domain does not carry the
428
+ * four methods. The input shape is V1's (`{ path: { id } }`) because the
429
+ * enforcer is the V1 instance — this is an adapter, not a second enforcer.
430
+ */
431
+ function createV2TodoEnforcerClient(
432
+ session: V2SessionDomain | undefined,
433
+ ): TodoEnforcerClient | undefined {
434
+ if (session === undefined) return undefined
435
+ const methods = session as V2TodoSessionMethods
436
+ for (const method of V2_TODO_CLIENT_METHODS) {
437
+ if (typeof methods[method] !== 'function') return undefined
438
+ }
439
+ // Every method is present: the guard above is the only place absence is
440
+ // tolerated, so the assertions below cannot fire at runtime.
441
+ const todo = methods.todo as NonNullable<V2TodoSessionMethods['todo']>
442
+ const messages = methods.messages as NonNullable<V2TodoSessionMethods['messages']>
443
+ const children = methods.children as NonNullable<V2TodoSessionMethods['children']>
444
+ const promptAsync = methods.promptAsync as NonNullable<V2TodoSessionMethods['promptAsync']>
445
+ return {
446
+ session: {
447
+ todo: (input) => todo.call(session, input) as Promise<TodoLike[]>,
448
+ messages: (input) => messages.call(session, input) as Promise<TodoEnforcerMessage[]>,
449
+ children: (input) => children.call(session, input) as Promise<TodoEnforcerChild[]>,
450
+ promptAsync: (input) => promptAsync.call(session, input),
451
+ },
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Construct the V1→V2 bridge IN the V2 entry and publish it on both channels
457
+ * (issue #265).
458
+ *
459
+ * Before this, `setV2Bridge`/`injectBridge`/`createV2Bridge` had no production
460
+ * caller: `resolveBridge()` always returned null, so `onSessionIdle` reached a
461
+ * null enforcer and idle continuation never ran on any V2 install — including
462
+ * the V1+V2 co-load, because nothing had ever put a bridge in `ctx.options`
463
+ * either.
464
+ *
465
+ * What is genuinely constructible without a V1 `PluginInput`:
466
+ *
467
+ * - `board` — a process-wide singleton (`getSharedBoard`), the same instance
468
+ * V1 and the hooks plugin use.
469
+ * - `todoEnforcer` — the V1 class, fed by an adapter over the host's session
470
+ * domain. Present only when that domain exposes the four methods the
471
+ * enforcer uses; otherwise the reduction is marked (`idle-todo-enforcer`)
472
+ * and, because the marker is one a migrating user must be told about, it
473
+ * is also part of the static seed.
474
+ *
475
+ * Files in the bridge that need a V1 `client` (goal loop, vision handler) stay
476
+ * out: `goal-tools` already declares the goal surface absent, and the vision
477
+ * handler is V1-only.
478
+ */
479
+ function installV2Bridge(context: PluginContext): TodoEnforcer | undefined {
480
+ // Co-load guard (#265 review): a bridge with an enforcer may already exist —
481
+ // registered by V1 in this process, or by an earlier V2 setup. Building a
482
+ // second enforcer would answer the same `session.idle` twice (V1's dispatcher
483
+ // and this plugin each inject a continuation prompt). Reuse, never overwrite.
484
+ const existing = resolveBridge(context)
485
+ if (existing?.todoEnforcer !== undefined) {
486
+ injectBridge(context, existing)
487
+ return existing.todoEnforcer
488
+ }
489
+
490
+ const todoClient = createV2TodoEnforcerClient(hostDomains(context).session)
491
+ if (todoClient === undefined) markUnsupported('idle-todo-enforcer')
492
+ const board = getSharedBoard()
493
+ const todoEnforcer =
494
+ todoClient === undefined
495
+ ? undefined
496
+ : new TodoEnforcer({
497
+ client: todoClient,
498
+ board,
499
+ options: { ...TODO_ENFORCER_DEFAULTS, enabled: todoEnforcerEnabledFromEnv() },
500
+ })
501
+ const bridge = createV2Bridge({ board, ...(todoEnforcer === undefined ? {} : { todoEnforcer }) })
502
+ // Two channels, both needed: `ctx.options` is what a handler holding the
503
+ // context reads (`resolveBridge(ctx)`), and the module-level reference is
504
+ // what the event handlers use, since they receive no context.
505
+ injectBridge(context, bridge)
506
+ setV2Bridge(bridge)
507
+ // Returned so the compaction hook can list the session's PENDING TODOS with
508
+ // the same instance — the `<todo_context>` half of V1's compaction blocks
509
+ // needs exactly `listPendingTodos`, and the host exposes no todo listing of
510
+ // its own.
511
+ return todoEnforcer
512
+ }
513
+
348
514
  // ─── V2 Transform Functions ─────────────────────────────────────────────
349
515
 
350
516
  function transformAgents(draft: AgentDraft): void {
@@ -656,10 +822,11 @@ async function onSessionIdle(_event: V2SessionEvent): Promise<void> {
656
822
  // ever arrives. Implementing this safely needs V2-side session threading
657
823
  // first; until then it stays deferred rather than approximated.
658
824
  //
659
- // Idle continuation — goal loop / todo enforcer dispatch. This one really
660
- // does delegate: `bridge.todoEnforcer` is the V1 enforcer instance, reached
661
- // only in a process that also loaded V1. On a V2-only install the bridge
662
- // resolves to null and idle continuation does not run.
825
+ // Idle continuation — goal loop / todo enforcer dispatch. The bridge is
826
+ // constructed by THIS module in `installV2Bridge` (Phase 0) and holds the
827
+ // V1 TodoEnforcer instance when the host's session domain exposes the
828
+ // methods the enforcer uses. Before issue #265 nothing injected a bridge on
829
+ // the V2 path, so this call was a guaranteed no-op on every install.
663
830
  const sessionID = _event.properties?.sessionID as string | undefined
664
831
  if (!sessionID) return
665
832
  const bridge = resolveBridge()
@@ -722,7 +889,6 @@ async function onSessionDeleted(event: V2SessionEvent): Promise<void> {
722
889
  return
723
890
  }
724
891
  readOnlyRegistry.unregister(sessionID)
725
- memoryInjectionCache.delete(sessionID)
726
892
  }
727
893
 
728
894
  /**
@@ -745,17 +911,35 @@ async function onSessionCompacted(_event: V2SessionEvent): Promise<void> {}
745
911
 
746
912
  // ─── V2 Session Hooks ───────────────────────────────────────────────────
747
913
 
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
914
+ /** One entry per no-op reason and session/site; successful passes retain each saving. */
915
+ const pruneSkipSessions = new Set<string>()
916
+ const PRUNE_SKIP_SESSIONS_MAX = 256
917
+
918
+ function logContextPrune(stats: PruneStats, sessionID: unknown): void {
919
+ if (stats.changed) {
920
+ appendV2HookLog(
921
+ `[context-pruner] site=${stats.site} messages=${stats.messagesTouched} ` +
922
+ `parts=${stats.partsPruned} est_tokens_saved=${stats.estimatedTokensSaved}`,
923
+ )
924
+ return
925
+ }
926
+ if (
927
+ stats.skipReason === null ||
928
+ stats.skipReason === 'not-array' ||
929
+ stats.skipReason === 'malformed'
930
+ ) {
931
+ return
932
+ }
933
+
934
+ const session = typeof sessionID === 'string' && sessionID !== '' ? sessionID : 'unknown'
935
+ const key = `${stats.site}:${session}:${stats.skipReason}`
936
+ if (pruneSkipSessions.has(key)) return
937
+ if (pruneSkipSessions.size >= PRUNE_SKIP_SESSIONS_MAX) pruneSkipSessions.clear()
938
+ pruneSkipSessions.add(key)
756
939
  appendV2HookLog(
757
- `[context-pruner] site=${stats.site} messages=${stats.messagesTouched} ` +
758
- `parts=${stats.partsPruned} est_tokens_saved=${stats.estimatedTokensSaved}`,
940
+ `[context-pruner] site=${stats.site} skip=${stats.skipReason} ` +
941
+ `messages=${stats.messagesTouched} parts=${stats.partsPruned} ` +
942
+ `est_tokens_saved=${stats.estimatedTokensSaved}`,
759
943
  )
760
944
  }
761
945
 
@@ -816,16 +1000,15 @@ function warnContextPrunerConfigOnce(options: unknown): void {
816
1000
  }
817
1001
  }
818
1002
 
819
- // ─── Ambient memory injection (opt-in, V2 context hook) ─────────────────
820
-
821
1003
  /**
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.
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.
827
1010
  */
828
- const memoryInjectionCache = new MemoryInjectionCache()
1011
+ const V2_VISION_HISTORY_TEXT: ReadonlyMap<string, ReadonlyMap<string, string>> = new Map()
829
1012
 
830
1013
  /**
831
1014
  * Register session hooks via V2 ctx.session.hook.
@@ -841,7 +1024,6 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
841
1024
  // Config validity is independent of hook availability; warn before the early
842
1025
  // return so a typo is visible even on a host that registers no session hook.
843
1026
  warnContextPrunerConfigOnce(context.options)
844
- warnInvalidMemoryInjectionConfig(context.options, appendV2HookLog)
845
1027
  const sessionCtx = hostDomains(context).session
846
1028
 
847
1029
  if (!sessionCtx?.hook) {
@@ -854,11 +1036,6 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
854
1036
  // applies the rules unconditionally.
855
1037
  const prunerConfig = resolveContextPrunerConfig(context.options)
856
1038
 
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
-
862
1039
  let registered = false
863
1040
 
864
1041
  try {
@@ -895,22 +1072,23 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
895
1072
  normalized.push({ type: 'text', text: POLICY } satisfies SystemPart)
896
1073
  }
897
1074
  }
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
- )
1075
+ // Vision history sanitization (V1
1076
+ // `experimental.chat.messages.transform` parity, #266). Image parts are
1077
+ // replaced with their cached description, or with the same placeholder
1078
+ // V1 uses, BEFORE a text-only provider serializer can turn them into
1079
+ // `image_url` content. The host's `context` payload carries the
1080
+ // provider-bound `messages` array and honors mutations per request, so
1081
+ // this is the same seam V1's transform occupies.
1082
+ //
1083
+ // The description map is empty on V2 by construction: descriptions are
1084
+ // cached by the V1 vision handler, which has no V2 counterpart (V2
1085
+ // materializes the image and asks the model to call `vision_describe`).
1086
+ // Every image part therefore becomes the placeholder — the safety
1087
+ // property V1's transform exists for — never a raw image.
1088
+ try {
1089
+ sanitizeVisionHistory({ messages: ctx.messages }, V2_VISION_HISTORY_TEXT)
1090
+ } catch (error) {
1091
+ logPruneFailureOnce(ctx.sessionID, 'context', error)
914
1092
  }
915
1093
  // Opt-in DCP: same engine as the compaction site, but per-request
916
1094
  // pruning invalidates the prompt cache, so it runs only when
@@ -919,7 +1097,7 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
919
1097
  if (prunerConfig.enabled) {
920
1098
  try {
921
1099
  const stats = pruneMessages(ctx.messages, prunerConfig, 'context')
922
- logContextPrune(stats)
1100
+ logContextPrune(stats, ctx.sessionID)
923
1101
  logPruneShapeIssue(stats, ctx.sessionID, 'context')
924
1102
  } catch (error) {
925
1103
  logPruneFailureOnce(ctx.sessionID, 'context', error)
@@ -1316,9 +1494,20 @@ interface V2ToolExecuteBeforeEvent {
1316
1494
  *
1317
1495
  * Omitting all three skips the branch wholesale: the guard only enters it when
1318
1496
  * `options?.isRootSession !== undefined`. `task` is still denied inside a
1319
- * read-only session via the blocked-tool list, so depth-2 holds for
1320
- * apollo/gaia; the caller/target matrix itself is NOT enforced on V2. That is
1321
- * a known gap, not a covered case.
1497
+ * read-only session via the blocked-tool list, so the read-only half of depth-2
1498
+ * holds for apollo/gaia.
1499
+ *
1500
+ * The caller/target half is NOT this guard's job on V2, and that is a division
1501
+ * of labour rather than a gap: V2 delegates through the native `subagent` tool
1502
+ * and its `permission.hook('evaluate')` handler, which calls
1503
+ * `evaluateV2Delegation` — the matrix (zeus → anyone; athena/hermes → apollo)
1504
+ * plus the same depth-2 rule, expressed as "a caller session that carries a
1505
+ * `parentID` is denied". Both are proved in
1506
+ * tests/pantheon/plugin-v2-contract.test.ts and
1507
+ * tests/pantheon/v2-delegation-enforce.test.ts.
1508
+ *
1509
+ * The Zeus read guard is a SEPARATE call in the same `execute.before` handler
1510
+ * (issue #264), fed from the same event `agent`; it is not part of this guard.
1322
1511
  */
1323
1512
  const v2EnforcementGuard = createEnforcementGuard({
1324
1513
  getReadOnlySessions: () => readOnlyRegistry.sessionIDs(),
@@ -1358,6 +1547,35 @@ function adaptV2ExecuteBeforeEvent(event: unknown): {
1358
1547
  }
1359
1548
  }
1360
1549
 
1550
+ /**
1551
+ * Test seam — override (or, with `null`, restore) the V2 shell-hook runner.
1552
+ *
1553
+ * Exported only for tests/pantheon/plugin-v2-contract.test.ts, which asserts
1554
+ * that the REGISTERED `execute.before`/`execute.after` handlers invoke the
1555
+ * formatter and the delegation audit scripts. Spawning the real scripts would
1556
+ * make the assertion depend on the shell, not on the wiring; the scripts
1557
+ * themselves are covered by tests/pantheon/v2-shell-hooks.test.ts.
1558
+ */
1559
+ export function setV2ShellRunnerForTests(runner: V2ShellRunner | null): void {
1560
+ shellRunnerOverride = runner ?? undefined
1561
+ }
1562
+
1563
+ let shellRunnerOverride: V2ShellRunner | undefined
1564
+
1565
+ /**
1566
+ * Test seam — clear the module-level bridge AND the process-wide registration.
1567
+ *
1568
+ * Exported only for tests/pantheon/plugin-v2-contract.test.ts. The co-load guard
1569
+ * makes `installV2Bridge` reuse an existing bridge (so V1's enforcer is never
1570
+ * duplicated), which means a test that asserts the CONSTRUCTION path has to
1571
+ * start from "no bridge". Production has no caller: a process keeps its bridge
1572
+ * for its lifetime.
1573
+ */
1574
+ export function resetV2BridgeForTests(): void {
1575
+ v1Bridge = null
1576
+ registerV2Bridge(null)
1577
+ }
1578
+
1361
1579
  /**
1362
1580
  * Register tool execution hooks via V2 ctx.tool.hook.
1363
1581
  *
@@ -1372,12 +1590,27 @@ async function registerV2ToolHooks(
1372
1590
  subagentOrigins: V2SubagentOriginRegistry,
1373
1591
  boundedReadOrigins?: V2BoundedReadOriginRegistry,
1374
1592
  ): Promise<{ registered: boolean; beforeRegistered: boolean }> {
1375
- const toolCtx = hostDomains(context).tool
1593
+ const host = hostDomains(context)
1594
+ const toolCtx = host.tool
1376
1595
 
1377
1596
  if (!toolCtx?.hook) {
1378
1597
  return { registered: false, beforeRegistered: false }
1379
1598
  }
1380
1599
 
1600
+ // V1 shell-hook parity (#266): formatter on every after-event, delegation
1601
+ // audit start/stop. Both scripts are environment-independent, so they are
1602
+ // invoked through the same runner the secret scan uses.
1603
+ const shellHooks = createV2ShellHooks({
1604
+ ...(shellRunnerOverride === undefined ? {} : { run: shellRunnerOverride }),
1605
+ onUnkeyed: appendV2HookLog,
1606
+ })
1607
+
1608
+ // Symlink resolution for the Zeus read guard (#272). The predicate is pure,
1609
+ // so the filesystem work happens at this call site, rooted at the project
1610
+ // directory the host reports. Same mechanism as V1's (src/plugin.ts) so the
1611
+ // two registration paths stay consistent.
1612
+ const resolveGuardPath = createGuardPathResolver(host.location?.directory || process.cwd())
1613
+
1381
1614
  let registered = false
1382
1615
  let beforeRegistered = false
1383
1616
 
@@ -1401,6 +1634,24 @@ async function registerV2ToolHooks(
1401
1634
  // and no session→agent map. A non-read-only (or absent) agent revokes the
1402
1635
  // registration, which also covers an in-session agent switch.
1403
1636
  syncReadOnlySession(readOnlyRegistry, input.sessionID, agent)
1637
+ // Zeus read guard (issue #264). V1 wires this from its `chat.params`
1638
+ // session→agent map (`src/plugin.ts`); V2 has no such map because the
1639
+ // host puts the active agent on THIS event, so the guard is fed from
1640
+ // the event's `agent` field — the same identity the read-only
1641
+ // registry above already trusts.
1642
+ //
1643
+ // Fail-closed on casing: `zeusReadGuard` compares the agent with an
1644
+ // exact `!== 'zeus'`, so a host that reports `Zeus` would silently
1645
+ // disable the guard. Normalizing through the shared
1646
+ // `normalizeDelegationAgent` keeps the comparison meaningful without
1647
+ // changing the predicate V1 uses.
1648
+ //
1649
+ // Runs BEFORE the read-only guard, matching V1's chain order. Both
1650
+ // throw to deny; neither is inside the scanner's try/catch, so a
1651
+ // denial keeps propagating to the host. The resolver is V1's too:
1652
+ // every TARGET path is also checked in its SYMLINK-RESOLVED form
1653
+ // (#272), and a resolution failure denies.
1654
+ zeusReadGuard(input.tool, output.args, normalizeDelegationAgent(agent), resolveGuardPath)
1404
1655
  // Deliberately OUTSIDE the try/catch below: a read-only denial must keep
1405
1656
  // propagating to the host, not be swallowed as a scanner failure.
1406
1657
  await v2EnforcementGuard(input, output)
@@ -1469,6 +1720,10 @@ async function registerV2ToolHooks(
1469
1720
  if (origin !== undefined) {
1470
1721
  writeV2AdmissionProof('tool.execute.before', { ...origin })
1471
1722
  }
1723
+ // Delegation audit START record (#266). Deliberately AFTER every guard
1724
+ // and the secret scan: a denied call must not leave a start record with
1725
+ // no matching stop. The formatter/stop halves run in `execute.after`.
1726
+ await shellHooks.before(event)
1472
1727
  } finally {
1473
1728
  // BENCH instrumentation — observation only; runs on the deny paths too.
1474
1729
  logBenchHookTiming('before', event, benchStartedAt)
@@ -1499,6 +1754,10 @@ async function registerV2ToolHooks(
1499
1754
  subagentOrigins.forget(event)
1500
1755
  boundedReadOrigins?.forget(event)
1501
1756
  await v2ExecuteAfter(event)
1757
+ // Formatter + delegation audit STOP (#266). Awaited for the same
1758
+ // reason V1 awaits it: the log record should exist before the tool
1759
+ // result is surfaced. Failures are swallowed inside the module.
1760
+ await shellHooks.after(event)
1502
1761
  } finally {
1503
1762
  // BENCH instrumentation — observation only; the awaited call means the
1504
1763
  // duration covers the whole parity chain, not just its dispatch.
@@ -1778,6 +2037,39 @@ export const plugin = define({
1778
2037
  id: 'pantheon-opencode-v2',
1779
2038
 
1780
2039
  async setup(context: PluginContext): Promise<void> {
2040
+ // ─── Phase 0: V1→V2 bridge (issue #265) ────────────────────────────
2041
+ // First, because the event subscription below can deliver `session.idle`
2042
+ // as soon as it starts: a bridge installed after it would lose the first
2043
+ // idle of the process. Constructing it here is what makes
2044
+ // `resolveBridge()` non-null on a V2 install — before this, the factory
2045
+ // and the injector had no production call site at all.
2046
+ //
2047
+ // The returned enforcer (when the host session domain supports it) is the
2048
+ // single instance: Phase 7 asks it for pending todos and the idle path asks
2049
+ // it to continue, so there are never two.
2050
+ //
2051
+ // Guarded, because this phase is the only one that MUTATES the context:
2052
+ // `injectBridge` writes `ctx.options`, and an unguarded throw here would
2053
+ // reject `setup()` and remove every later registration with it — the read
2054
+ // guard, the secret scan and all tools. A degraded run is far better than a
2055
+ // plugin that registers nothing, and the degradation is reported (`v1-bridge`
2056
+ // in the live unsupported list) instead of being invisible.
2057
+ let idleEnforcer: TodoEnforcer | undefined
2058
+ try {
2059
+ idleEnforcer = installV2Bridge(context)
2060
+ } catch (error) {
2061
+ idleEnforcer = undefined
2062
+ markUnsupported('v1-bridge')
2063
+ if (!bridgeFailureLogged) {
2064
+ bridgeFailureLogged = true
2065
+ const reason = error instanceof Error ? error.message : String(error)
2066
+ appendV2HookLog(
2067
+ `[v1-bridge] construction failed; continuing without a bridge ` +
2068
+ `(idle continuation and todo context unavailable): ${reason}`,
2069
+ )
2070
+ }
2071
+ }
2072
+
1781
2073
  // ─── Phase 1: V2 Transforms (isolated per-domain, best-effort) ────
1782
2074
  // Each transform registration is individually wrapped and settled via Promise.allSettled:
1783
2075
  // a rejection marks only that transform unsupported
@@ -1858,13 +2150,17 @@ export const plugin = define({
1858
2150
  // ─── Phase 7: V2 Compaction Hook (best-effort) ───────────────────
1859
2151
  const compactionCtx = hostDomains(context).session
1860
2152
  if (compactionCtx?.hook) {
2153
+ // File-based goal store, constructed once: the compaction context needs
2154
+ // active goals per session, and the store needs no host API (same
2155
+ // `.pantheon/goals` directory V1 uses).
2156
+ const goalStore = new GoalStore({ dir: '.pantheon/goals' })
1861
2157
  try {
1862
2158
  // 2.0.16 `SessionHooks` key is `compaction` (the migration doc maps
1863
2159
  // `experimental.session.compacting` → `ctx.session.hook("compaction")`).
1864
2160
  // `compacting` is not a valid key: the registry accepts any string and
1865
2161
  // silently drops unknown names, so the old name was a permanent no-op.
1866
2162
  // Proven by the canary's negative control.
1867
- await compactionCtx.hook('compaction', (event: unknown) => {
2163
+ await compactionCtx.hook('compaction', async (event: unknown) => {
1868
2164
  try {
1869
2165
  // Opt-in lifetime proof for the host-backed hook canary
1870
2166
  // (tests/pantheon/plugin-v2-hook-canary.test.mjs, MODE=real). It is
@@ -1889,11 +2185,68 @@ export const plugin = define({
1889
2185
  // untouched. Apply the rules by default: it only changes what feeds
1890
2186
  // the summary. Never set `input.result`: the model must summarize
1891
2187
  // the pruned history, not be replaced by a canned summary.
1892
- const payload = event as { sessionID?: unknown; messages?: unknown } | null | undefined
2188
+ //
2189
+ // The host's compaction payload is
2190
+ // `{ session, agent, model, tools, system, messages, … }` — the id
2191
+ // is on `session.id`, NOT top-level `sessionID` (measured against
2192
+ // the 2.1.4 host; both spellings are accepted below).
2193
+ const payload = event as {
2194
+ sessionID?: unknown
2195
+ session?: { id?: unknown }
2196
+ messages?: unknown
2197
+ system?: unknown
2198
+ } | null
2199
+ const sessionID =
2200
+ typeof payload?.sessionID === 'string'
2201
+ ? payload.sessionID
2202
+ : typeof payload?.session?.id === 'string'
2203
+ ? payload.session.id
2204
+ : undefined
1893
2205
  const prunerConfig = resolveContextPrunerConfig(context.options)
1894
2206
  const stats = pruneMessages(payload?.messages, prunerConfig, 'compaction')
1895
- logContextPrune(stats)
1896
- logPruneShapeIssue(stats, payload?.sessionID, 'compaction')
2207
+ logContextPrune(stats, sessionID)
2208
+ logPruneShapeIssue(stats, sessionID, 'compaction')
2209
+
2210
+ // Compaction context (V1 `experimental.session.compacting`
2211
+ // parity, #266). The SAME builder V1 uses — directive +
2212
+ // `<mission_context>` — pushed into the payload's `system` array,
2213
+ // which is the only text sink the V2 compaction hook exposes
2214
+ // (`context` is the session-hook name in V1, not a field here).
2215
+ //
2216
+ // The `<todo_context>` section is present only when the bridge
2217
+ // built a real enforcer (host session domain exposes the todo
2218
+ // listing), and `<tool_ceiling>` has no V2 producer at all — both
2219
+ // reductions are declared in the capability seed instead of
2220
+ // silently missing.
2221
+ const blocks = await buildCompactionContext({
2222
+ ...(sessionID === undefined ? {} : { sessionID }),
2223
+ goals: {
2224
+ // Same gate V1 uses: the goal loop is disabled in this build,
2225
+ // so `<mission_context>` is omitted on both surfaces.
2226
+ enabled: GOAL_LOOP_DEFAULTS.enabled,
2227
+ list: (id: string) => goalStore.list(id),
2228
+ },
2229
+ ...(idleEnforcer === undefined
2230
+ ? {}
2231
+ : {
2232
+ todos: {
2233
+ // V1's own source: `TodoEnforcer.listPendingTodos`.
2234
+ enabled: todoEnforcerEnabledFromEnv(),
2235
+ list: (id: string) => idleEnforcer.listPendingTodos(id),
2236
+ },
2237
+ }),
2238
+ })
2239
+ if (blocks.length > 0 && !appendSystemBlocks(payload, blocks)) {
2240
+ // The payload carried no usable `system`. Diagnostic once per
2241
+ // process: a silent miss here would look like "no goals".
2242
+ if (!compactionChannelWarned) {
2243
+ compactionChannelWarned = true
2244
+ appendV2HookLog(
2245
+ '[compaction-context] payload.system is not a string or array; ' +
2246
+ 'compaction context could not be injected',
2247
+ )
2248
+ }
2249
+ }
1897
2250
  } catch (error) {
1898
2251
  // Fail-open: any unexpected shape or engine failure must not kill
1899
2252
  // the compaction request. One diagnostic line per session maximum.