@bridgebrew/harness-opencode 0.0.0-stage → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.ts ADDED
@@ -0,0 +1,1611 @@
1
+ // The `opencode` driver (AD-28): runs OpenCode 2 (`@opencode/cli`, 2.0.18 or newer) as `opencode serve --stdio`, one
2
+ // server per session, started by the host (`processes`, AD-27), and speaks its HTTP API and event stream (./api.ts).
3
+ // Partly adapted from an MIT-licensed OpenCode 2 adapter (THIRD_PARTY_NOTICES, research-032), in plain
4
+ // TypeScript; OpenCode 1.x is not supported (its API is another).
5
+ //
6
+ // A session is one server and one OpenCode session: the server prints its URL (`{"url":…}`) on its first stdout line and
7
+ // takes the password the driver put in `OPENCODE_PASSWORD`. The driver subscribes to `/api/event` first (the stream is
8
+ // global and nothing is replayed), then loads the stored session (`GET /api/session/<resume>`; a session OpenCode no
9
+ // longer has opens fresh, `resumed` false) or creates one in the folder with the model and the permission rules of the
10
+ // mode, and registers the session's MCP servers on that server. Each turn is a `prompt`; it ends on the session's next
11
+ // `session.execution.succeeded|failed|interrupted`. Text and reasoning stream per delta, an `…ended` fills in what did
12
+ // not stream; tool calls go from `tool.input.started` to `tool.success|failed`, a step's tokens are the usage. A level is
13
+ // a set of session rules (`shell`, `edit`, `external_directory`: ask, allow or deny; God allows `*`), with the MCP
14
+ // servers' tools after them (`<server>_<tool>`, OpenCode's action for an MCP tool); Plan is OpenCode's `plan` agent
15
+ // with every edit denied but its plan files. `setMode` rewrites the rules at once, and switches the agent.
16
+ // Sub-agents (bridge#212 S8): until then a subagent's call showed with its answer and its own events stayed in its
17
+ // session; now each session created below ours (`session.created` with a `parentID` in its tree) is a `subagent` event
18
+ // (its id its session's, its title its task's description or its session's title, its agent its session's agent),
19
+ // linked to the `task`/`subagent` call whose progress names its session, its text, reasoning and tool calls naming it,
20
+ // its execution's end its end; `stopSubagent` asks its session's `/interrupt`.
21
+ // Permission asks of the session and of its subagents' sessions become `decision`s: allow (`once`), allow for this
22
+ // session (rules added for the ask's `save` patterns; OpenCode's own `always` would save for the whole project), deny
23
+ // (`reject` with a message, which the model reads); a cancelled decision, or one left open when the turn ends, is a
24
+ // `reject` without a message, which stops the execution. An edit's ask carries its diff: it fills that tool call's
25
+ // `paths` and `diffs`. A question form is one decision of kind `question`, its fields its questions. `interrupt` cancels the decisions,
26
+ // asks `/interrupt`, then closes the session when the turn has not ended `stopMs` later. A lost event stream closes the
27
+ // session (the next `open` resumes it). `steer` posts a `prompt` with `delivery: steer` while a turn runs: OpenCode puts
28
+ // it in the session's inbox and delivers it into the running execution at its next step (`session.inbox.delivered`,
29
+ // its id the one the prompt answered), or starts an execution with it once the running one ended; the turn ends at the
30
+ // end of the execution that took the last one, so what the agent does about it streams to the same turn. Not handled
31
+ // yet: executions OpenCode starts by itself (a background subagent's report: their events are dropped and their
32
+ // asks rejected), fork and rollback, compaction and
33
+ // slash commands, model variants, an external server, reconnecting. An entry may set `command` (default
34
+ // `opencode2`, the name `@opencode/cli` installs beside `opencode`), `args` (flags for `serve`) and `environment` (an
35
+ // isolated OpenCode's XDG folders, say). `status` checks `<command> --version` without a model call.
36
+ import { randomBytes } from 'node:crypto';
37
+ import { readFileSync } from 'node:fs';
38
+ import { resolve } from 'node:path';
39
+ import { pathToFileURL } from 'node:url';
40
+ import { isRecord, listOf } from './json.ts';
41
+ import type { Context } from 'cordis';
42
+ import { ApiError, connect, located, type Api, type Event, type Fetch } from './api.ts';
43
+
44
+ export const name = 'harness-opencode';
45
+ export const inject = ['harness', 'processes'];
46
+
47
+ /** The `harness` contract's driver (`ctx.harness`, typed by the harness plugin; never imported, AD-8). */
48
+ type Driver = Parameters<Context['harness']['register']>[1];
49
+ type Config = Parameters<Driver['capabilities']>[0];
50
+ type McpServer = Parameters<Driver['open']>[0]['mcpServers'][number];
51
+ type Session = Awaited<ReturnType<Driver['open']>>;
52
+ type HarnessEvent = Parameters<Parameters<Session['prompt']>[1]>[0];
53
+ type TurnEnd = Awaited<ReturnType<Session['prompt']>>;
54
+ type Tool = Extract<HarnessEvent, { type: 'tool' }>;
55
+ type Diff = NonNullable<Tool['diffs']>[number];
56
+ type Question = NonNullable<Extract<HarnessEvent, { type: 'decision' }>['questions']>[number];
57
+ /** A question request's answers (the contract's `DecisionAnswers`). */
58
+ type Answers = Exclude<Parameters<Session['answer']>[1], string | null>;
59
+
60
+ /** Whether `answers` fits `questions` as the harness contract says: each question once, its options among its own,
61
+ * several only with `multiSelect`, a text only with `custom` (without `multiSelect`, in place of an option), every
62
+ * required question answered. */
63
+ export const fits = (questions: Question[], answers: Answers) => {
64
+ if (!Array.isArray(answers.answers)) return false;
65
+ const seen = new Set<string>();
66
+ for (const each of answers.answers) {
67
+ const question = questions.find((one) => one.id === each.question);
68
+ if (!question || seen.has(question.id)) return false;
69
+ seen.add(question.id);
70
+ const chosen = each.options ?? [];
71
+ if (chosen.some((id) => !question.options.some((option) => option.id === id))) return false;
72
+ if (new Set(chosen).size !== chosen.length) return false;
73
+ if (chosen.length > 1 && !question.multiSelect) return false;
74
+ if (each.text !== undefined && !question.custom) return false;
75
+ // A single choice is one string in OpenCode's answer: an option's value or the text, never both.
76
+ if (!question.multiSelect && chosen.length && each.text?.trim()) return false;
77
+ }
78
+ return questions.every((question) => {
79
+ if (question.required === false) return true;
80
+ const given = answers.answers.find((each) => each.question === question.id);
81
+ return !!given?.options?.length || !!given?.text?.trim();
82
+ });
83
+ };
84
+ type Model = { id: string; name: string; description?: string; current?: boolean };
85
+ /** Starts a process through the host: the seam tests replace with a scripted server. */
86
+ export type Spawn = (options: {
87
+ command: string;
88
+ args: string[];
89
+ cwd: string;
90
+ env?: Record<string, string>;
91
+ }) => ReturnType<Context['processes']['spawn']>;
92
+ export type { Fetch };
93
+
94
+ /** The four levels, in Bridge's order; OpenCode has no reviewer, so none takes `auto`. */
95
+ type ModeId = 'read-only' | 'ask' | 'build' | 'god';
96
+ type ModeOption = 'plan';
97
+ const MODES: readonly {
98
+ id: ModeId;
99
+ name: string;
100
+ description: string;
101
+ current?: true;
102
+ full?: true;
103
+ readOnly?: true;
104
+ options?: ModeOption[];
105
+ }[] = [
106
+ {
107
+ id: 'read-only',
108
+ name: 'Read-only',
109
+ description: 'Reads only; refuses every change',
110
+ readOnly: true,
111
+ },
112
+ {
113
+ id: 'ask',
114
+ name: 'Ask',
115
+ description: 'Asks before each change to the project or workspace; refuses anything outside',
116
+ options: ['plan'],
117
+ },
118
+ {
119
+ id: 'build',
120
+ name: 'Build',
121
+ description:
122
+ 'Changes the project or workspace without asking; refuses anything outside (shell commands are not confined)',
123
+ current: true,
124
+ options: ['plan'],
125
+ },
126
+ {
127
+ id: 'god',
128
+ name: 'God',
129
+ description: 'Everything, beyond the project or workspace too, without asking',
130
+ full: true,
131
+ options: ['plan'],
132
+ },
133
+ ];
134
+ type Options = NonNullable<Parameters<Driver['open']>[0]['options']>;
135
+
136
+ /** The mode and options an open or a switch asks for; refuses an unknown id or an option the mode does not list. */
137
+ const modeOf = (harness: string, mode: string | undefined, options: Options | undefined) => {
138
+ const found = MODES.find((each) => each.id === (mode ?? 'build'));
139
+ if (!found) throw new Error(`harness ${harness}: OpenCode has no mode ${mode}`);
140
+ const allowed: readonly string[] = found.options ?? [];
141
+ for (const option of Object.keys(options ?? {}))
142
+ if (!allowed.includes(option))
143
+ throw new Error(`harness ${harness}: OpenCode mode ${found.id} has no option ${option}`);
144
+ return { mode: found.id, options: { ...(options ?? {}) } };
145
+ };
146
+
147
+ /** OpenCode's session instructions entry starts with this runtime line. */
148
+ const RUNTIME_INFO =
149
+ "<runtime_info>In case you're asked: you are running in Bridge through the OpenCode harness. No need to mention this otherwise.</runtime_info>";
150
+
151
+ /** The session's `instructions` entry (`PUT …/instructions/entries/bridge`): the runtime line, then the session's
152
+ * `instructions`, then each attached MCP server's `instructions` (a server without one adds nothing), non-empty parts
153
+ * joined by a blank line. */
154
+ const instructionsText = (instructions: string | undefined, servers: McpServer[]) =>
155
+ [RUNTIME_INFO, instructions, ...servers.map((each) => each.instructions)]
156
+ .filter((part): part is string => typeof part === 'string' && part !== '')
157
+ .join('\n\n');
158
+
159
+ /** A permission rule: OpenCode checks the agent's rules, then the session's; the last one that matches decides. */
160
+ export interface Rule {
161
+ action: string;
162
+ resource: string;
163
+ effect: 'allow' | 'deny' | 'ask';
164
+ }
165
+ const rule = (action: string, effect: Rule['effect'], resource = '*'): Rule => ({
166
+ action,
167
+ resource,
168
+ effect,
169
+ });
170
+
171
+ /** The agent a mode runs: the `plan` option is OpenCode's `plan` agent, the others its `build` agent. */
172
+ export const agentOf = (options: Options | undefined) => (options?.plan ? 'plan' : 'build');
173
+
174
+ /** The folders the plan agent may still write (its plan files, `~/.opencode/plan/*`), from its own rules: the blanket
175
+ * `edit deny` and `external_directory ask` of the session would otherwise override them. */
176
+ export const planPathsOf = (agents: unknown): Rule[] => {
177
+ const plan = listOf(agents).find(
178
+ (agent) => isRecord(agent) && (agent.id === 'plan' || agent.name === 'plan'),
179
+ );
180
+ return listOf(isRecord(plan) ? plan.permissions : undefined).flatMap((each) =>
181
+ isRecord(each) &&
182
+ each.action === 'edit' &&
183
+ each.effect === 'allow' &&
184
+ typeof each.resource === 'string' &&
185
+ each.resource !== '*'
186
+ ? [rule('edit', 'allow', each.resource), rule('external_directory', 'allow', each.resource)]
187
+ : [],
188
+ );
189
+ };
190
+
191
+ /** A session's rules for a level and its options: the level's, then each MCP server's
192
+ * tools (`<server>_<tool>`: asked, allowed where the level accepts edits for a server whose tools edit, its `approved`
193
+ * ones always), then the "allow for this session" `grants`; with Plan, every edit denied after them. The plan agent's
194
+ * own folders (`planPaths`, `~/.opencode/plan/*`) are allowed in God only: below God they are outside the session's
195
+ * folder, so no allow rule is added and the driver's `external_directory` rejection applies. Shell and read are never
196
+ * denied: OpenCode's free tier refuses a session whose rules deny them (the driver refuses those asks itself). */
197
+ export const rulesOf = (
198
+ level: ModeId,
199
+ options: Options | undefined,
200
+ servers: McpServer[],
201
+ grants: Rule[] = [],
202
+ planPaths: Rule[] = [],
203
+ readOnly: string[] = [],
204
+ ): Rule[] => {
205
+ const plan = options?.plan ? [rule('edit', 'deny'), ...(level === 'god' ? planPaths : [])] : [];
206
+ if (level === 'god') return [rule('*', 'allow'), ...plan];
207
+ return [
208
+ rule('shell', level === 'build' ? 'allow' : 'ask'),
209
+ rule('edit', level === 'build' ? 'allow' : level === 'read-only' ? 'deny' : 'ask'),
210
+ rule('external_directory', 'ask'),
211
+ ...servers.flatMap((server) => [
212
+ rule(`${server.name}_*`, server.edits && level === 'build' ? 'allow' : 'ask'),
213
+ ...(server.approved ?? []).map((tool) => rule(`${server.name}_${tool}`, 'allow')),
214
+ ]),
215
+ ...(level === 'read-only' ? [] : grants),
216
+ // Read-only folders (the workspace's `.bridge/`, research-061): no edit there below God, even one allowed for the
217
+ // session.
218
+ ...readOnly.map((folder) => rule('edit', 'deny', `${folder}/*`)),
219
+ ...plan,
220
+ ];
221
+ };
222
+
223
+ /** An MCP server as OpenCode 2's config (`PUT /api/experimental/mcp/<name>`): `local` runs a command (its arguments in
224
+ * the same array), `remote` is an HTTP endpoint. Registered on the session's own server, in memory: it goes with it. */
225
+ export const toOpenCode = (server: McpServer) =>
226
+ 'url' in server
227
+ ? {
228
+ type: 'remote' as const,
229
+ url: server.url,
230
+ ...(server.headers && { headers: server.headers }),
231
+ oauth: false,
232
+ }
233
+ : {
234
+ type: 'local' as const,
235
+ command: [server.command, ...server.args],
236
+ ...(server.env && { environment: server.env }),
237
+ };
238
+
239
+ /** `provider/model` as OpenCode's model reference; the model id may itself hold `/` (split at the first one). */
240
+ export const modelRefOf = (model: string) => {
241
+ const cut = model.indexOf('/');
242
+ if (cut <= 0 || cut === model.length - 1)
243
+ throw new Error(`OpenCode model ${model} must be written provider/model`);
244
+ return { providerID: model.slice(0, cut), id: model.slice(cut + 1) };
245
+ };
246
+
247
+ /** `--version`'s answer (`opencode v2.0.29` on 2.x, `1.19.0` on 1.x) as numbers. */
248
+ export const versionOf = (output: string): [number, number, number] | undefined => {
249
+ const found = /(\d+)\.(\d+)\.(\d+)/.exec(output);
250
+ return found ? [Number(found[1]), Number(found[2]), Number(found[3])] : undefined;
251
+ };
252
+ const MINIMUM: [number, number, number] = [2, 0, 18];
253
+ const older = (a: [number, number, number], b: [number, number, number]) =>
254
+ a[0] !== b[0] ? a[0] < b[0] : a[1] !== b[1] ? a[1] < b[1] : a[2] < b[2];
255
+
256
+ /** How long a setup request may take, how long the server has to print its URL, and how long a turn has to end after
257
+ * `interrupt` before its session is closed (also how long `close` waits for the exit).
258
+ * ponytail: driver constants; a harness setting if a machine needs more. */
259
+ const DEADLINES = { requestMs: 30_000, startMs: 30_000, stopMs: 10_000 };
260
+ /** Waits for `exited`, or `ms` at most; the timer is cleared once it exits, so it never keeps a stopping worker busy. */
261
+ const exitedWithin = async (exited: Promise<unknown>, ms: number) => {
262
+ let timer: ReturnType<typeof setTimeout> | undefined;
263
+ try {
264
+ await Promise.race([exited, new Promise((resolve) => (timer = setTimeout(resolve, ms)))]);
265
+ } finally {
266
+ clearTimeout(timer);
267
+ }
268
+ };
269
+ /** How long a status check waits for `--version`. */
270
+ const STATUS_MS = 15_000;
271
+ /** How long a model list is kept, per entry setup. */
272
+ const MODELS_TTL_MS = 5 * 60_000;
273
+ /** A server started a moment ago lists no models yet: read again this often, this long. */
274
+ const CATALOG_RETRY = { everyMs: 250, forMs: 5_000 };
275
+ /** The longest `setTimeout` delay (2^31 - 1 ms); a longer one fires at once. */
276
+ const TIMEOUT_MAX = 2_147_483_647;
277
+ /** What a declined ask tells the model (it reads it as `permission.rejected`). */
278
+ const DECLINED = 'The user declined this request.';
279
+ const LATE = 'The user did not answer in time.';
280
+ const READ_ONLY = 'Read-only: this session only reads.';
281
+ const OUTSIDE = "Outside this session's project or workspace: only God may go there.";
282
+ const EXPIRED = Symbol('expired');
283
+
284
+ /** The entry's `environment` as variables, the well-formed names only, later ones winning. */
285
+ export const environmentOf = (entries: unknown): Record<string, string> =>
286
+ Object.fromEntries(
287
+ listOf(entries).flatMap((each) =>
288
+ isRecord(each) &&
289
+ typeof each.name === 'string' &&
290
+ /^[A-Za-z_][A-Za-z0-9_]*$/.test(each.name) &&
291
+ typeof each.value === 'string'
292
+ ? [[each.name, each.value]]
293
+ : [],
294
+ ),
295
+ );
296
+
297
+ /** How an entry starts `opencode serve`: its command, extra flags and environment. Throws for a malformed entry. */
298
+ const setupOf = (harness: string, config: Config) => {
299
+ const command = config.command ?? 'opencode2';
300
+ if (typeof command !== 'string' || !command)
301
+ throw new Error(
302
+ `harness ${harness}: command must be the path or name of the opencode executable`,
303
+ );
304
+ const args = config.args ?? [];
305
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== 'string'))
306
+ throw new Error(`harness ${harness}: args must be a list of strings`);
307
+ return {
308
+ command,
309
+ args: ['serve', ...(args as string[]), '--stdio', '--port', '0', '--hostname', '127.0.0.1'],
310
+ env: environmentOf(config.environment),
311
+ };
312
+ };
313
+ type Setup = ReturnType<typeof setupOf>;
314
+
315
+ const str = (value: unknown) => (typeof value === 'string' && value !== '' ? value : undefined);
316
+ /** `value` as an object whose fields are read one by one, or an empty one when it is not an object. */
317
+ const recordOf = (value: unknown): Record<string, unknown> => (isRecord(value) ? value : {});
318
+ /** An HTTP answer's `data` (its payload) as an object, or an empty one. */
319
+ const dataOf = (answer: unknown) => recordOf(recordOf(answer).data);
320
+ const pathIn = (input: unknown) => {
321
+ const given = recordOf(input);
322
+ return str(given.filePath) ?? str(given.path) ?? str(given.file);
323
+ };
324
+
325
+ /** The edits of one file of an edit's ask (`metadata.files[]`: `{file, patch, status}`): each hunk of its unified diff
326
+ * with its context lines; an added file's new text alone. */
327
+ export const diffsOf = (file: unknown): Diff[] => {
328
+ const given = recordOf(file);
329
+ const path = str(given.file);
330
+ if (!path || typeof given.patch !== 'string') return [];
331
+ const hunks: string[][] = [];
332
+ for (const line of given.patch.split('\n')) {
333
+ if (line.startsWith('@@')) hunks.push([]);
334
+ else if (hunks.length && !line.startsWith('\\')) hunks.at(-1)!.push(line);
335
+ }
336
+ const added = given.status === 'added';
337
+ return hunks.map((lines) => {
338
+ const side = (mark: string) =>
339
+ lines
340
+ .filter((line) => line[0] === ' ' || line[0] === mark)
341
+ .map((line) => line.slice(1))
342
+ .join('\n');
343
+ return added ? { path, newText: side('+') } : { path, oldText: side('-'), newText: side('+') };
344
+ });
345
+ };
346
+
347
+ /** A tool call as Bridge shows it, from its OpenCode name and input. */
348
+ export const toolOf = (id: string, name: string, input: unknown, status: Tool['status']): Tool => {
349
+ const base = { type: 'tool' as const, id, status, ...(input !== undefined && { input }) };
350
+ const given = recordOf(input);
351
+ const tool = name.toLowerCase();
352
+ const path = pathIn(input);
353
+ if (tool === 'shell' || tool === 'bash')
354
+ return { ...base, title: str(given.command) ?? 'Command', kind: 'execute' };
355
+ if (['edit', 'write', 'patch', 'apply_patch', 'multiedit'].includes(tool)) {
356
+ const oldText = typeof given.oldString === 'string' ? given.oldString : undefined;
357
+ const newText = typeof given.newString === 'string' ? given.newString : undefined;
358
+ return {
359
+ ...base,
360
+ title: path ? `Edit ${path}` : 'Edit',
361
+ kind: 'edit',
362
+ ...(path && { paths: [path] }),
363
+ ...(path &&
364
+ oldText !== undefined &&
365
+ newText !== undefined && { diffs: [{ path, oldText, newText }] }),
366
+ };
367
+ }
368
+ if (tool === 'read') return { ...base, title: path ? `Read ${path}` : 'Read', kind: 'read' };
369
+ if (['glob', 'grep', 'search', 'list', 'ls', 'lsp'].includes(tool)) {
370
+ const what = str(given.pattern) ?? str(given.query) ?? path;
371
+ return { ...base, title: what ? `${name} ${what}` : name, kind: 'search' };
372
+ }
373
+ if (tool.includes('web') || tool === 'codesearch' || tool === 'fetch') {
374
+ const what = str(given.query) ?? str(given.url);
375
+ return { ...base, title: what ? `${name} ${what}` : name, kind: 'fetch' };
376
+ }
377
+ if (tool === 'subagent' || tool === 'task') {
378
+ const description = str(given.description);
379
+ return {
380
+ ...base,
381
+ title: `Subagent${description ? `: ${description}` : ''}`,
382
+ kind: 'other',
383
+ };
384
+ }
385
+ if (tool === 'execute') return { ...base, title: 'Run code', kind: 'other' };
386
+ return { ...base, title: name, kind: 'other' };
387
+ };
388
+
389
+ /** A finished call's output: its text parts, a subagent's answer without the `<subagent …>` wrapper. */
390
+ const outputOf = (content: unknown) => {
391
+ const text = listOf(content)
392
+ .flatMap((part) =>
393
+ isRecord(part) && part.type === 'text' && typeof part.text === 'string' ? [part.text] : [],
394
+ )
395
+ .join('\n');
396
+ return /^<subagent\b[^>]*>\n?([\s\S]*?)\n?<\/subagent>$/.exec(text.trim())?.[1] ?? text;
397
+ };
398
+
399
+ /** How a call that ran ends: `failed` when it failed, or when it ran a command that exited non-zero (`metadata.exit`
400
+ * or `exitCode`: OpenCode reports a shell's exit code as a success). */
401
+ const endOf = (type: string, metadata: unknown) => {
402
+ const { exit, exitCode } = recordOf(metadata);
403
+ const exited = [exit, exitCode].some((code) => typeof code === 'number' && code !== 0);
404
+ return type === 'session.tool.success' && !exited ? 'completed' : 'failed';
405
+ };
406
+
407
+ /** An ask's title: the command for a shell, the files for an edit, the folder for another directory, else the action
408
+ * (an MCP tool's is `<server>_<tool>`) and what it names. */
409
+ export const askTitle = (action: string, resources: string[]) => {
410
+ const named = resources.filter((each) => each !== '*');
411
+ if (action === 'shell') return named.join('\n') || 'Run a command';
412
+ if (action === 'edit') return named.length ? `Edit ${named.join(', ')}` : 'Edit files';
413
+ if (action === 'external_directory')
414
+ return named.length ? `Access ${named.join(', ')}` : 'Access files outside the folder';
415
+ if (action === 'read') return named.length ? `Read ${named.join(', ')}` : 'Read files';
416
+ return named.length ? `${action}: ${named.join(', ')}` : `Run ${action}`;
417
+ };
418
+
419
+ /** The stderr tail an error message carries: its last lines. */
420
+ const tailOf = (stderr: string) => {
421
+ const lines = stderr
422
+ .replace(/\x1b\[[0-9;]*m/g, '')
423
+ .split('\n')
424
+ .map((line) => line.trim())
425
+ .filter(Boolean)
426
+ .slice(-5)
427
+ .join(' | ');
428
+ return lines ? `: ${lines}` : '';
429
+ };
430
+
431
+ /** The line of a failed command's error output that says why: the last error Node or the CLI printed (`Error: …`,
432
+ * `TypeError [ERR_…]: …`, `error: …`), else the last line that is neither a stack frame nor Node's `Node.js v…` line,
433
+ * else its last line. Node prints its version after the error, which alone tells nothing. */
434
+ const failureOf = (stderr: string) => {
435
+ const lines = stderr
436
+ .trim()
437
+ .split('\n')
438
+ .map((line) => line.trim());
439
+ return (
440
+ lines.findLast((line) => /^(?:Uncaught )?(?:\w*Error|error)(?: \[\w+\])?: /.test(line)) ??
441
+ lines.findLast((line) => line !== '' && !/^at /.test(line) && !/^Node\.js v\d/.test(line)) ??
442
+ lines.at(-1) ??
443
+ ''
444
+ );
445
+ };
446
+
447
+ /** Runs `command args` through `spawn` to its end, or `ms` (then killed): its exit code (null when killed) and output. */
448
+ const runToEnd = async (spawn: Spawn, options: Parameters<Spawn>[0], ms: number) => {
449
+ const handle = await spawn(options);
450
+ let stdout = '';
451
+ let stderr = '';
452
+ handle.onOutput((stream, chunk) => {
453
+ if (stream === 'stdout') stdout += chunk;
454
+ else stderr += chunk;
455
+ });
456
+ let timer: ReturnType<typeof setTimeout> | undefined;
457
+ const late = new Promise<null>((resolve) => {
458
+ timer = setTimeout(() => resolve(null), ms);
459
+ });
460
+ const ended = await Promise.race([handle.exited, late]);
461
+ clearTimeout(timer);
462
+ if (ended === null) await handle.kill();
463
+ return { code: ended?.code ?? null, stdout, stderr };
464
+ };
465
+
466
+ /** `spawn` starts a process through the host, `fetch` reaches the server it starts (tests pass scripted ones).
467
+ * `disposing` tells whether this plugin is disposing: a turn its server's exit ends is then `interrupted`. `log`: the
468
+ * plugin's `ctx.logger` (AD-21). */
469
+ export const opencodeDriver = ({
470
+ spawn,
471
+ fetch = globalThis.fetch as Fetch,
472
+ disposing = () => false,
473
+ deadlines: { requestMs, startMs, stopMs } = DEADLINES,
474
+ catalog = CATALOG_RETRY,
475
+ log = console,
476
+ }: {
477
+ spawn: Spawn;
478
+ fetch?: Fetch;
479
+ disposing?: () => boolean;
480
+ deadlines?: { requestMs: number; startMs: number; stopMs: number };
481
+ catalog?: { everyMs: number; forMs: number };
482
+ log?: { error: (...args: unknown[]) => void };
483
+ }): Driver => {
484
+ /** Configs whose `decisionTimeoutMs` was refused, said once each. */
485
+ const warned = new Set<string>();
486
+ /** Model lists by entry setup, with when they were read; a pending read is shared. */
487
+ const listed = new Map<string, { at: number; models: Promise<Model[]> }>();
488
+
489
+ /** Starts `opencode serve --stdio` in `cwd` with a fresh password, and connects once it printed its URL. Its stdout
490
+ * and stderr keep being read (a full pipe would block it); `stderr()` is the tail, for error messages. */
491
+ const start = async (setup: Setup, cwd: string, env: Record<string, string>) => {
492
+ const password = randomBytes(32).toString('base64url');
493
+ const handle = await spawn({
494
+ command: setup.command,
495
+ args: setup.args,
496
+ cwd,
497
+ env: { ...setup.env, ...env, OPENCODE_PASSWORD: password },
498
+ });
499
+ let stdout = '';
500
+ let stderr = '';
501
+ /** Its first stdout line is its address; the rest is the server's own to say. */
502
+ let first = true;
503
+ let found: (url: string) => void = () => {};
504
+ const url = new Promise<string>((resolve) => {
505
+ found = resolve;
506
+ });
507
+ handle.onOutput((stream, chunk) => {
508
+ if (stream === 'stderr') {
509
+ stderr = (stderr + chunk).slice(-4096);
510
+ return;
511
+ }
512
+ if (!first) return;
513
+ stdout += chunk;
514
+ const cut = stdout.indexOf('\n');
515
+ if (cut < 0) return;
516
+ first = false;
517
+ try {
518
+ const said: unknown = JSON.parse(stdout.slice(0, cut));
519
+ if (isRecord(said) && typeof said.url === 'string') found(said.url);
520
+ } catch {}
521
+ });
522
+ let timer: ReturnType<typeof setTimeout> | undefined;
523
+ const ended = await Promise.race([
524
+ url,
525
+ handle.exited.then(
526
+ ({ code, signal }) => new Error(`it exited (${signal ?? `code ${code}`})`),
527
+ ),
528
+ new Promise<Error>((resolve) => {
529
+ timer = setTimeout(
530
+ () => resolve(new Error(`it gave no address within ${startMs / 1000} s`)),
531
+ startMs,
532
+ );
533
+ }),
534
+ ]);
535
+ clearTimeout(timer);
536
+ if (ended instanceof Error) {
537
+ void handle.kill();
538
+ throw new Error(`OpenCode's server did not start: ${ended.message}${tailOf(stderr)}`);
539
+ }
540
+ return {
541
+ handle,
542
+ api: connect({ url: ended, password, fetch, requestMs }),
543
+ stderr: () => stderr,
544
+ };
545
+ };
546
+
547
+ /** Reads `path` (a catalog: models) until it lists something or `catalog.forMs` passed. A server still warming up
548
+ * answers 503: read again like an empty list, within the same deadline. */
549
+ const catalogOf = async (api: Api, path: string) => {
550
+ const until = Date.now() + catalog.forMs;
551
+ for (;;) {
552
+ const read = await api.get(path).catch((error: unknown) => {
553
+ if (error instanceof ApiError && error.status === 503) return error;
554
+ throw error;
555
+ });
556
+ const data = isRecord(read) ? listOf(read.data) : [];
557
+ if (data.length) return data;
558
+ if (Date.now() >= until) {
559
+ if (read instanceof ApiError) throw read; // still warming up past the deadline: not an empty catalog
560
+ return data;
561
+ }
562
+ await new Promise((resolve) => setTimeout(resolve, catalog.everyMs));
563
+ }
564
+ };
565
+
566
+ const driver: Driver = {
567
+ name: 'opencode',
568
+ capabilities: () => ({ resume: true, images: true, models: true, modes: true, steer: true }),
569
+ // `GET /api/model` from a throwaway server (its default marked current), kept `MODELS_TTL_MS` per setup. A list that
570
+ // cannot be read is empty (and not kept): the entry's custom models still show.
571
+ async models({ harness, config, cwd }) {
572
+ let setup: Setup;
573
+ try {
574
+ setup = setupOf(harness, config);
575
+ } catch {
576
+ return [];
577
+ }
578
+ const key = JSON.stringify(setup);
579
+ const known = listed.get(key);
580
+ if (known && Date.now() - known.at < MODELS_TTL_MS) return known.models;
581
+ const models = (async () => {
582
+ const server = await start(setup, cwd, {});
583
+ try {
584
+ const where = located(cwd);
585
+ const all = await catalogOf(server.api, `/api/model?${where}`);
586
+ const preferred = await server.api
587
+ .get(`/api/model/default?${where}`)
588
+ .catch(() => undefined);
589
+ const current =
590
+ isRecord(preferred) && isRecord(preferred.data)
591
+ ? `${preferred.data.providerID}/${preferred.data.id}`
592
+ : undefined;
593
+ return all.flatMap((each) => {
594
+ if (!isRecord(each)) return [];
595
+ const { id, providerID } = each;
596
+ if (typeof id !== 'string' || typeof providerID !== 'string') return [];
597
+ if (each.enabled === false || each.status === 'deprecated') return [];
598
+ const reference = `${providerID}/${id}`;
599
+ return [
600
+ {
601
+ id: reference,
602
+ name: `${str(each.name) ?? id} (${providerID})`,
603
+ ...(reference === current && { current: true }),
604
+ },
605
+ ];
606
+ });
607
+ } finally {
608
+ void server.handle.kill();
609
+ }
610
+ })();
611
+ listed.set(key, { at: Date.now(), models });
612
+ try {
613
+ return await models;
614
+ } catch (error) {
615
+ listed.delete(key);
616
+ log.error(`harness ${harness}: OpenCode's models could not be listed`, error);
617
+ return [];
618
+ }
619
+ },
620
+ modes: async () =>
621
+ MODES.map(({ id, name, description, current, full, readOnly, options }) => ({
622
+ id,
623
+ name,
624
+ description,
625
+ ...(current !== undefined && { current }),
626
+ ...(full !== undefined && { full }),
627
+ ...(readOnly !== undefined && { readOnly }),
628
+ ...(options !== undefined && { options: [...options] }),
629
+ })),
630
+ // `command --version` in the entry's environment: OpenCode 2 (2.0.18 or newer) is what this driver speaks.
631
+ async status({ config, cwd }) {
632
+ const command =
633
+ typeof config.command === 'string' && config.command ? config.command : 'opencode2';
634
+ const ran = await runToEnd(
635
+ spawn,
636
+ { command, args: ['--version'], cwd, env: environmentOf(config.environment) },
637
+ STATUS_MS,
638
+ );
639
+ const said = ran.stdout.trim().split('\n')[0]?.trim();
640
+ const version = said ? versionOf(said) : undefined;
641
+ if (ran.code !== 0 || !said || !version) {
642
+ const why = failureOf(ran.stderr);
643
+ return {
644
+ installed: false,
645
+ message: `${command} --version ${ran.code === null ? 'did not answer' : 'failed'}${why ? `: ${why}` : ''}`,
646
+ fix: 'Install OpenCode 2 (npm install -g @opencode/cli, which installs opencode2), or set Command to the path of the OpenCode 2 executable.',
647
+ };
648
+ }
649
+ const known = { installed: true as const, version: said };
650
+ if (version[0] < 2)
651
+ return {
652
+ ...known,
653
+ message: `${command} is OpenCode ${version.join('.')}: this driver needs OpenCode 2.`,
654
+ fix: 'Install OpenCode 2 (npm install -g @opencode/cli) and set Command to opencode2.',
655
+ };
656
+ if (older(version, MINIMUM))
657
+ return {
658
+ ...known,
659
+ message: `OpenCode ${version.join('.')} is older than ${MINIMUM.join('.')}.`,
660
+ fix: `${command} upgrade`,
661
+ };
662
+ return known;
663
+ },
664
+ async open({
665
+ harness,
666
+ config,
667
+ cwd,
668
+ model,
669
+ mode,
670
+ options,
671
+ mcpServers,
672
+ resume,
673
+ env: agentEnv,
674
+ instructions,
675
+ readOnly = [],
676
+ }) {
677
+ const initial = modeOf(harness, mode, options);
678
+ const setup = setupOf(harness, config);
679
+ const reference = model !== undefined ? modelRefOf(model) : undefined;
680
+ const raw = config.decisionTimeoutMs;
681
+ const valid = typeof raw === 'number' && Number.isFinite(raw) && raw > 0;
682
+ if (raw !== undefined && !valid && !warned.has(JSON.stringify(config))) {
683
+ warned.add(JSON.stringify(config));
684
+ log.error(
685
+ `harness ${harness}: decisionTimeoutMs must be a positive number of milliseconds, got ${JSON.stringify(raw) ?? String(raw)}; decisions wait without a timeout`,
686
+ );
687
+ }
688
+ const timeout = valid ? Math.min(raw, TIMEOUT_MAX) : undefined;
689
+
690
+ let currentMode: ModeId = initial.mode;
691
+ let currentOptions: Options = initial.options;
692
+ /** "Allow for this session" answers, as rules after the mode's. */
693
+ const grants: Rule[] = [];
694
+ /** The plan agent's own folders, read once from the server when a Plan session needs them. */
695
+ let planPaths: Promise<Rule[]> | undefined;
696
+ const rules = async () =>
697
+ rulesOf(
698
+ currentMode,
699
+ currentOptions,
700
+ mcpServers,
701
+ grants,
702
+ currentMode === 'god' && currentOptions.plan
703
+ ? await (planPaths ??= catalogOf(api, `/api/agent?${located(cwd)}`)
704
+ .then(planPathsOf)
705
+ .catch(() => []))
706
+ : [],
707
+ readOnly,
708
+ );
709
+ let sessionId = '';
710
+ /** The session and its subagents' sessions (whose `parentID` chain reaches it). */
711
+ const tree = new Set<string>();
712
+ /** The running turn: its listener, tool calls by id (with their OpenCode name), the blocks whose text streamed,
713
+ * and whether `interrupt` asked it to stop. */
714
+ let turn:
715
+ | {
716
+ onEvent: (event: HarnessEvent) => void;
717
+ done: (end: TurnEnd) => void;
718
+ tools: Map<string, Tool & { name: string }>;
719
+ streamed: Set<string>;
720
+ stopping: boolean;
721
+ /** Its steered messages not delivered yet: their inbox ids, and the posts not answered yet. */
722
+ steering: Set<string>;
723
+ posting: number;
724
+ /** The inbox ids delivered during it (one may be delivered before its post answers). */
725
+ delivered: Set<string>;
726
+ /** The execution ended while a steered message waited: the turn ends with the execution that takes it. */
727
+ idle?: TurnEnd;
728
+ }
729
+ | undefined;
730
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
731
+ let closed = false;
732
+ /** Open decisions by id: how to settle them, the option ids offered, and the ask or form they answer. */
733
+ const decisions = new Map<
734
+ string,
735
+ {
736
+ settle: (choice: string | Answers | null | typeof EXPIRED) => void;
737
+ offered: Set<string>;
738
+ request: string;
739
+ /** A form's questions: answered with their answers. */
740
+ questions?: Question[];
741
+ }
742
+ >();
743
+ let decided = 0;
744
+ const cancelDecisions = () => {
745
+ for (const { settle } of [...decisions.values()]) settle(null);
746
+ };
747
+
748
+ /** Ends the running turn: its calls still running end with it (`completed` or `failed`). */
749
+ const finish = (end: TurnEnd) => {
750
+ const ending = turn;
751
+ if (!ending) return;
752
+ turn = undefined;
753
+ clearTimeout(stopTimer);
754
+ stopTimer = undefined;
755
+ cancelDecisions();
756
+ for (const { name: _, ...tool } of ending.tools.values()) {
757
+ if (tool.status === 'running' || tool.status === 'pending')
758
+ ending.onEvent({
759
+ ...tool,
760
+ status: end.reason === 'completed' ? 'completed' : 'failed',
761
+ });
762
+ }
763
+ ending.done(end);
764
+ };
765
+ const emit = (event: HarnessEvent) => turn?.onEvent(event);
766
+ const setTool = (tool: Tool & { name: string }) => {
767
+ if (!turn) return;
768
+ turn.tools.set(tool.id, tool);
769
+ const { name: _, ...shown } = tool;
770
+ emit(shown);
771
+ };
772
+
773
+ /** Asks the user; settles with an offered option id, a form's answers, `null` (cancelled, turn ended) or
774
+ * EXPIRED. An approval unless `questions` (a form's) are given. */
775
+ const decide = (
776
+ title: string,
777
+ options: { id: string; label: string; kind: 'allow' | 'deny' | 'other' }[],
778
+ request: string,
779
+ tool?: string,
780
+ questions?: Question[],
781
+ ) =>
782
+ new Promise<string | Answers | null | typeof EXPIRED>((resolve) => {
783
+ if (!turn) return resolve(null);
784
+ const id = `decision-${++decided}`;
785
+ const timer =
786
+ timeout === undefined ? undefined : setTimeout(() => settle(EXPIRED), timeout);
787
+ function settle(choice: string | Answers | null | typeof EXPIRED) {
788
+ if (!decisions.delete(id)) return;
789
+ clearTimeout(timer);
790
+ resolve(choice);
791
+ }
792
+ decisions.set(id, {
793
+ settle,
794
+ offered: new Set(options.map((option) => option.id)),
795
+ request,
796
+ ...(questions !== undefined && { questions }),
797
+ });
798
+ turn.onEvent({
799
+ type: 'decision',
800
+ id,
801
+ title,
802
+ options,
803
+ kind: questions ? 'question' : 'approval',
804
+ ...(questions !== undefined && { questions }),
805
+ ...(timeout !== undefined && {
806
+ expiresAt: new Date(Date.now() + timeout).toISOString(),
807
+ }),
808
+ ...(tool !== undefined && { tool }),
809
+ });
810
+ });
811
+ /** Settles the decisions of ask or form `request` (answered elsewhere, or gone). */
812
+ const withdraw = (request: string) => {
813
+ for (const each of [...decisions.values()]) if (each.request === request) each.settle(null);
814
+ };
815
+
816
+ let server: Awaited<ReturnType<typeof start>>;
817
+ try {
818
+ server = await start(setup, cwd, {
819
+ ...(agentEnv ?? {}),
820
+ });
821
+ } catch (error) {
822
+ throw new Error(
823
+ `harness ${harness}: OpenCode could not start: ${error instanceof Error ? error.message : String(error)}`,
824
+ );
825
+ }
826
+ const { handle, api } = server;
827
+
828
+ /** Replies to ask `ask` of session `session`; a reply OpenCode cannot take is logged, and the turn stopped (it
829
+ * would wait on the ask forever). */
830
+ const reply = (session: string, ask: string, body: { decision: string; message?: string }) =>
831
+ api
832
+ .post(`/api/session/${session}/permission/${ask}/reply`, body)
833
+ .catch((error: unknown) => {
834
+ if (error instanceof ApiError && error.status === 404) return; // gone: settled already
835
+ log.error(`harness ${harness}: OpenCode did not take the answer to ${ask}`, error);
836
+ if (turn && session === sessionId)
837
+ void api.post(`/api/session/${sessionId}/interrupt`).catch(() => {});
838
+ });
839
+
840
+ const onAsk = async (data: unknown) => {
841
+ const request = recordOf(data);
842
+ const session = String(request.sessionID);
843
+ const ask = String(request.id);
844
+ const action = str(request.action) ?? 'permission';
845
+ const resources: string[] = listOf(request.resources).filter(
846
+ (each): each is string => typeof each === 'string',
847
+ );
848
+ const save: string[] = listOf(request.save).filter(
849
+ (each): each is string => typeof each === 'string',
850
+ );
851
+ // Outside a turn (an execution OpenCode started by itself) nobody would answer: stop it.
852
+ if (!turn) return void reply(session, ask, { decision: 'reject' });
853
+ // The level refuses some asks itself, without asking the user (and says why to the model).
854
+ const refused =
855
+ currentMode === 'read-only'
856
+ ? READ_ONLY
857
+ : currentMode !== 'god' && action === 'external_directory'
858
+ ? OUTSIDE
859
+ : undefined;
860
+ if (refused) return void reply(session, ask, { decision: 'reject', message: refused });
861
+ // An edit's ask carries its diff: it goes on the call it is about.
862
+ const files = listOf(recordOf(request.metadata).files);
863
+ const sourceId = str(recordOf(request.source).id);
864
+ const call = sourceId ? turn.tools.get(sourceId) : undefined;
865
+ if (call && files.length) {
866
+ const paths = files
867
+ .map((file) => str(recordOf(file).file))
868
+ .filter((path): path is string => path !== undefined);
869
+ const diffs = files.flatMap(diffsOf);
870
+ setTool({ ...call, ...(paths.length && { paths }), ...(diffs.length && { diffs }) });
871
+ }
872
+ const choice = await decide(
873
+ askTitle(action, resources),
874
+ [
875
+ { id: 'allow', label: 'Allow', kind: 'allow' },
876
+ ...(save.length
877
+ ? [{ id: 'allow_session', label: 'Allow for this session', kind: 'allow' as const }]
878
+ : []),
879
+ { id: 'deny', label: 'Deny', kind: 'deny' },
880
+ ],
881
+ ask,
882
+ call?.id,
883
+ );
884
+ if (choice === 'allow_session') {
885
+ grants.push(...save.map((pattern) => rule(action, 'allow', pattern)));
886
+ const permissions = await rules();
887
+ await Promise.all(
888
+ [...new Set([sessionId, session])].map((each) =>
889
+ api
890
+ .patch(`/api/session/${each}`, { permissions })
891
+ .catch((error: unknown) =>
892
+ log.error(`harness ${harness}: OpenCode did not take the session's rules`, error),
893
+ ),
894
+ ),
895
+ );
896
+ }
897
+ await reply(
898
+ session,
899
+ ask,
900
+ choice === 'allow' || choice === 'allow_session'
901
+ ? { decision: 'once' }
902
+ : choice === 'deny'
903
+ ? { decision: 'reject', message: DECLINED }
904
+ : choice === EXPIRED
905
+ ? { decision: 'reject', message: LATE }
906
+ : { decision: 'reject' },
907
+ );
908
+ };
909
+
910
+ // A question form: one decision with its fields as questions (a string field: one option, or a free text where
911
+ // it has no options or takes a custom one; a multiselect field: several options); a field of another kind (a
912
+ // number, a boolean, a link) or shown on a condition cannot be asked, and cancels the form (which ends the
913
+ // execution).
914
+ const onForm = async (form: unknown) => {
915
+ const asked = recordOf(form);
916
+ const session = String(asked.sessionID);
917
+ const id = String(asked.id);
918
+ const cancel = (message: string) =>
919
+ api
920
+ .delete(`/api/session/${session}/form/${id}?message=${encodeURIComponent(message)}`)
921
+ .catch(() => {});
922
+ if (!turn) return void cancel('Nobody is there to answer.');
923
+ const fields: { key: string; values: string[]; multiple: boolean }[] = [];
924
+ const questions: Question[] = [];
925
+ for (const raw of listOf(asked.fields)) {
926
+ const field = recordOf(raw);
927
+ const options = listOf(field.options).flatMap((option) =>
928
+ isRecord(option) && typeof option.value === 'string'
929
+ ? [
930
+ {
931
+ value: option.value,
932
+ label: str(option.label) ?? option.value,
933
+ description: str(option.description),
934
+ },
935
+ ]
936
+ : [],
937
+ );
938
+ const multiple = field.type === 'multiselect';
939
+ if (
940
+ (field.type !== 'string' && !multiple) ||
941
+ (multiple && !options.length) ||
942
+ field.hidden ||
943
+ field.when
944
+ )
945
+ return void cancel('Bridge can only ask questions with options or a text answer.');
946
+ const title = str(field.title);
947
+ const description = str(field.description);
948
+ fields.push({
949
+ key: String(field.key),
950
+ values: options.map((option) => option.value),
951
+ multiple,
952
+ });
953
+ questions.push({
954
+ id: String(field.key),
955
+ ...(title && description && { header: title }),
956
+ question: description ?? title ?? str(asked.title) ?? 'Question',
957
+ options: options.map((option, index) => ({
958
+ id: `option-${index}`,
959
+ label: option.label,
960
+ ...(option.description && { description: option.description }),
961
+ })),
962
+ ...(multiple && { multiSelect: true as const }),
963
+ ...((field.custom === true || !options.length) && { custom: true as const }),
964
+ ...(field.required === false && { required: false }),
965
+ });
966
+ }
967
+ const [only] = questions;
968
+ if (!only)
969
+ return void cancel('Bridge can only ask questions with options or a text answer.');
970
+ const single = questions.length === 1 && only.options.length > 0 && !only.multiSelect;
971
+ const choice = await decide(
972
+ questions
973
+ .map((question) =>
974
+ question.header ? `${question.header}: ${question.question}` : question.question,
975
+ )
976
+ .join('\n'),
977
+ single
978
+ ? only.options.map(({ id: option, label }) => ({
979
+ id: option,
980
+ label,
981
+ kind: 'other' as const,
982
+ }))
983
+ : [],
984
+ id,
985
+ undefined,
986
+ questions,
987
+ );
988
+ if (choice === null || choice === EXPIRED)
989
+ return void cancel(choice === EXPIRED ? LATE : DECLINED);
990
+ const given: Answers =
991
+ typeof choice === 'string'
992
+ ? { answers: [{ question: only.id, options: [choice] }] }
993
+ : choice;
994
+ const answer: Record<string, string | string[]> = {};
995
+ for (const field of fields) {
996
+ const each = given.answers.find((one) => one.question === field.key);
997
+ if (!each) continue;
998
+ const values = (each.options ?? []).map(
999
+ (option) => field.values[Number(option.slice('option-'.length))]!,
1000
+ );
1001
+ const text = each.text?.trim();
1002
+ if (field.multiple) answer[field.key] = [...values, ...(text ? [text] : [])];
1003
+ // A single choice is its option's value, else the text typed.
1004
+ else if (values[0] !== undefined || text) answer[field.key] = values[0] ?? text!;
1005
+ }
1006
+ await api
1007
+ .post(`/api/session/${session}/form/${id}/reply`, { answer })
1008
+ .catch((error: unknown) =>
1009
+ log.error(`harness ${harness}: OpenCode did not take the answer`, error),
1010
+ );
1011
+ };
1012
+
1013
+ /** The context window of the model a step runs, read once per model from the session's server (again after a
1014
+ * failed read). */
1015
+ const windows = new Map<string, Promise<number | undefined>>();
1016
+ const windowOf = (ref: unknown) => {
1017
+ const mine = recordOf(ref);
1018
+ const key = `${mine.providerID}/${mine.id}`;
1019
+ if (!windows.has(key))
1020
+ windows.set(
1021
+ key,
1022
+ catalogOf(api, `/api/model?${located(cwd)}`)
1023
+ .then((all) => {
1024
+ const found = all.find(
1025
+ (each) =>
1026
+ isRecord(each) && each.providerID === mine.providerID && each.id === mine.id,
1027
+ );
1028
+ const limit = isRecord(found) ? found.limit : undefined;
1029
+ const sizes = recordOf(limit);
1030
+ const size = sizes.input ?? sizes.context;
1031
+ return typeof size === 'number' && size > 0 ? size : undefined;
1032
+ })
1033
+ .catch(() => {
1034
+ windows.delete(key); // a failed read is not kept: the next step reads again
1035
+ return undefined;
1036
+ }),
1037
+ );
1038
+ return windows.get(key)!;
1039
+ };
1040
+ let stepModel: unknown = reference;
1041
+
1042
+ /** The sub-agents' sessions below ours (bridge#212 S8): what was last told of each. */
1043
+ const children = new Map<
1044
+ string,
1045
+ {
1046
+ title: string;
1047
+ agent?: string;
1048
+ tool?: string;
1049
+ status: 'running' | 'completed' | 'failed' | 'interrupted';
1050
+ }
1051
+ >();
1052
+ /** Sub-agent `id` started or changed: told once per change, an end final until its session runs a new execution
1053
+ * (`again`: the subagent tool continued it, with its `sessionID`). */
1054
+ const tellChild = (
1055
+ id: string,
1056
+ change: {
1057
+ title?: string | undefined;
1058
+ agent?: string | undefined;
1059
+ tool?: string | undefined;
1060
+ status?: 'running' | 'completed' | 'failed' | 'interrupted';
1061
+ },
1062
+ again = false,
1063
+ ) => {
1064
+ const was = children.get(id);
1065
+ if (was && was.status !== 'running' && !again) return;
1066
+ const now = {
1067
+ title: change.title ?? was?.title ?? 'Sub-agent',
1068
+ status: change.status ?? was?.status ?? 'running',
1069
+ ...((change.agent ?? was?.agent) !== undefined && { agent: change.agent ?? was?.agent }),
1070
+ ...((change.tool ?? was?.tool) !== undefined && { tool: change.tool ?? was?.tool }),
1071
+ };
1072
+ children.set(id, now);
1073
+ if (
1074
+ was &&
1075
+ was.status === now.status &&
1076
+ was.title === now.title &&
1077
+ was.tool === now.tool &&
1078
+ was.agent === now.agent
1079
+ )
1080
+ return;
1081
+ emit({ type: 'subagent', id, ...now });
1082
+ };
1083
+ /** An event of sub-agent session `child`: its words, reasoning and tool calls, naming it; its execution's end. */
1084
+ const onChild = (child: string, type: string, body: Record<string, unknown>) => {
1085
+ if (!turn || !children.has(child)) return;
1086
+ const sub = { subagent: child };
1087
+ switch (type) {
1088
+ case 'session.text.delta':
1089
+ case 'session.reasoning.delta': {
1090
+ if (typeof body.delta !== 'string' || !body.delta) return;
1091
+ const kind = type === 'session.text.delta' ? 'text' : 'thought';
1092
+ turn.streamed.add(`${kind}:${body.assistantMessageID}:${body.ordinal}`);
1093
+ emit({ type: kind, text: body.delta, ...sub });
1094
+ return;
1095
+ }
1096
+ case 'session.text.ended':
1097
+ case 'session.reasoning.ended': {
1098
+ const kind = type === 'session.text.ended' ? 'text' : 'thought';
1099
+ const text = str(body.text);
1100
+ if (!turn.streamed.has(`${kind}:${body.assistantMessageID}:${body.ordinal}`) && text)
1101
+ emit({ type: kind, text, ...sub });
1102
+ return;
1103
+ }
1104
+ case 'session.tool.input.started':
1105
+ case 'session.tool.called': {
1106
+ const id = str(body.id);
1107
+ if (!id) return;
1108
+ const known = turn.tools.get(id);
1109
+ const name = known?.name ?? str(body.name) ?? 'tool';
1110
+ const status = type === 'session.tool.called' ? 'running' : 'pending';
1111
+ setTool({ ...toolOf(id, name, body.input ?? known?.input, status), name, ...sub });
1112
+ return;
1113
+ }
1114
+ case 'session.tool.success':
1115
+ case 'session.tool.failed': {
1116
+ const id = str(body.id);
1117
+ const known = id ? turn.tools.get(id) : undefined;
1118
+ if (!known) return;
1119
+ setTool({
1120
+ ...known,
1121
+ status: endOf(type, body.metadata),
1122
+ output:
1123
+ type === 'session.tool.success'
1124
+ ? outputOf(body.content)
1125
+ : (str(recordOf(body.error).message) ?? 'The tool failed.'),
1126
+ });
1127
+ return;
1128
+ }
1129
+ case 'session.execution.started':
1130
+ // A sub-agent that ended runs again: its session was continued.
1131
+ if (children.get(child)?.status !== 'running')
1132
+ tellChild(child, { status: 'running' }, true);
1133
+ return;
1134
+ case 'session.execution.succeeded':
1135
+ tellChild(child, { status: 'completed' });
1136
+ return;
1137
+ case 'session.execution.interrupted':
1138
+ tellChild(child, { status: 'interrupted' });
1139
+ return;
1140
+ case 'session.execution.failed':
1141
+ tellChild(child, { status: 'failed' });
1142
+ return;
1143
+ default:
1144
+ return;
1145
+ }
1146
+ };
1147
+
1148
+ const onEvent = ({ type, data }: Event) => {
1149
+ const body = recordOf(data);
1150
+ if (
1151
+ type === 'session.created' &&
1152
+ typeof body.parentID === 'string' &&
1153
+ tree.has(body.parentID)
1154
+ ) {
1155
+ const child = String(body.sessionID);
1156
+ tree.add(child);
1157
+ // A sub-agent of this turn's (bridge#212 S8).
1158
+ if (turn)
1159
+ tellChild(child, {
1160
+ title: str(body.title),
1161
+ agent: str(body.agent),
1162
+ });
1163
+ return;
1164
+ }
1165
+ const session = body.sessionID ?? recordOf(body.form).sessionID;
1166
+ if (typeof session !== 'string' || !tree.has(session)) return;
1167
+ switch (type) {
1168
+ case 'permission.asked':
1169
+ void onAsk(data);
1170
+ return;
1171
+ case 'permission.replied':
1172
+ withdraw(String(body.requestID));
1173
+ return;
1174
+ case 'form.created':
1175
+ void onForm(body.form);
1176
+ return;
1177
+ case 'form.replied':
1178
+ case 'form.cancelled':
1179
+ withdraw(String(body.id));
1180
+ return;
1181
+ }
1182
+ // A subagent's own events name it (bridge#212 S8).
1183
+ if (session !== sessionId) {
1184
+ onChild(session, type, body);
1185
+ return;
1186
+ }
1187
+ if (!turn) return;
1188
+ switch (type) {
1189
+ case 'session.text.delta':
1190
+ case 'session.reasoning.delta': {
1191
+ if (typeof body.delta !== 'string' || !body.delta) return;
1192
+ const kind = type === 'session.text.delta' ? 'text' : 'thought';
1193
+ turn.streamed.add(`${kind}:${body.assistantMessageID}:${body.ordinal}`);
1194
+ emit({ type: kind, text: body.delta });
1195
+ return;
1196
+ }
1197
+ case 'session.text.ended':
1198
+ case 'session.reasoning.ended': {
1199
+ const kind = type === 'session.text.ended' ? 'text' : 'thought';
1200
+ const text = str(body.text);
1201
+ if (!turn.streamed.has(`${kind}:${body.assistantMessageID}:${body.ordinal}`) && text)
1202
+ emit({ type: kind, text });
1203
+ return;
1204
+ }
1205
+ case 'session.tool.input.started': {
1206
+ const id = str(body.id);
1207
+ if (!id) return;
1208
+ const name = str(body.name) ?? 'tool';
1209
+ setTool({ ...toolOf(id, name, undefined, 'pending'), name });
1210
+ return;
1211
+ }
1212
+ case 'session.tool.called': {
1213
+ const id = str(body.id);
1214
+ if (!id) return;
1215
+ const known = turn.tools.get(id);
1216
+ const name = known?.name ?? str(body.name) ?? 'tool';
1217
+ const tool = toolOf(id, name, body.input, 'running');
1218
+ // An ask may have given the call its paths and diffs already.
1219
+ setTool({
1220
+ ...tool,
1221
+ ...(known?.diffs && { paths: known.paths, diffs: known.diffs }),
1222
+ name,
1223
+ });
1224
+ return;
1225
+ }
1226
+ case 'session.tool.progress': {
1227
+ // Code Mode: an `execute` call names the MCP tools its code calls.
1228
+ const id = str(body.id);
1229
+ const known = id ? turn.tools.get(id) : undefined;
1230
+ // A subagent call names its session: the sub-agent's call, its task's description its title.
1231
+ const started = str(recordOf(body.metadata).sessionID);
1232
+ if (id && started && children.has(started))
1233
+ tellChild(started, {
1234
+ tool: id,
1235
+ title: str(recordOf(known?.input).description),
1236
+ });
1237
+ const calls = listOf(recordOf(body.metadata).toolCalls);
1238
+ const names = [
1239
+ ...new Set(
1240
+ calls
1241
+ .map((each) => (isRecord(each) ? str(each.tool) : undefined))
1242
+ .filter((tool): tool is string => tool !== undefined),
1243
+ ),
1244
+ ];
1245
+ if (known && names.length) setTool({ ...known, title: `Run ${names.join(', ')}` });
1246
+ return;
1247
+ }
1248
+ case 'session.tool.success':
1249
+ case 'session.tool.failed': {
1250
+ const id = str(body.id);
1251
+ const known = id ? turn.tools.get(id) : undefined;
1252
+ if (!known) return;
1253
+ const output =
1254
+ type === 'session.tool.success'
1255
+ ? outputOf(body.content)
1256
+ : (str(recordOf(body.error).message) ?? 'The tool failed.');
1257
+ setTool({
1258
+ ...known,
1259
+ status: endOf(type, body.metadata),
1260
+ output,
1261
+ });
1262
+ return;
1263
+ }
1264
+ case 'session.step.started': {
1265
+ const model = recordOf(body.model);
1266
+ if (model.providerID && model.id) stepModel = model;
1267
+ return;
1268
+ }
1269
+ case 'session.step.ended':
1270
+ case 'session.step.failed': {
1271
+ // The context's fill is the last step's: its input with the cache, and its output.
1272
+ const tokens = recordOf(body.tokens);
1273
+ const cache = recordOf(tokens.cache);
1274
+ const used =
1275
+ (typeof tokens.input === 'number' ? tokens.input : 0) +
1276
+ (typeof cache.read === 'number' ? cache.read : 0) +
1277
+ (typeof cache.write === 'number' ? cache.write : 0) +
1278
+ (typeof tokens.output === 'number' ? tokens.output : 0);
1279
+ if (!(used > 0)) return;
1280
+ const mine = turn;
1281
+ void windowOf(stepModel).then((size) =>
1282
+ mine === turn
1283
+ ? emit({ type: 'usage', used, ...(size !== undefined && { size }) })
1284
+ : undefined,
1285
+ );
1286
+ return;
1287
+ }
1288
+ case 'session.inbox.delivered': {
1289
+ const inbox = str(body.inboxID);
1290
+ if (!inbox) return;
1291
+ turn.delivered.add(inbox);
1292
+ turn.steering.delete(inbox);
1293
+ return;
1294
+ }
1295
+ case 'session.execution.started':
1296
+ turn.idle = undefined;
1297
+ return;
1298
+ case 'session.execution.succeeded':
1299
+ if (turn.stopping) return finish({ reason: 'interrupted' });
1300
+ // A steered message still waits: OpenCode runs it next, in this turn.
1301
+ if (turn.steering.size || turn.posting) {
1302
+ turn.idle = { reason: 'completed' };
1303
+ return;
1304
+ }
1305
+ finish({ reason: 'completed' });
1306
+ return;
1307
+ case 'session.execution.interrupted':
1308
+ finish({ reason: 'interrupted' });
1309
+ return;
1310
+ case 'session.execution.failed':
1311
+ finish({
1312
+ reason: 'failed',
1313
+ message: str(recordOf(body.error).message) ?? 'OpenCode failed the turn.',
1314
+ });
1315
+ return;
1316
+ default:
1317
+ return;
1318
+ }
1319
+ };
1320
+
1321
+ let stream: { stop(): void } | undefined;
1322
+ // Its exit closes the session and ends its turn.
1323
+ const exited = handle.exited.then(({ code, signal }) => {
1324
+ const wasClosed = closed;
1325
+ closed = true;
1326
+ stream?.stop();
1327
+ finish(
1328
+ wasClosed || disposing() || turn?.stopping
1329
+ ? {
1330
+ reason: 'interrupted',
1331
+ ...(disposing() && { message: 'Harness driver stopped during this turn' }),
1332
+ }
1333
+ : {
1334
+ reason: 'failed',
1335
+ message: `OpenCode exited (${signal ?? `code ${code}`})${tailOf(server.stderr())}`,
1336
+ },
1337
+ );
1338
+ });
1339
+
1340
+ const close = async () => {
1341
+ if (!closed) {
1342
+ closed = true;
1343
+ stream?.stop();
1344
+ void handle.kill();
1345
+ }
1346
+ finish({ reason: 'interrupted', message: 'Session closed' });
1347
+ await exitedWithin(exited, stopMs);
1348
+ };
1349
+
1350
+ let resumed = false;
1351
+ try {
1352
+ // The stream first: nothing said before the subscription is replayed.
1353
+ stream = await api.events(
1354
+ (event) => {
1355
+ try {
1356
+ onEvent(event);
1357
+ } catch (error) {
1358
+ log.error('opencode: an event failed to map', error);
1359
+ }
1360
+ },
1361
+ (error) => {
1362
+ if (!error || closed) return;
1363
+ log.error(`harness ${harness}: OpenCode's event stream was lost`, error);
1364
+ const ending = turn;
1365
+ if (ending)
1366
+ finish({
1367
+ reason: 'failed',
1368
+ message: `OpenCode's event stream was lost: ${error.message}`,
1369
+ });
1370
+ void close();
1371
+ },
1372
+ );
1373
+ if (resume !== undefined) {
1374
+ // Only the session's own 404 means OpenCode no longer has it; a refusal after is the open's failure.
1375
+ const found = await api
1376
+ .get(`/api/session/${encodeURIComponent(resume)}`)
1377
+ .catch((error: unknown) => {
1378
+ if (!(error instanceof ApiError && error.status === 404)) throw error;
1379
+ log.error(
1380
+ `harness ${harness}: session ${resume} could not be resumed; starting a new one`,
1381
+ error,
1382
+ );
1383
+ return undefined;
1384
+ });
1385
+ if (found) {
1386
+ sessionId = str(dataOf(found).id) ?? resume;
1387
+ resumed = true;
1388
+ await api.patch(`/api/session/${sessionId}`, { permissions: await rules() });
1389
+ if ((str(dataOf(found).agent) ?? 'build') !== agentOf(currentOptions))
1390
+ await api.post(`/api/session/${sessionId}/agent`, {
1391
+ agent: agentOf(currentOptions),
1392
+ });
1393
+ const was = recordOf(dataOf(found).model);
1394
+ if (reference && (was.providerID !== reference.providerID || was.id !== reference.id))
1395
+ await api.post(`/api/session/${sessionId}/model`, { model: reference });
1396
+ }
1397
+ }
1398
+ if (!resumed) {
1399
+ const created = await api.post('/api/session', {
1400
+ location: { directory: cwd },
1401
+ ...(reference && { model: reference }),
1402
+ ...(agentOf(currentOptions) === 'plan' && { agent: 'plan' }),
1403
+ permissions: await rules(),
1404
+ });
1405
+ sessionId = str(dataOf(created).id) ?? '';
1406
+ if (!sessionId) throw new Error('OpenCode answered without a session id');
1407
+ }
1408
+ tree.add(sessionId);
1409
+ // ponytail: a server that refuses an MCP server still runs the turn, without its tools.
1410
+ const attached: McpServer[] = [];
1411
+ for (const each of mcpServers)
1412
+ await api
1413
+ .put(`/api/experimental/mcp/${encodeURIComponent(each.name)}?${located(cwd)}`, {
1414
+ config: toOpenCode(each),
1415
+ })
1416
+ .then(() => {
1417
+ attached.push(each);
1418
+ })
1419
+ .catch((error: unknown) =>
1420
+ log.error(`harness ${harness}: OpenCode did not take MCP server ${each.name}`, error),
1421
+ );
1422
+ // The session's stable guidance, before the first prompt: only the servers it attached carry their text.
1423
+ await api
1424
+ .put(
1425
+ `/api/experimental/session/${encodeURIComponent(sessionId)}/instructions/entries/bridge`,
1426
+ { value: instructionsText(instructions, attached) },
1427
+ )
1428
+ .catch((error: unknown) =>
1429
+ log.error(
1430
+ `harness ${harness}: OpenCode did not take the session's instructions`,
1431
+ error,
1432
+ ),
1433
+ );
1434
+ } catch (error) {
1435
+ closed = true;
1436
+ stream?.stop();
1437
+ void handle.kill();
1438
+ await exitedWithin(exited, stopMs);
1439
+ throw new Error(
1440
+ `harness ${harness}: OpenCode could not start: ${error instanceof Error ? error.message : String(error)}`,
1441
+ );
1442
+ }
1443
+
1444
+ const id = sessionId;
1445
+ return {
1446
+ resume: id,
1447
+ model,
1448
+ get mode() {
1449
+ return currentMode;
1450
+ },
1451
+ get options() {
1452
+ return { ...currentOptions };
1453
+ },
1454
+ get closed() {
1455
+ return closed;
1456
+ },
1457
+ exited,
1458
+ resumed,
1459
+ prompt(text, onEvent, images = []) {
1460
+ if (closed)
1461
+ return Promise.resolve({ reason: 'failed', message: 'The OpenCode session is closed' });
1462
+ if (turn)
1463
+ return Promise.resolve({ reason: 'failed', message: 'A turn is already running' });
1464
+ return new Promise<TurnEnd>((done) => {
1465
+ const mine: NonNullable<typeof turn> = {
1466
+ onEvent,
1467
+ done,
1468
+ tools: new Map(),
1469
+ streamed: new Set(),
1470
+ stopping: false,
1471
+ steering: new Set(),
1472
+ posting: 0,
1473
+ delivered: new Set(),
1474
+ };
1475
+ turn = mine;
1476
+ api
1477
+ .post(`/api/session/${id}/prompt`, {
1478
+ text,
1479
+ // Images as files OpenCode reads itself (probe p-image: a `file://` URI).
1480
+ ...(images.length && {
1481
+ files: images.map((image) => ({
1482
+ uri: pathToFileURL(resolve(cwd, image.path)).href,
1483
+ name: image.name,
1484
+ })),
1485
+ }),
1486
+ })
1487
+ .catch((error: unknown) => {
1488
+ if (turn === mine && !closed)
1489
+ finish({
1490
+ reason: 'failed',
1491
+ message: `OpenCode refused the turn: ${error instanceof Error ? error.message : String(error)}`,
1492
+ });
1493
+ });
1494
+ });
1495
+ },
1496
+ async steer(text, images = []) {
1497
+ const mine = turn;
1498
+ if (closed || !mine || mine.stopping) return false;
1499
+ mine.posting++;
1500
+ let inbox: string | undefined;
1501
+ let took = false;
1502
+ try {
1503
+ const answer = await api.post(`/api/session/${id}/prompt`, {
1504
+ text,
1505
+ ...(images.length && {
1506
+ files: images.map((image) => ({
1507
+ uri: pathToFileURL(resolve(cwd, image.path)).href,
1508
+ name: image.name,
1509
+ })),
1510
+ }),
1511
+ delivery: 'steer',
1512
+ });
1513
+ took = true;
1514
+ inbox = str(recordOf(recordOf(answer).data).id);
1515
+ } catch {
1516
+ took = false;
1517
+ }
1518
+ mine.posting--;
1519
+ if (took && inbox && !mine.delivered.has(inbox)) mine.steering.add(inbox);
1520
+ // The execution ended meanwhile with nothing left to wait for: the turn ends as it would have.
1521
+ if (turn === mine && mine.idle && !mine.steering.size && !mine.posting) finish(mine.idle);
1522
+ return took;
1523
+ },
1524
+ async stopSubagent(id) {
1525
+ if (children.get(id)?.status !== 'running' || closed) return false;
1526
+ await api.post(`/api/session/${id}/interrupt`);
1527
+ return true;
1528
+ },
1529
+ async interrupt() {
1530
+ if (!turn || turn.stopping) return;
1531
+ turn.stopping = true;
1532
+ // Decisions first: OpenCode waits on an unanswered ask.
1533
+ cancelDecisions();
1534
+ void api.post(`/api/session/${id}/interrupt`).catch(() => {});
1535
+ // An interrupt OpenCode acknowledges without ending the execution: past `stopMs`, the session goes.
1536
+ stopTimer = setTimeout(() => void close(), stopMs);
1537
+ },
1538
+ async answer(decision, option) {
1539
+ const pending = decisions.get(decision);
1540
+ if (!pending) return false;
1541
+ if (option !== null && typeof option === 'object') {
1542
+ // Answers only for a form, and only what it offered.
1543
+ if (!pending.questions || !fits(pending.questions, option)) return false;
1544
+ } else if (option !== null && !pending.offered.has(option)) return false;
1545
+ pending.settle(option);
1546
+ return true;
1547
+ },
1548
+ // The rules change at once: OpenCode applies them to the asks after.
1549
+ async setMode(mode, options) {
1550
+ const next = modeOf(harness, mode, options);
1551
+ if (closed) throw new Error(`harness ${harness}: the session is closed`);
1552
+ const was = currentMode;
1553
+ const wasOptions = currentOptions;
1554
+ const wasGrants = [...grants];
1555
+ currentMode = next.mode;
1556
+ currentOptions = next.options;
1557
+ // "Allow for this session" answers go with the level and options that took them.
1558
+ grants.length = 0;
1559
+ const switched = agentOf(wasOptions) !== agentOf(currentOptions);
1560
+ try {
1561
+ // The agent from OpenCode's next step (it tells the model it entered or left Plan); the rules at once.
1562
+ if (switched)
1563
+ await api.post(`/api/session/${id}/agent`, { agent: agentOf(currentOptions) });
1564
+ await api.patch(`/api/session/${id}`, { permissions: await rules() });
1565
+ } catch (error) {
1566
+ // Half applied, maybe (a lost answer): which rules OpenCode holds is not known, so the session closes
1567
+ // rather than run under rules it does not say (audit L12-01).
1568
+ currentMode = was;
1569
+ currentOptions = wasOptions;
1570
+ grants.splice(0, grants.length, ...wasGrants);
1571
+ await close().catch(() => {});
1572
+ throw error;
1573
+ }
1574
+ },
1575
+ close,
1576
+ };
1577
+ },
1578
+ };
1579
+ return driver;
1580
+ };
1581
+
1582
+ /** The manifest's `bridge.driver` (title, description, settings schema), for the Providers screen. */
1583
+ const infoOf = () => {
1584
+ // oxlint-disable-next-line bridge/no-new-unchecked-cast -- the plugin's own bundled package.json
1585
+ const manifest = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) as {
1586
+ bridge?: { driver?: Record<string, unknown> };
1587
+ };
1588
+ const { title, description, config } = manifest.bridge?.driver ?? {};
1589
+ return {
1590
+ ...(typeof title === 'string' && { title }),
1591
+ ...(typeof description === 'string' && { description }),
1592
+ ...(typeof config === 'object' &&
1593
+ config !== null && { config: config as Record<string, unknown> }),
1594
+ };
1595
+ };
1596
+
1597
+ export function apply(ctx: Context) {
1598
+ // Set as this plugin disposes, before its processes' exits come back (the kill goes through the host).
1599
+ let disposing = false;
1600
+ ctx.effect(() => () => {
1601
+ disposing = true;
1602
+ });
1603
+ ctx.harness.register(ctx, {
1604
+ ...opencodeDriver({
1605
+ spawn: (options) => ctx.processes.spawn(ctx, options),
1606
+ disposing: () => disposing,
1607
+ log: ctx.logger,
1608
+ }),
1609
+ info: infoOf(),
1610
+ });
1611
+ }