pantheon-opencode 1.6.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  /**
@@ -2150,11 +2150,16 @@ export function sanitizeVisionHistory(
2150
2150
 
2151
2151
  const raw = value as { type?: unknown; id?: unknown; mime?: unknown }
2152
2152
  const isImageUrl = raw.type === 'image_url'
2153
+ // AI-SDK provider-bound parts use `{ type: 'image', ... }` rather than
2154
+ // the `image_url`/`file` shapes; without this branch such a part reached
2155
+ // the provider untouched, which is the failure this sanitizer exists to
2156
+ // prevent.
2157
+ const isImagePart = raw.type === 'image'
2153
2158
  const isImageFile =
2154
2159
  raw.type === 'file' &&
2155
2160
  typeof raw.mime === 'string' &&
2156
2161
  raw.mime.toLowerCase().startsWith('image/')
2157
- if (isImageUrl || isImageFile) {
2162
+ if (isImageUrl || isImagePart || isImageFile) {
2158
2163
  const partID = typeof raw.id === 'string' ? raw.id : ''
2159
2164
  const text =
2160
2165
  descriptions?.get(partID) ??