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
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Symlink resolution for the Zeus read guard.
3
+ *
4
+ * `zeusReadGuard` is a pure, synchronous predicate shared by V1 and V2, so it
5
+ * cannot touch the filesystem itself. It therefore used to match only the
6
+ * STRING path: `docs/link → ../src` reached `src/` after resolution but passed
7
+ * the guard, while `pantheon_bounded_read` refused the same path via `lstat` +
8
+ * `realpath`. This module closes that gap at the CALL SITES: they resolve the
9
+ * raw path once, then hand the result to the guard.
10
+ *
11
+ * Resolution rules:
12
+ * - relative paths resolve against the project root, absolute paths stand;
13
+ * - a path that does not exist resolves its deepest EXISTING ancestor and
14
+ * re-appends the remaining segments — a deleted path can still be a bypass;
15
+ * - a resolved path inside the project root is expressed RELATIVE to it (so a
16
+ * project living under a directory named `src` is not a false positive),
17
+ * and a resolved path outside the root stays absolute (the guard already
18
+ * suffix-matches absolute paths, which is what catches `../src`);
19
+ * - any resolution failure (symlink loop, permissions, …) is reported as
20
+ * `failed`: a read guard fails CLOSED, and the guard denies.
21
+ */
22
+
23
+ import { lstatSync, realpathSync, statSync } from 'node:fs'
24
+ import path from 'node:path'
25
+
26
+ /** One path form prepared for the guard. */
27
+ export interface GuardPathResolution {
28
+ /** Path as supplied, with separators normalized. */
29
+ raw: string
30
+ /**
31
+ * Symlink-resolved path: relative to the project root when it lands inside
32
+ * it, absolute otherwise. Absent when resolution failed.
33
+ */
34
+ resolved?: string
35
+ /** `true` when the path could not be resolved — the guard must DENY. */
36
+ failed: boolean
37
+ /** Filesystem annotation from the call-site resolver; never computed by the pure guard. */
38
+ isRegularFile?: boolean
39
+ /** Whether the canonical target is the project root or one of its descendants. */
40
+ withinProject?: boolean
41
+ }
42
+
43
+ /** Errors that mean "this component does not exist", not "resolution failed". */
44
+ const MISSING_CODES: ReadonlySet<string> = new Set(['ENOENT', 'ENOTDIR'])
45
+ /** Bound filesystem component walks; paths beyond this limit fail closed. */
46
+ const MAX_PATH_COMPONENTS = 64
47
+
48
+ function errorCode(error: unknown): string {
49
+ if (typeof error !== 'object' || error === null || !('code' in error)) return ''
50
+ return String((error as { code: unknown }).code)
51
+ }
52
+
53
+ function isMissing(error: unknown): boolean {
54
+ return MISSING_CODES.has(errorCode(error))
55
+ }
56
+
57
+ /** `true` when `target` is `root` or lives under it (both absolute). */
58
+ function isWithin(root: string, target: string): boolean {
59
+ const relative = path.relative(root, target)
60
+ return (
61
+ relative === '' ||
62
+ (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
63
+ )
64
+ }
65
+
66
+ /**
67
+ * `realpath` of `absolute`, or of its deepest existing ancestor with the
68
+ * non-existent remainder appended. At most 64 components are examined; an
69
+ * existing dangling symlink or an overlong path fails closed.
70
+ *
71
+ * @returns the resolved absolute path, or `undefined` when resolution failed
72
+ * for a reason other than a missing component.
73
+ */
74
+ function resolveExistingPrefix(absolute: string): string | undefined {
75
+ let cursor = path.resolve(absolute)
76
+ if (cursor.split(path.sep).filter(Boolean).length > MAX_PATH_COMPONENTS) return undefined
77
+ const remainder: string[] = []
78
+ for (let walked = 0; walked < MAX_PATH_COMPONENTS; walked++) {
79
+ try {
80
+ const resolved = realpathSync(cursor)
81
+ return remainder.length === 0 ? resolved : path.join(resolved, ...remainder)
82
+ } catch (error) {
83
+ if (!isMissing(error)) return undefined
84
+ try {
85
+ if (lstatSync(cursor).isSymbolicLink()) return undefined
86
+ } catch (lstatError) {
87
+ if (!isMissing(lstatError)) return undefined
88
+ }
89
+ const parent = path.dirname(cursor)
90
+ // Reached the filesystem root without resolving: unreachable on a sane
91
+ // system, but a failure must stay a failure (fail closed).
92
+ if (parent === cursor) return undefined
93
+ remainder.unshift(path.basename(cursor))
94
+ cursor = parent
95
+ }
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ /** Normalize a resolved absolute path into the form the guard matches. */
101
+ function toGuardForm(resolvedAbsolute: string, rootReal: string): string {
102
+ const relative = isWithin(rootReal, resolvedAbsolute)
103
+ ? path.relative(rootReal, resolvedAbsolute)
104
+ : resolvedAbsolute
105
+ return relative.split(path.sep).join('/')
106
+ }
107
+
108
+ /** Canonicalize an existing project directory; failure must never broaden access. */
109
+ function canonicalProjectRoot(projectRoot: string): string | undefined {
110
+ try {
111
+ const rootReal = realpathSync(path.resolve(projectRoot))
112
+ return statSync(rootReal).isDirectory() ? rootReal : undefined
113
+ } catch {
114
+ return undefined
115
+ }
116
+ }
117
+
118
+ function resolveAgainst(rawPath: string, rootReal: string): GuardPathResolution {
119
+ const raw = rawPath.replace(/\\/g, '/')
120
+ const absolute = path.resolve(rootReal, raw)
121
+ const resolvedAbsolute = resolveExistingPrefix(absolute)
122
+ if (resolvedAbsolute === undefined) return { raw, failed: true }
123
+ let isRegularFile = false
124
+ try {
125
+ isRegularFile = statSync(resolvedAbsolute).isFile()
126
+ } catch (error) {
127
+ if (!isMissing(error)) return { raw, failed: true }
128
+ }
129
+ return {
130
+ raw,
131
+ resolved: toGuardForm(resolvedAbsolute, rootReal),
132
+ failed: false,
133
+ isRegularFile,
134
+ withinProject: isWithin(rootReal, resolvedAbsolute),
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Resolve one raw tool path for the Zeus read guard.
140
+ *
141
+ * Use {@link createGuardPathResolver} at a call site that checks many paths:
142
+ * it resolves the project root once instead of once per path.
143
+ */
144
+ export function resolveGuardPathForCheck(
145
+ rawPath: string,
146
+ projectRoot: string,
147
+ ): GuardPathResolution {
148
+ const rootReal = canonicalProjectRoot(projectRoot)
149
+ return rootReal === undefined ? { raw: rawPath, failed: true } : resolveAgainst(rawPath, rootReal)
150
+ }
151
+
152
+ /**
153
+ * Build the per-call-site resolver. The project root is resolved once, so a
154
+ * symlinked root (`/tmp` → `/private/tmp`) compares against real paths.
155
+ */
156
+ export function createGuardPathResolver(
157
+ projectRoot: string,
158
+ ): (rawPath: string) => GuardPathResolution {
159
+ const rootReal = canonicalProjectRoot(projectRoot)
160
+ return (rawPath) =>
161
+ rootReal === undefined ? { raw: rawPath, failed: true } : resolveAgainst(rawPath, rootReal)
162
+ }
@@ -61,6 +61,12 @@ const DENIED_EXTENSIONS = new Set([
61
61
  '.db',
62
62
  '.sql',
63
63
  ])
64
+ /**
65
+ * Top-level code roots denied for the same reason the Zeus read guard denies
66
+ * them (`ZEUS_READ_DENY_PATTERNS` in delegation-enforce.ts): `src/`, `tests/`,
67
+ * `scripts/`. Mirrors `/^(src\/|tests?\/|scripts?\/)/`.
68
+ */
69
+ const DENIED_CODE_ROOTS = new Set(['src', 'test', 'tests', 'script', 'scripts'])
64
70
  const DENIED_MEDIA_EXTENSIONS = new Set([
65
71
  '.avif',
66
72
  '.bmp',
@@ -314,6 +320,14 @@ function sensitivePath(relativePath: string): boolean {
314
320
  const leaf = components.at(-1) ?? ''
315
321
  const extension = path.extname(leaf)
316
322
  return (
323
+ // Code roots are denied for the SAME reason the Zeus read guard denies
324
+ // `read`/`glob`/`grep` on them (issue #264): this tool is root-Zeus-only, so
325
+ // allowing `src/`, `tests/` or `scripts/` here would let the orchestrator
326
+ // read 2×400 lines of source through a first-class tool while the guarded
327
+ // `read` is refused — the documented "Zeus delegates code reads to @apollo"
328
+ // policy would hold only on paper. Docs, config, the memory bank and
329
+ // `.pantheon/` stay readable: that is what this tool exists for.
330
+ DENIED_CODE_ROOTS.has(components[0] ?? '') ||
317
331
  components.some(
318
332
  (component) =>
319
333
  DENIED_COMPONENTS.has(component) ||
@@ -499,7 +513,7 @@ export function createV2BoundedReadTool(dependencies: BoundedReadDependencies):
499
513
  const definition: V2ToolDef = {
500
514
  name: BOUNDED_READ_TOOL,
501
515
  description:
502
- 'Read a small line range from one exact text file inside the current project. Root Zeus only; two files and 400 lines total per assistant message. Denies recognized sensitive scopes and known binary/media formats; returns only bounded valid UTF-8 text after secret scanning. No directories or fallback reading.',
516
+ 'Read a small line range from one exact text file inside the current project. Root Zeus only; two files and 400 lines total per assistant message. Denies the code roots Zeus must delegate (src/, tests/, scripts/), recognized sensitive scopes, and known binary/media formats; returns only bounded valid UTF-8 text after secret scanning. No directories or fallback reading.',
503
517
  input: {
504
518
  type: 'object',
505
519
  additionalProperties: false,
@@ -124,3 +124,30 @@ export function getV2BridgeFromContext(ctx: V2ContextLike): PantheonV2Bridge | n
124
124
  export function injectBridge(ctx: V2ContextLike, bridge: PantheonV2Bridge): void {
125
125
  ctx.options[BRIDGE_OPTIONS_KEY] = bridge
126
126
  }
127
+
128
+ // ─── Process-wide registration (cross-generation) ──────────────────────
129
+
130
+ /**
131
+ * The bridge registered by whichever plugin loaded first in this process.
132
+ *
133
+ * The module-level handle lives HERE rather than in `plugin-v2.ts` because V1
134
+ * must be able to publish its singletons WITHOUT importing the V2 plugin: a
135
+ * V1-only install never loads `plugin-v2.ts`, and importing it just to hand
136
+ * over a bridge would pull the V2 `define()` into that process.
137
+ *
138
+ * Why registration matters: in a process that loads both generations (npm +
139
+ * repo double load, or a mixed config), V1's idle dispatcher and the V2 entry
140
+ * would otherwise each build a TodoEnforcer and answer the same `session.idle`
141
+ * twice — two continuation prompts for one idle. V1 registers; V2 reuses.
142
+ */
143
+ let registeredBridge: PantheonV2Bridge | null = null
144
+
145
+ /** Publish (or, with `null`, clear) the process-wide bridge. */
146
+ export function registerV2Bridge(bridge: PantheonV2Bridge | null): void {
147
+ registeredBridge = bridge
148
+ }
149
+
150
+ /** The bridge published by this process, or null. */
151
+ export function getRegisteredV2Bridge(): PantheonV2Bridge | null {
152
+ return registeredBridge
153
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * V2 shell-hook parity — the two V1 shell hooks that had no V2 equivalent.
3
+ *
4
+ * V1 runs them from `src/plugins/pantheon-hooks.ts` (`tool.execute.before` /
5
+ * `tool.execute.after`):
6
+ *
7
+ * - `format-multi-language.sh` on every completed tool call (post-write
8
+ * formatting);
9
+ * - `on-subagent-delegation-start.sh` / `-stop.sh`, which append the
10
+ * `delegations.log` audit records (start/stop joined on `delegation_id`).
11
+ *
12
+ * `pantheon-hooks.ts` is a SEPARATE plugin and is never loaded on a V2-only
13
+ * install — `opencode.json` `plugins` declares only `src/plugin-v2` — so both
14
+ * were dead on V2. The scripts themselves are environment-independent (they
15
+ * read the Claude Code payload from stdin and write their own log files), so
16
+ * they are run through the same `runHook` runner the secret scan already uses;
17
+ * no V1 plugin import is needed and none is introduced.
18
+ *
19
+ * What is derived here, and why it is not a second implementation of V1:
20
+ *
21
+ * - `delegation_id` — a UUID generated in the BEFORE hook and carried to the
22
+ * STOP hook through a callID-keyed record, which is how the two log lines
23
+ * join (V1 does the same in `pantheon-hooks.ts`).
24
+ * - `agent_id` — `tool_input.subagent_type` (or `agent`/`target`) first, the
25
+ * tool name last, mirroring V1's `delegationAgent`. The AFTER-time args are
26
+ * never used to derive it, because a background dispatch returns
27
+ * `{task_id, state}` there and no agent.
28
+ * - `status` — `failure` on an error event, `dispatched` when the result
29
+ * carries a `task_id` or a running/queued state, `success` otherwise. A
30
+ * background dispatch is DISPATCH, never a fabricated success.
31
+ *
32
+ * Fail-open by contract: every call is wrapped, so a missing script, a timeout
33
+ * or a malformed payload can never break the tool call it observes. The audit
34
+ * trail is telemetry; the security decisions live in the guards, not here.
35
+ *
36
+ * @module v2-shell-hooks
37
+ */
38
+
39
+ import { randomUUID } from 'node:crypto'
40
+ import { type HookPayload, type HookResult, runHook } from '../plugins/hook-runner.ts'
41
+
42
+ /**
43
+ * Delegation tool names. MIRRORS `DELEGATION_TOOL_RE` in
44
+ * `src/plugins/pantheon-hooks.ts` (V1). Duplicated rather than imported: that
45
+ * module is the V1 plugin, not loaded on a V2-only install, and importing it
46
+ * for one regex would resurrect the V1 coupling V2 exists to remove. The drift
47
+ * risk is asserted by tests/pantheon/v2-shell-hooks.test.ts.
48
+ */
49
+ export const V2_DELEGATION_TOOL_RE = /^(task|.*subagent.*)$/i
50
+
51
+ /** Scripts, by the names `scripts/hooks/` ships. */
52
+ export const FORMATTER_SCRIPT = 'format-multi-language.sh'
53
+ export const DELEGATION_START_SCRIPT = 'on-subagent-delegation-start.sh'
54
+ export const DELEGATION_STOP_SCRIPT = 'on-subagent-delegation-stop.sh'
55
+
56
+ /** One script invocation. Injected in tests to avoid spawning a shell. */
57
+ export type V2ShellRunner = (script: string, payload: HookPayload) => Promise<HookResult>
58
+
59
+ const defaultRunner: V2ShellRunner = (script, payload) => runHook(script, payload)
60
+
61
+ /** Hard cap on pending records — a tool result may never arrive. */
62
+ const MAX_PENDING_STARTS = 256
63
+
64
+ interface DelegationStart {
65
+ delegationId: string
66
+ agent: string
67
+ startedAt: number
68
+ }
69
+
70
+ /** The `execute.before` fields this module reads. */
71
+ interface V2BeforeEvent {
72
+ tool?: unknown
73
+ sessionID?: unknown
74
+ agent?: unknown
75
+ id?: unknown
76
+ input?: unknown
77
+ }
78
+
79
+ /** The `execute.after` fields this module reads. */
80
+ interface V2AfterEvent extends V2BeforeEvent {
81
+ status?: unknown
82
+ result?: unknown
83
+ }
84
+
85
+ /** Payload with the lifecycle keys the audit scripts read. */
86
+ type AuditPayload = HookPayload & Record<string, unknown>
87
+
88
+ function text(value: unknown): string {
89
+ return typeof value === 'string' ? value : ''
90
+ }
91
+
92
+ /** `tool_input.subagent_type` (or agent/target) first, the tool name last. */
93
+ export function delegationAgent(tool: string, args: unknown): string {
94
+ if (args !== null && typeof args === 'object') {
95
+ const record = args as Record<string, unknown>
96
+ for (const key of ['subagent_type', 'subagentType', 'agent', 'target']) {
97
+ const candidate = record[key]
98
+ if (typeof candidate === 'string' && candidate.trim() !== '') return candidate
99
+ }
100
+ }
101
+ return tool
102
+ }
103
+
104
+ /** Task id from a background dispatch result, or '' when absent. */
105
+ export function extractTaskID(result: unknown): string {
106
+ if (result === null || typeof result !== 'object') return ''
107
+ const record = result as Record<string, unknown>
108
+ const direct = record.task_id ?? record.taskID
109
+ if (typeof direct === 'string') return direct
110
+ const metadata = record.metadata
111
+ if (metadata !== null && typeof metadata === 'object') {
112
+ const nested = (metadata as Record<string, unknown>).task_id
113
+ if (typeof nested === 'string') return nested
114
+ }
115
+ return ''
116
+ }
117
+
118
+ /** `success` | `failure` | `dispatched`, never a fabricated success. */
119
+ export function delegationStatus(event: V2AfterEvent): string {
120
+ if (event.status === 'error') return 'failure'
121
+ const result = event.result
122
+ if (result !== null && typeof result === 'object') {
123
+ const metadata = (result as Record<string, unknown>).metadata
124
+ if (metadata !== null && typeof metadata === 'object') {
125
+ for (const key of ['status', 'state']) {
126
+ const value = (metadata as Record<string, unknown>)[key]
127
+ if (
128
+ typeof value === 'string' &&
129
+ /^(running|queued|pending|scheduled)$/i.test(value.trim())
130
+ ) {
131
+ return 'dispatched'
132
+ }
133
+ }
134
+ }
135
+ }
136
+ return extractTaskID(result) !== '' ? 'dispatched' : 'success'
137
+ }
138
+
139
+ /**
140
+ * Build the two V2 shell-hook handlers.
141
+ *
142
+ * `run` and `now` exist for tests; production uses `runHook` and `Date.now`.
143
+ */
144
+ export function createV2ShellHooks(
145
+ options: {
146
+ run?: V2ShellRunner
147
+ now?: () => number
148
+ /** Diagnostic sink for the unkeyed-event case (wired to hooks.log). */
149
+ onUnkeyed?: (message: string) => void
150
+ } = {},
151
+ ): {
152
+ before(event: unknown): Promise<void>
153
+ after(event: unknown): Promise<void>
154
+ } {
155
+ const run = options.run ?? defaultRunner
156
+ const now = options.now ?? Date.now
157
+ const starts = new Map<string, DelegationStart>()
158
+ /** Set once: a host that never sends `id` must not flood the log. */
159
+ let unkeyedWarned = false
160
+ const warnUnkeyed = (phase: string): void => {
161
+ if (unkeyedWarned) return
162
+ unkeyedWarned = true
163
+ options.onUnkeyed?.(
164
+ `[delegation-audit] ${phase} event carries no tool call id; the audit record was skipped ` +
165
+ 'because a START without a key can never be joined by its STOP',
166
+ )
167
+ }
168
+
169
+ /** Fire and swallow: telemetry must never break the observed tool call. */
170
+ const fire = async (script: string, payload: AuditPayload): Promise<void> => {
171
+ try {
172
+ await run(script, payload)
173
+ } catch {
174
+ // Deliberately silent: the scripts log their own failures, and a thrown
175
+ // audit hook would turn a completed tool call into an error.
176
+ }
177
+ }
178
+
179
+ const basePayload = (event: V2BeforeEvent): AuditPayload => ({
180
+ tool_name: text(event.tool),
181
+ tool_input: event.input ?? {},
182
+ agent_id: text(event.agent),
183
+ session_id: text(event.sessionID),
184
+ })
185
+
186
+ return {
187
+ async before(rawEvent: unknown): Promise<void> {
188
+ if (rawEvent === null || typeof rawEvent !== 'object') return
189
+ const event = rawEvent as V2BeforeEvent
190
+ const tool = text(event.tool)
191
+ if (!V2_DELEGATION_TOOL_RE.test(tool)) return
192
+ const callID = text(event.id)
193
+ if (callID === '') {
194
+ // A START record with no joinable key is a record that can never be
195
+ // closed: the after-event carries no id either, so the STOP would have
196
+ // to omit `delegation_id` and the audit log would hold an orphan line
197
+ // forever. Refuse to write it, and say so once.
198
+ warnUnkeyed('execute.before')
199
+ return
200
+ }
201
+ const start: DelegationStart = {
202
+ delegationId: randomUUID(),
203
+ agent: delegationAgent(tool, event.input),
204
+ startedAt: now(),
205
+ }
206
+ while (starts.size >= MAX_PENDING_STARTS) {
207
+ const oldest = starts.keys().next().value
208
+ if (oldest === undefined) break
209
+ starts.delete(oldest)
210
+ }
211
+ starts.set(callID, start)
212
+ await fire(DELEGATION_START_SCRIPT, {
213
+ ...basePayload(event),
214
+ agent_id: start.agent,
215
+ delegation_id: start.delegationId,
216
+ })
217
+ },
218
+
219
+ async after(rawEvent: unknown): Promise<void> {
220
+ if (rawEvent === null || typeof rawEvent !== 'object') return
221
+ const event = rawEvent as V2AfterEvent
222
+ const tool = text(event.tool)
223
+ const payload = basePayload(event)
224
+ // V1 runs the formatter on every after-event; the script no-ops when the
225
+ // tool call touched no file it recognises.
226
+ await fire(FORMATTER_SCRIPT, payload)
227
+ if (!V2_DELEGATION_TOOL_RE.test(tool)) return
228
+ const callID = text(event.id)
229
+ if (callID === '') {
230
+ // Mirrors the before-hook: no key means no join, so no record.
231
+ warnUnkeyed('execute.after')
232
+ return
233
+ }
234
+ const start = starts.get(callID)
235
+ starts.delete(callID)
236
+ const taskID = extractTaskID(event.result)
237
+ await fire(DELEGATION_STOP_SCRIPT, {
238
+ ...payload,
239
+ ...(start === undefined
240
+ ? {
241
+ // No BEFORE record (the call was rejected before the audit ran, or
242
+ // the record was evicted). The STOP still needs a key field to be a
243
+ // well-formed audit line, so it gets a fresh one — an orphan STOP,
244
+ // never an unkeyed one.
245
+ delegation_id: randomUUID(),
246
+ }
247
+ : {
248
+ // The BEFORE-time agent wins: the AFTER-time args may carry the
249
+ // merged background result, which has no subagent_type.
250
+ agent_id: start.agent,
251
+ delegation_id: start.delegationId,
252
+ duration_ms: Math.max(0, now() - start.startedAt),
253
+ }),
254
+ status: delegationStatus(event),
255
+ tool_output: event.result ?? null,
256
+ ...(taskID === '' ? {} : { task_id: taskID }),
257
+ })
258
+ },
259
+ }
260
+ }
@@ -68,11 +68,39 @@ export const V2_UNSUPPORTED_FEATURE_SEED = Object.freeze([
68
68
  // transform, which a live 2.0.22 host does provide.
69
69
  'skill-transform',
70
70
  // Adapter limitation, not a host gap: the goal loop needs a GoalStore, a
71
- // GoalLoopClient and a BackgroundJobBoard, none of which the V2
72
- // PluginContext exposes, and the V1 bridge resolves to null outside V1.
73
- // pantheon_goal_create/get/update are therefore absent from the V2 surface
74
- // rather than registered as non-functional placeholders.
71
+ // GoalLoopClient and a BackgroundJobBoard. V2 has no `client` to build the
72
+ // loop's session calls, and the bridge the V2 entry injects deliberately
73
+ // carries the board and the todo enforcer only, so
74
+ // pantheon_goal_create/get/update stay absent from the V2 surface rather
75
+ // than being registered as non-functional placeholders.
75
76
  'goal-tools',
77
+ // CONDITIONAL reduction (issue #265/#267): the V2 entry DOES construct the
78
+ // V1 TodoEnforcer and inject it through the bridge, but only when the host's
79
+ // `session` domain exposes the four methods the enforcer uses (`todo`,
80
+ // `messages`, `children`, `promptAsync`). The measured 2.1.4 domain exposes
81
+ // `hook`/`get`/`list`/`create`/`remove`/`prompt`/`generate`/… and NOT the
82
+ // four, so on that host idle continuation does not run and the enforcer is
83
+ // not constructed — the limitation is announced here instead of being hidden
84
+ // behind a null bridge. V1 reaches those calls through `client.session`.
85
+ 'idle-todo-enforcer',
86
+ // Todo preservation across compaction (`todo-preserve.ts`): V1 captures the
87
+ // session's todo list in `experimental.session.compacting`, activates the
88
+ // snapshot on `session.compacted` and rewrites the first post-compaction
89
+ // `todowrite`. V2 has no todo API to capture from, so the snapshot is absent
90
+ // and the first `todowrite` is not rewritten.
91
+ 'todo-restore',
92
+ // The `<tool_ceiling>` block fed by `handleToolCeilingEvent` on V1
93
+ // (`message.updated`). V2's event route handles session.* events only, so
94
+ // there is no producer for the host-reported remaining context budget and
95
+ // the block is not injected into the compaction context.
96
+ 'tool-ceiling',
97
+ // BackgroundJobBoard bookkeeping: the shared board INSTANCE is reachable on
98
+ // V2 through the injected bridge, but the transitions that make it useful
99
+ // (onTerminal audit line, terminal reports on session.idle, dispatch mirror
100
+ // for native background tasks) are driven from V1's event hook and from
101
+ // pantheon-hooks.ts, neither of which a V2-only install loads. The board is
102
+ // present; nothing on V2 writes to it.
103
+ 'board-transitions',
76
104
  ])
77
105
 
78
106
  /**
@@ -10,6 +10,7 @@ import { homedir } from 'node:os'
10
10
  import { join, resolve } from 'node:path'
11
11
  import { fileURLToPath } from 'node:url'
12
12
  import { resolveActivePreset } from './presets.mjs'
13
+ import { isValidSessionId } from './session-guard.ts'
13
14
  import {
14
15
  describeImagesNative,
15
16
  NATIVE_MAX_TOKENS,
@@ -93,10 +94,10 @@ function imageReference(uri: string, mime: string, name: string): string {
93
94
  * tool's `prompt`. NOTE: the description cache keys on the full prompt, so the
94
95
  * same image asked with a new question gets a fresh describe — same image +
95
96
  * same question within the TTL reuses the stored description.
96
- * `sessionID` (the V2 `prompt` hook event's live session id, when present) is
97
- * relayed as an MCP `session_id` instruction: the MCP runs in a separate
98
- * process the host hands no session id to, and the Zen gateway rejects a
99
- * sessionless call with HTTP 400 `MissingSessionID` (mirrors
97
+ * `sessionID` (the V2 `prompt` hook event's live session id, when valid under
98
+ * the host session guard) is relayed as an MCP `session_id` instruction: the
99
+ * MCP runs in a separate process the host hands no session id to, and the Zen
100
+ * gateway rejects a sessionless call with HTTP 400 `MissingSessionID` (mirrors
100
101
  * `generateInjectionPrompt` on the V1 path).
101
102
  * The question and the session id are never logged.
102
103
  */
@@ -144,10 +145,9 @@ export function buildV2VisionPromptContext(
144
145
  }
145
146
  // MCP session relay (see the doc comment above): JSON.stringify quotes the
146
147
  // id so it cannot spoof the surrounding instruction layout; never logged.
147
- const session = sessionID?.trim()
148
- if (session) {
148
+ if (isValidSessionId(sessionID)) {
149
149
  lines.push(
150
- `Prefira a ferramenta nativa \`vision_describe\` (ela já repassa a sessão automaticamente). Se usar o MCP pantheon-vision (\`vision_describe\`/\`vision_ocr\`/\`vision_analyze\`), repasse session_id=${JSON.stringify(session)} no parâmetro \`session_id\` — sem ele o gateway Zen rejeita a chamada com MissingSessionID.`,
150
+ `Prefira a ferramenta nativa \`vision_describe\` (ela já repassa a sessão automaticamente). Se usar o MCP pantheon-vision (\`vision_describe\`/\`vision_ocr\`/\`vision_analyze\`), repasse session_id=${JSON.stringify(sessionID)} no parâmetro \`session_id\` — sem ele o gateway Zen rejeita a chamada com MissingSessionID.`,
151
151
  )
152
152
  }
153
153
  return lines.join('\n')
@@ -241,14 +241,11 @@ function exactModelMatch(models: V2VisionModel[], requested: string): V2VisionMo
241
241
  }
242
242
 
243
243
  /**
244
- * Select a native transport model. An EXPLICIT pin (`preferred` — the env
245
- * `PANTHEON_VISION_MODEL`, the config file, or the active preset) ALWAYS wins,
246
- * even when it names a free-tier model: the pin is the user's decision, so the
247
- * call surfaces the gateway's HTTP 403 with its actionable message instead of
248
- * silently substituting a different model. The free-tier exclusion
249
- * (`-free` suffix / cost ≤ 0) applies ONLY to AUTOMATIC selection — discovery
250
- * then the Go default — because the direct gateway rejects free-tier models
251
- * with HTTP 403, so they cannot serve the native describe path unasked.
244
+ * Select a native transport model. An explicit pin must be eligible for the
245
+ * native Zen image path or selection fails; it is never silently substituted.
246
+ * Free-tier exclusion (`-free` suffix / cost ≤ 0) applies only to automatic
247
+ * discovery, preserving the user's choice when a free model is explicitly
248
+ * pinned (the gateway can then return its actionable 403).
252
249
  */
253
250
  export function selectV2VisionModel(
254
251
  available: unknown,
@@ -263,8 +260,7 @@ export function selectV2VisionModel(
263
260
  )
264
261
  const pinned = preferred?.trim()
265
262
  if (pinned) {
266
- const configured = exactModelMatch(capable, pinned)
267
- if (configured) return configured
263
+ return exactModelMatch(capable, pinned)
268
264
  }
269
265
  const candidates = capable.filter((model) => !isFreeVisionModel(model))
270
266
  const defaultModel = exactModelMatch(candidates, DEFAULT_MODEL)
@@ -314,21 +310,19 @@ async function configuredVisionModel(directory: string): Promise<string | undefi
314
310
  return undefined
315
311
  }
316
312
 
317
- async function preferredVisionModel(directory: string): Promise<string> {
313
+ async function preferredVisionModel(directory: string): Promise<string | undefined> {
318
314
  const envModel = process.env.PANTHEON_VISION_MODEL?.trim()
319
315
  if (envModel) return envModel
320
316
  const configModel = await configuredVisionModel(directory)
321
317
  if (configModel) return configModel
322
318
  try {
323
- return (
324
- resolveActivePreset({
325
- env: process.env,
326
- candidates: activePresetCandidates(directory),
327
- logger: { warn: () => undefined },
328
- })?.vision?.model ?? DEFAULT_MODEL
329
- )
319
+ return resolveActivePreset({
320
+ env: process.env,
321
+ candidates: activePresetCandidates(directory),
322
+ logger: { warn: () => undefined },
323
+ })?.vision?.model
330
324
  } catch {
331
- return DEFAULT_MODEL
325
+ return undefined
332
326
  }
333
327
  }
334
328
 
@@ -551,17 +545,28 @@ export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefini
551
545
  },
552
546
  output: {},
553
547
  execute: async (input, rawContext) => {
554
- let stage = 'load image'
548
+ let stage = 'validate OpenCode session'
555
549
  try {
556
- const pathValue = typeof input.path === 'string' ? input.path : ''
557
550
  const call = (asRecord(rawContext) ?? {}) as V2VisionToolContext
551
+ if (!isValidSessionId(call.sessionID)) {
552
+ throw new Error(
553
+ 'a valid OpenCode session id is required; retry this tool from an active OpenCode session',
554
+ )
555
+ }
556
+ const pathValue = typeof input.path === 'string' ? input.path : ''
558
557
  const directory = call.directory || process.cwd()
558
+ stage = 'load image'
559
559
  const image = await imageAttachment(pathValue, directory, call.signal)
560
560
  stage = 'read model catalog'
561
561
  const preferred = await preferredVisionModel(directory)
562
562
  const catalog = await runtime.model.list()
563
563
  const model = selectV2VisionModel(catalog, preferred)
564
564
  if (!model) {
565
+ if (preferred?.trim()) {
566
+ throw new Error(
567
+ `explicitly configured Vision model "${preferred}" is unavailable or ineligible for the native OpenCode Zen image path; update or remove the explicit model pin (PANTHEON_VISION_MODEL, visionModel config, or active preset), or choose an enabled image-capable OpenCode Zen model`,
568
+ )
569
+ }
565
570
  throw new Error(
566
571
  'no available OpenCode Zen multimodal model accepts image input; connect OpenCode Zen and enable an image-capable model',
567
572
  )
@@ -586,7 +591,7 @@ export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefini
586
591
  // header ONLY for Zen targets, never to a non-Zen provider.
587
592
  const requestTarget: NativeVisionTarget = {
588
593
  ...target,
589
- ...(call.sessionID ? { sessionID: call.sessionID } : {}),
594
+ sessionID: call.sessionID,
590
595
  }
591
596
  let failure: NativeVisionFailure | undefined
592
597
  const output = await describeImagesNative(