@usepipa/pipa 0.5.6 → 0.6.0-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.
package/src/opencode.mjs CHANGED
@@ -1,15 +1,19 @@
1
1
  import crossSpawn from "cross-spawn";
2
+ import { randomBytes } from "node:crypto";
2
3
  import { constants } from "node:fs";
3
4
  import { chmod, lstat, mkdir, mkdtemp, open, realpath, rm, writeFile } from "node:fs/promises";
4
5
  import os from "node:os";
5
6
  import path from "node:path";
6
7
  import { pathToFileURL } from "node:url";
8
+ import { createV1Adapter } from "./opencode-v1.mjs";
9
+ import { createV2Adapter } from "./opencode-v2.mjs";
7
10
  import { normalizeModel } from "./state.mjs";
8
11
 
9
12
  const SLACK_SECRET_ENV_KEY = /(?:^|_)SLACK(?:_[A-Z0-9]+)*_(?:TOKEN|SECRET)$/iu;
10
13
  const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
11
14
 
12
- export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
15
+ export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
16
+ export const MAX_ARTIFACT_BYTES = 100 * 1024 * 1024;
13
17
  const ARTIFACT_MARKER = "PIPA_ARTIFACTS:";
14
18
  const MAX_ARTIFACT_DECLARATION_BYTES = 8 * 1024;
15
19
  const MAX_ARTIFACT_PATH_BYTES = 1024;
@@ -23,6 +27,16 @@ export class PipaStoppedError extends Error {
23
27
 
24
28
  export class PipaRestartingError extends PipaStoppedError {}
25
29
 
30
+ export class OpenCodeReadinessError extends Error {}
31
+
32
+ export function parseOpenCodeVersion(output) {
33
+ const match = /^(?:OpenCode\s+)?v?((0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)$/iu.exec(String(output ?? "").trim());
34
+ if (!match || match[3]?.split(".").some((part) => /^0\d+$/u.test(part))) throw new Error("OpenCode identity has an invalid version. Check `opencode --version` and the selected server URL.");
35
+ const major = Number(match[2]);
36
+ if (major !== 1 && major !== 2) throw new Error("Unsupported OpenCode major. Install a supported v1 or v2 runtime and check `opencode --version`.");
37
+ return { version: match[1], major };
38
+ }
39
+
26
40
  export function cleanChildEnvironment(environment = process.env) {
27
41
  return {
28
42
  ...Object.fromEntries(Object.entries(environment).filter(([key]) => !SLACK_SECRET_ENV_KEY.test(key))),
@@ -33,47 +47,50 @@ export function cleanChildEnvironment(environment = process.env) {
33
47
  export async function startSocketOpenCodeServer(config, options = {}) {
34
48
  const environment = options.environment ?? process.env;
35
49
  const attachUrl = options.attachUrl ?? environment.PIPA_OPENCODE_ATTACH_URL?.trim();
36
- const fetchImpl = options.fetch ?? fetch;
37
- const startupTimeoutMs = options.startupTimeoutMs ?? 30_000;
38
- const headers = authenticationHeaders(environment);
39
-
40
50
  if (attachUrl) {
41
51
  const baseUrl = normalizeBaseUrl(attachUrl);
42
- await waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs, options.signal);
43
- return externalServer(baseUrl);
52
+ const connection = await checkOpenCodeConnection(baseUrl, config.workingDirectory, { ...options, environment });
53
+ return { ...externalServer(baseUrl), connection };
44
54
  }
45
55
 
56
+ const identity = parseOpenCodeVersion(await (options.checkOpenCode ?? runOpenCodeVersion)(options));
57
+ options.signal?.throwIfAborted();
58
+ const childEnvironment = ownedEnvironment(environment, identity.major);
46
59
  const spawn = options.spawn ?? crossSpawn;
47
60
  const platform = options.platform ?? process.platform;
48
61
  const child = spawn("opencode", [
49
62
  "serve",
50
63
  "--hostname", "127.0.0.1",
51
64
  "--port", "0",
52
- "--log-level", "ERROR",
65
+ "--log-level", identity.major === 1 ? "ERROR" : "error",
53
66
  ], {
54
67
  cwd: config.workingDirectory,
55
- env: cleanChildEnvironment(environment),
68
+ env: childEnvironment,
56
69
  shell: false,
57
70
  stdio: ["ignore", "pipe", "pipe"],
58
71
  });
59
72
  const exit = waitForExit(child);
60
73
 
74
+ const controller = new AbortController();
75
+ const startupSignal = AbortSignal.any([controller.signal, ...(options.signal ? [options.signal] : [])]);
61
76
  try {
62
77
  const baseUrl = await Promise.race([
63
- readListeningUrl(child, startupTimeoutMs),
78
+ readListeningUrl(child, options.startupTimeoutMs, startupSignal),
64
79
  exit.then((code) => { throw new Error(`OpenCode server exited before startup with code ${code}.`); }),
65
80
  ]);
66
81
  child.stdout?.resume();
67
82
  child.stderr?.resume();
68
- await Promise.race([
69
- waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs, options.signal),
83
+ const connection = await Promise.race([
84
+ checkOpenCodeConnection(baseUrl, config.workingDirectory, { ...options, environment: childEnvironment, identity, signal: startupSignal }),
70
85
  exit.then((code) => { throw new Error(`OpenCode server exited before startup with code ${code}.`); }),
71
86
  ]);
72
- return ownedServer(baseUrl, child, exit, platform);
87
+ return { ...ownedServer(baseUrl, child, exit, platform), connection };
73
88
  } catch (error) {
74
89
  terminateChild(child, platform);
75
90
  await Promise.race([exit.catch(() => undefined), delay(5_000)]);
76
91
  throw error;
92
+ } finally {
93
+ controller.abort();
77
94
  }
78
95
  }
79
96
 
@@ -81,14 +98,37 @@ export function createOpenCodeExecutor(options = {}) {
81
98
  const baseUrl = normalizeBaseUrl(options.baseUrl);
82
99
  const fetchImpl = options.fetch ?? fetch;
83
100
  const environment = options.environment ?? process.env;
84
- const headers = authenticationHeaders(environment);
101
+ let headers = options.connection?.headers ?? authenticationHeaders(environment);
85
102
  const pollIntervalMs = options.pollIntervalMs ?? 1_000;
86
103
  const useDataUrls = !isLoopbackUrl(baseUrl);
87
104
  const remove = options.rm ?? rm;
88
105
  const artifactRoot = options.artifactRoot;
89
106
  const active = new Set();
90
107
  const activeSessions = new Map();
108
+ let adapter;
109
+ let capabilities;
110
+ let readiness;
91
111
  let stopReason;
112
+ // Readiness is shared across turns; only stopping the executor cancels its probe.
113
+ const readinessController = new AbortController();
114
+
115
+ async function ready(workingDirectory) {
116
+ if (stopReason) throw stopReason;
117
+ readiness ??= (async () => {
118
+ const connection = options.connection ?? await checkOpenCodeConnection(baseUrl, workingDirectory, { ...options, environment, fetch: fetchImpl,
119
+ signal: AbortSignal.any([readinessController.signal, ...(options.signal ? [options.signal] : [])]),
120
+ });
121
+ headers = connection.headers ?? headers;
122
+ capabilities = Object.freeze({ modelDiscovery: true, liveModelSwitch: connection.major === 2 });
123
+ adapter = connection.major === 2
124
+ ? createV2Adapter({ ...options, baseUrl, fetch: fetchImpl, headers, environment, pollIntervalMs })
125
+ : createV1Adapter({ request, baseUrl, fetchImpl, headers, pollIntervalMs });
126
+ await adapter.ready?.(workingDirectory);
127
+ })();
128
+ await readiness;
129
+ // Failed turn cleanup blocks subsequent turns even after initial readiness resolved.
130
+ await adapter.ready?.(workingDirectory);
131
+ }
92
132
 
93
133
  async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
94
134
  const url = serverUrl(baseUrl, pathname, workingDirectory);
@@ -128,51 +168,31 @@ export function createOpenCodeExecutor(options = {}) {
128
168
  async function runTurn({ prompt, sessionId, model, defaultModel, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
129
169
  if (!prompt?.trim()) throw new Error("A prompt is required.");
130
170
  if (stopReason) throw stopReason;
131
- let selectedModel = normalizeModel(model);
171
+ if (sessionId && activeSessions.has(sessionId)) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
172
+ let temporaryDirectory;
173
+ const selectedModel = normalizeModel(model);
132
174
  const newThreadModel = normalizeModel(defaultModel);
133
- const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
134
175
  const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
135
176
  const controller = new AbortController();
136
177
  const abort = () => controller.abort(signal.reason);
137
178
  if (signal?.aborted) abort();
138
179
  else signal?.addEventListener("abort", abort, { once: true });
139
180
  active.add(controller);
181
+ if (sessionId) activeSessions.set(sessionId, { controller, workingDirectory, resolved: false });
140
182
  let artifactDirectory;
141
183
 
142
184
  try {
143
185
  try {
186
+ temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
187
+ controller.signal.throwIfAborted();
144
188
  const files = await stageAttachments(attachments, temporaryDirectory, useDataUrls, controller.signal);
145
189
  if (stopReason) throw stopReason;
146
- let selectedSessionId = sessionId;
147
- let messages;
148
- if (selectedSessionId) {
149
- try {
150
- while (true) {
151
- const status = (await request("/session/status", { method: "GET" }, workingDirectory, controller))?.[selectedSessionId]?.type;
152
- if (status !== "busy" && status !== "retry") break;
153
- await delay(pollIntervalMs, controller.signal);
154
- }
155
- messages = await request(`/session/${encodeURIComponent(selectedSessionId)}/message?limit=1`, { method: "GET" }, workingDirectory, controller);
156
- } catch (error) {
157
- if (!(error instanceof OpenCodeRequestError) || error.status !== 404) throw error;
158
- selectedSessionId = null;
159
- }
160
- }
161
- if (!selectedSessionId) {
162
- const session = await request("/session", { method: "POST", body: "{}" }, workingDirectory, controller);
163
- if (!session?.id) throw new Error("OpenCode did not create a session.");
164
- selectedSessionId = session.id;
165
- messages = [];
166
- }
190
+ await abortable(ready(workingDirectory), controller.signal);
191
+ const prepared = await adapter.resolveSession(sessionId, workingDirectory, controller);
192
+ const selectedSessionId = prepared.sessionId;
167
193
 
168
- if (!selectedModel) {
169
- // OpenCode history persists the thread's model, including interrupted user turns.
170
- const last = messages.at(-1)?.info;
171
- const threadModel = last?.role === "user" ? last.model
172
- : last?.providerID && last?.modelID ? { providerID: last.providerID, modelID: last.modelID } : null;
173
- selectedModel = normalizeModel(threadModel) ?? newThreadModel;
174
- }
175
- activeSessions.set(selectedSessionId, { controller, workingDirectory });
194
+ if (activeSessions.has(selectedSessionId) && activeSessions.get(selectedSessionId).controller !== controller) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
195
+ activeSessions.set(selectedSessionId, { controller, workingDirectory, resolved: true });
176
196
  await onSession?.(selectedSessionId);
177
197
  if (controller.signal.aborted) throw controller.signal.reason;
178
198
 
@@ -186,74 +206,16 @@ export function createOpenCodeExecutor(options = {}) {
186
206
  } catch {}
187
207
  }
188
208
 
189
- const baseline = new Set(messages.map((message) => message?.info?.id).filter(Boolean));
190
- let dismissed = false;
191
- let permissionRejected = false;
192
- if (onInteraction) {
193
- const watcher = watchInteractions({
194
- baseUrl,
195
- fetchImpl,
196
- headers,
197
- sessionId: selectedSessionId,
198
- workingDirectory,
199
- controller,
200
- onInteraction,
201
- onPermissionReplied,
202
- onPermissionsReconciled,
203
- onPermissionRejected: () => { permissionRejected = true; },
204
- onDismiss: () => { dismissed = true; },
205
- requestTurn: request,
206
- });
207
- await watcher.ready;
208
- }
209
- await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
210
- method: "POST",
211
- body: JSON.stringify({ ...promptBody(prompt, files, contextEnvironment, artifactDirectory), ...(selectedModel ? { model: selectedModel } : {}) }),
212
- }, workingDirectory, controller, [204]);
213
-
214
- while (true) {
215
- const [currentMessages, statuses] = await Promise.all([
216
- request(`/session/${encodeURIComponent(selectedSessionId)}/message?limit=1`, { method: "GET" }, workingDirectory, controller),
217
- request("/session/status", { method: "GET" }, workingDirectory, controller),
218
- ]);
219
- const finalMessage = latestAssistantMessage(currentMessages, baseline);
220
- const status = statuses?.[selectedSessionId]?.type;
221
- if (dismissed && status !== "busy" && status !== "retry") return { text: "", sessionId: selectedSessionId };
222
- if (finalMessage?.error) {
223
- const error = finalMessage.error;
224
- const providerID = finalMessage.providerID ?? selectedModel?.providerID;
225
- const provider = typeof providerID === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/iu.test(providerID) ? `provider "${providerID}"` : "selected provider";
226
- const statusCode = error.data?.statusCode;
227
- const http = Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599 ? ` (HTTP ${statusCode})` : "";
228
- // Classify upstream failures without exposing response bodies, headers, or credentials.
229
- if (statusCode === 401 || error.name === "ProviderAuthError") {
230
- const expiredKey = statusCode === 401 && typeof error.data?.message === "string" && /\bAPI key (?:has )?expired\b/iu.test(error.data.message);
231
- throw new Error(expiredKey
232
- ? `OpenCode ${provider} API key has expired. Replace that provider's API key in OpenCode, or choose another provider with your installation's model command, then start a new thread.`
233
- : `OpenCode ${provider} authentication failed${http}. Reconnect that provider in OpenCode, or choose another provider with your installation's model command, then start a new thread.`);
234
- }
235
- throw new Error(`OpenCode ${provider} ${http ? `failed${http}` : "failed to complete the turn"}.`);
236
- }
237
- if (["error", "failed", "cancelled"].includes(status)) throw new Error("OpenCode failed to complete the turn.");
238
- if (finalMessage && ((status !== "retry" && finalMessage.completed && finalMessage.finish === "stop") || status === "idle" || (!status && finalMessage.completed))) {
239
- if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
240
- if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
241
- const parsed = slackTurn ? parseArtifactDeclaration(finalMessage.text) : { text: finalMessage.text };
242
- const artifacts = artifactDirectory && parsed.paths ? await readArtifacts(artifactDirectory, parsed.paths, options.onArtifactOpened) : [];
243
- return {
244
- text: parsed.text,
245
- sessionId: selectedSessionId,
246
- ...(artifacts.length ? { files: artifacts } : {}),
247
- };
248
- }
249
- await delay(pollIntervalMs, controller.signal);
250
- }
209
+ const text = await adapter.execute({ ...prepared, model: selectedModel, defaultModel: newThreadModel, workingDirectory, controller, prompt, files,
210
+ instructions: turnInstructions(contextEnvironment, artifactDirectory), onInteraction, onPermissionReplied, onPermissionsReconciled });
211
+ const parsed = slackTurn ? parseArtifactDeclaration(text) : { text };
212
+ const artifacts = artifactDirectory && parsed.paths ? await readArtifacts(artifactDirectory, parsed.paths, options.onArtifactOpened) : [];
213
+ return { text: parsed.text, sessionId: selectedSessionId, ...(artifacts.length ? { files: artifacts } : {}) };
214
+ } catch (error) {
215
+ if (controller.signal.aborted) throw controller.signal.reason;
216
+ throw error;
251
217
  } finally {
252
218
  controller.abort(new Error("OpenCode turn completed."));
253
- active.delete(controller);
254
- for (const [sessionId, turn] of activeSessions) {
255
- if (turn.controller === controller) activeSessions.delete(sessionId);
256
- }
257
219
  }
258
220
  } catch (error) {
259
221
  if (stopReason) throw stopReason;
@@ -274,46 +236,74 @@ export function createOpenCodeExecutor(options = {}) {
274
236
  }
275
237
  }
276
238
  signal?.removeEventListener("abort", abort);
239
+ active.delete(controller);
240
+ for (const [sessionId, turn] of activeSessions) {
241
+ if (turn.controller === controller) activeSessions.delete(sessionId);
242
+ }
277
243
  }
278
244
  }
279
245
 
280
246
  return {
247
+ // Unknown until authenticated runtime negotiation has completed.
248
+ get capabilities() { return capabilities; },
249
+ ready,
281
250
  runTurn,
282
- async listModels(workingDirectory) {
251
+ async listModels(input = {}) {
252
+ const flat = typeof input === "string";
253
+ const { workingDirectory, signal } = flat ? { workingDirectory: input } : input;
283
254
  if (stopReason) throw stopReason;
284
255
  const controller = new AbortController();
285
- const timer = setTimeout(() => controller.abort(new Error("Model discovery timed out.")), 1_500);
256
+ const abort = () => controller.abort(signal.reason);
257
+ if (signal?.aborted) abort();
258
+ else signal?.addEventListener("abort", abort, { once: true });
286
259
  active.add(controller);
260
+ const timer = setTimeout(() => controller.abort(new Error("Model discovery timed out.")), 1_500);
287
261
  try {
288
- const catalog = await request("/config/providers", { method: "GET" }, workingDirectory, controller, [200], false);
289
- if (!Array.isArray(catalog?.providers)) throw new Error("OpenCode returned an invalid model catalog.");
290
- return catalog.providers.flatMap((provider) => {
291
- if (!provider?.models || typeof provider.models !== "object" || Array.isArray(provider.models)) throw new Error("Invalid provider models.");
292
- return Object.entries(provider.models).map(([id, model]) => ({
293
- ...normalizeModel({ providerID: provider.id, modelID: model.id ?? id }),
294
- name: typeof model.name === "string" ? model.name : id,
295
- }));
296
- });
262
+ await abortable(ready(workingDirectory), controller.signal);
263
+ controller.signal.throwIfAborted();
264
+ if (!capabilities.modelDiscovery) throw new Error("OpenCode model discovery is not supported by this adapter.");
265
+ const catalog = await abortable(adapter.listModels(workingDirectory, controller.signal), controller.signal);
266
+ controller.signal.throwIfAborted();
267
+ return flat ? catalog.models.map((model) => ({ providerID: model.providerID, modelID: model.id, name: model.name })) : catalog;
297
268
  } finally {
298
269
  clearTimeout(timer);
270
+ controller.abort();
299
271
  active.delete(controller);
272
+ signal?.removeEventListener("abort", abort);
273
+ }
274
+ },
275
+ async switchModel({ sessionId, model, workingDirectory, signal } = {}) {
276
+ if (stopReason) throw stopReason;
277
+ const controller = new AbortController();
278
+ const abort = () => controller.abort(signal.reason);
279
+ if (signal?.aborted) abort();
280
+ else signal?.addEventListener("abort", abort, { once: true });
281
+ active.add(controller);
282
+ try {
283
+ await abortable(ready(workingDirectory), controller.signal);
284
+ controller.signal.throwIfAborted();
285
+ if (!capabilities.liveModelSwitch) throw new Error("OpenCode live model switching is not supported by this adapter.");
286
+ return await adapter.switchModel(sessionId, model, workingDirectory, controller.signal);
287
+ } finally {
288
+ controller.abort();
289
+ active.delete(controller);
290
+ signal?.removeEventListener("abort", abort);
300
291
  }
301
292
  },
302
293
  async abortTurn(sessionId, reason = new Error("OpenCode turn aborted.")) {
303
294
  const turn = activeSessions.get(sessionId);
304
295
  if (!turn) return;
305
- const abortController = new AbortController();
306
296
  try {
307
- await request(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, turn.workingDirectory, abortController, [200, 204, 404], false);
297
+ if (turn.resolved) await adapter.abortTurn(sessionId, turn.workingDirectory);
308
298
  } catch {
309
299
  // Local cancellation still supersedes the turn if OpenCode's abort request fails.
310
300
  } finally {
311
- abortController.abort(reason);
312
301
  turn.controller.abort(reason);
313
302
  }
314
303
  },
315
304
  stopAll(reason = new PipaStoppedError()) {
316
305
  stopReason ??= reason;
306
+ readinessController.abort(stopReason);
317
307
  for (const controller of active) controller.abort(stopReason);
318
308
  },
319
309
  };
@@ -329,19 +319,22 @@ async function sessionArtifactDirectory(root, sessionId, workingDirectory) {
329
319
  return path.join(resolvedRoot, sessionId);
330
320
  }
331
321
 
332
- export function startOpenCodeServer(config, options = {}) {
322
+ export async function startOpenCodeServer(config, options = {}) {
323
+ const identity = parseOpenCodeVersion(await (options.checkOpenCode ?? runOpenCodeVersion)(options));
324
+ options.signal?.throwIfAborted();
325
+ const environment = ownedEnvironment(options.environment ?? process.env, identity.major);
333
326
  const spawn = options.spawn ?? crossSpawn;
334
327
  const platform = options.platform ?? process.platform;
335
328
  const child = spawn("opencode", [
336
329
  "serve",
337
330
  "--hostname", config.openCodeHostname,
338
331
  "--port", String(config.openCodePort),
339
- "--log-level", "ERROR",
332
+ "--log-level", identity.major === 1 ? "ERROR" : "error",
340
333
  ], {
341
334
  cwd: config.workingDirectory,
342
- env: cleanChildEnvironment(options.environment ?? process.env),
335
+ env: environment,
343
336
  shell: false,
344
- stdio: "inherit",
337
+ stdio: config.openCodePort === 0 ? ["ignore", "pipe", "pipe"] : "inherit",
345
338
  });
346
339
  let stopping = false;
347
340
  const exit = waitForExit(child).then((code) => {
@@ -349,14 +342,19 @@ export function startOpenCodeServer(config, options = {}) {
349
342
  });
350
343
  void exit.catch(() => undefined);
351
344
 
352
- return {
345
+ const listening = config.openCodePort === 0 ? readListeningUrl(child, options.startupTimeoutMs, options.signal) : null;
346
+ void listening?.catch(() => undefined);
347
+ const server = {
353
348
  async ready() {
354
349
  const controller = new AbortController();
355
350
  const hostname = config.openCodeHostname.includes(":") && !config.openCodeHostname.startsWith("[") ? `[${config.openCodeHostname}]` : config.openCodeHostname;
356
351
  try {
357
- await Promise.race([
358
- waitForWorkspace(`http://${hostname}:${config.openCodePort}`, config.workingDirectory,
359
- options.fetch ?? fetch, authenticationHeaders(options.environment ?? process.env), options.startupTimeoutMs ?? 30_000, controller.signal),
352
+ const baseUrl = listening ? await Promise.race([listening, exit.then(() => { throw new Error("OpenCode stopped before reporting its listening URL."); })]) : `http://${hostname}:${config.openCodePort}`;
353
+ child.stdout?.resume();
354
+ child.stderr?.resume();
355
+ server.connection = await Promise.race([
356
+ checkOpenCodeConnection(baseUrl, config.workingDirectory, { ...options, environment, identity,
357
+ signal: AbortSignal.any([controller.signal, ...(options.signal ? [options.signal] : [])]) }),
360
358
  exit.then(() => { throw new Error("OpenCode stopped before workspace readiness."); }),
361
359
  ]);
362
360
  } finally { controller.abort(); }
@@ -368,27 +366,32 @@ export function startOpenCodeServer(config, options = {}) {
368
366
  terminateChild(child, platform, signal);
369
367
  },
370
368
  };
369
+ return server;
371
370
  }
372
371
 
373
372
  export async function runOpenCodeVersion(options = {}) {
373
+ options.signal?.throwIfAborted();
374
374
  const spawn = options.spawn ?? crossSpawn;
375
375
  const platform = options.platform ?? process.platform;
376
- const timeoutMs = options.timeoutMs ?? 30_000;
376
+ const timeoutMs = options.timeoutMs;
377
377
  const child = spawn("opencode", ["--version"], {
378
378
  env: cleanChildEnvironment(options.environment ?? process.env),
379
379
  shell: false,
380
380
  stdio: ["ignore", "pipe", "pipe"],
381
381
  });
382
382
  let timer;
383
+ const abort = () => terminateChild(child, platform);
384
+ options.signal?.addEventListener("abort", abort, { once: true });
383
385
  try {
384
386
  const operation = Promise.all([collect(child.stdout), collect(child.stderr), waitForExit(child)]);
385
- const timeout = new Promise((_, reject) => {
387
+ const timeout = timeoutMs === undefined ? null : new Promise((_, reject) => {
386
388
  timer = setTimeout(() => {
387
389
  terminateChild(child, platform);
388
390
  reject(new Error(`OpenCode version check timed out after ${timeoutMs}ms.`));
389
391
  }, timeoutMs);
390
392
  });
391
- const [stdout, stderr, code] = await Promise.race([operation, timeout]);
393
+ const result = timeout ? Promise.race([operation, timeout]) : operation;
394
+ const [stdout, stderr, code] = await (options.signal ? abortable(result, options.signal) : result);
392
395
  if (code !== 0) throw new Error(stderr.trim() || "OpenCode version check failed.");
393
396
  return stdout.trim();
394
397
  } catch (error) {
@@ -396,19 +399,21 @@ export async function runOpenCodeVersion(options = {}) {
396
399
  throw error;
397
400
  } finally {
398
401
  clearTimeout(timer);
402
+ options.signal?.removeEventListener("abort", abort);
399
403
  }
400
404
  }
401
405
 
402
406
  async function stageAttachments(attachments, temporaryDirectory, useDataUrls, signal) {
403
407
  const files = [];
404
408
  for (const [index, attachment] of attachments.entries()) {
409
+ if (attachment.size !== undefined && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_ATTACHMENT_BYTES)) throw new Error("Attached files must be 10 MiB or smaller.");
405
410
  let data;
406
411
  try {
407
412
  data = await abortable(attachment.fetchData(), signal);
408
413
  } catch {
409
414
  throw new Error("Could not read one of the attached files. Please try uploading it again.");
410
415
  }
411
- if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 100 MB or smaller.");
416
+ if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 10 MiB or smaller.");
412
417
  try {
413
418
  const filename = sanitizeFilename(path.basename(attachment.name || "attachment"), "attachment");
414
419
  const file = path.join(temporaryDirectory, `${index + 1}-${filename}`);
@@ -426,8 +431,7 @@ async function stageAttachments(attachments, temporaryDirectory, useDataUrls, si
426
431
  return files;
427
432
  }
428
433
 
429
- function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
430
- const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
434
+ function turnInstructions(contextEnvironment, artifactDirectory) {
431
435
  const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
432
436
  const instructions = ["For scheduling requests, consult `pipa routine --help`, convert timezone wording to an IANA timezone, preview first, show the normalized details, and create only after user confirmation."];
433
437
  const restartCommand = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack" && contextEnvironment.PIPA_CURRENT_SLACK_CHANNEL_ID
@@ -439,10 +443,7 @@ function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
439
443
  instructions.push("Keep naturally short answers inline. For deeper work or larger deliverables, keep the Slack response concise and use the most suitable artifact format.");
440
444
  if (artifactDirectory) instructions.push(`To attach files, copy up to 10 top-level files (100 MB total) to this private artifact directory: ${artifactDirectory}\nOnly if you created files, end your response with exactly one final line in this format: ${ARTIFACT_MARKER} [\"report.csv\",\"brief.pdf\"]\nDo not emit ${ARTIFACT_MARKER} otherwise.`);
441
445
  }
442
- return {
443
- parts,
444
- ...(instructions.length ? { system: instructions.join("\n\n") } : {}),
445
- };
446
+ return instructions.join("\n\n");
446
447
  }
447
448
 
448
449
  function parseArtifactDeclaration(text) {
@@ -494,7 +495,7 @@ async function readArtifacts(directory, paths, onOpened) {
494
495
  const before = await handle.stat({ bigint: true });
495
496
  await onOpened?.(filename);
496
497
  const size = Number(before.size);
497
- if (!before.isFile() || size > MAX_ATTACHMENT_BYTES || total + size > MAX_ATTACHMENT_BYTES) throw new Error("Artifact exceeds delivery limits.");
498
+ if (!before.isFile() || size > MAX_ARTIFACT_BYTES || total + size > MAX_ARTIFACT_BYTES) throw new Error("Artifact exceeds delivery limits.");
498
499
  const data = Buffer.alloc(size + 1);
499
500
  let bytesRead = 0;
500
501
  while (bytesRead < data.length) {
@@ -526,25 +527,6 @@ function sanitizeFilename(value, fallback = "artifact") {
526
527
  return Array.from(sanitized).reduce((result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result, "") || fallback;
527
528
  }
528
529
 
529
- function latestAssistantMessage(messages, baseline) {
530
- for (let index = messages.length - 1; index >= 0; index -= 1) {
531
- const message = messages[index];
532
- if (!message?.info?.id || baseline.has(message.info.id) || message.info.role !== "assistant") continue;
533
- return {
534
- completed: typeof message.info.time?.completed === "number",
535
- providerID: message.info.providerID,
536
- error: message.info.error,
537
- finish: message.info.finish,
538
- text: message.parts
539
- .filter((part) => part.type === "text" && typeof part.text === "string" && part.text)
540
- .map((part) => part.text)
541
- .join("\n")
542
- .trim(),
543
- };
544
- }
545
- return null;
546
- }
547
-
548
530
  function ownedServer(baseUrl, child, exit, platform) {
549
531
  let stopping = false;
550
532
  let rejectFailure;
@@ -592,31 +574,89 @@ function externalServer(baseUrl) {
592
574
  };
593
575
  }
594
576
 
595
- async function waitForWorkspace(baseUrl, workingDirectory, fetchImpl, headers, timeoutMs, signal) {
596
- const deadline = Date.now() + timeoutMs;
577
+ export async function checkOpenCodeConnection(baseUrl, workingDirectory, options = {}) {
578
+ baseUrl = normalizeBaseUrl(baseUrl);
579
+ const fetchImpl = options.fetch ?? fetch;
580
+ const environment = options.environment ?? process.env;
581
+ const signal = options.signal;
582
+ const deadline = options.startupTimeoutMs === undefined ? Infinity : Date.now() + options.startupTimeoutMs;
583
+ let connection;
584
+ async function read(pathname, headers, directory, candidate = false) {
585
+ const url = serverUrl(baseUrl, pathname, directory);
586
+ const response = await fetchImpl(url, {
587
+ headers,
588
+ redirect: "manual",
589
+ signal: AbortSignal.any([AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))), ...(signal ? [signal] : [])]),
590
+ });
591
+ if (!response.ok) await response.body?.cancel().catch(() => undefined);
592
+ if (response.status === 401 || response.status === 403) throw new Error("OpenCode authentication failed. Check OPENCODE_SERVER_USERNAME/OPENCODE_SERVER_PASSWORD for v1 or OPENCODE_PASSWORD (then OPENCODE_SERVER_PASSWORD) for v2 credentials.");
593
+ if ([502, 503, 504].includes(response.status)) throw new OpenCodeReadinessError("OpenCode is temporarily unavailable.");
594
+ if (candidate && [404, 405].includes(response.status)) return null;
595
+ if (!response.ok) throw new Error(`OpenCode protocol check failed (HTTP ${response.status}). Check the server URL and supported runtime.`);
596
+ try { return await response.json(); }
597
+ catch (error) {
598
+ if (!(error instanceof SyntaxError)) throw error;
599
+ if (candidate) return null; // Legacy identity routes on v2 serve the web UI.
600
+ throw new Error("OpenCode protocol check returned invalid JSON. Check the server URL and runtime.");
601
+ }
602
+ }
597
603
  while (Date.now() < deadline) {
604
+ signal?.throwIfAborted();
598
605
  try {
599
- const status = await fetchImpl(serverUrl(baseUrl, "/session/status", workingDirectory), {
600
- headers,
601
- signal: AbortSignal.any([AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))), ...(signal ? [signal] : [])]),
602
- });
603
- const sessions = status.ok ? await status.json() : null;
604
- if (sessions && typeof sessions === "object" && !Array.isArray(sessions)
605
- && Object.values(sessions).every((session) => session && typeof session === "object" && typeof session.type === "string")) return;
606
- } catch {
607
- // OpenCode can accept its socket before the configured workspace is ready.
606
+ if (!connection) {
607
+ const v1Headers = authenticationHeaders(environment, 1);
608
+ const health = await read("/global/health", v1Headers, undefined, true);
609
+ if (typeof health?.healthy === "boolean" && typeof health.version === "string") {
610
+ const identity = parseOpenCodeVersion(health.version);
611
+ if (identity.major !== 1) throw new Error("OpenCode identity/protocol mismatch at /global/health.");
612
+ if (!health.healthy) throw new OpenCodeReadinessError("OpenCode is not healthy yet.");
613
+ connection = { ...identity, headers: v1Headers };
614
+ } else {
615
+ const headers = authenticationHeaders(environment, 2);
616
+ const info = await read("/api/info", headers, undefined, true);
617
+ if (!info || typeof info.version !== "string" || !Number.isSafeInteger(info.pid) || info.pid <= 0
618
+ || !Array.isArray(info.urls) || !info.urls.every((url) => typeof url === "string") || typeof info.paths?.tmp !== "string") {
619
+ throw new Error("OpenCode identity protocol is unsupported. Check the selected server URL and install a supported v1 or v2 runtime.");
620
+ }
621
+ const identity = parseOpenCodeVersion(info.version);
622
+ if (identity.major !== 2) throw new Error("OpenCode identity/protocol mismatch at /api/info.");
623
+ connection = { ...identity, headers };
624
+ }
625
+ if (options.identity && options.identity.version !== connection.version) throw new Error("OpenCode CLI/server identity mismatch. Check the executable and selected listening server.");
626
+ }
627
+ const headers = connection.headers;
628
+ if (connection.major === 2) {
629
+ const locationUrl = `/api/location?${new URLSearchParams({ "location[directory]": workingDirectory })}`;
630
+ const location = await read(locationUrl, headers);
631
+ if (typeof location?.directory !== "string" || !path.isAbsolute(location.directory) || typeof location.project?.id !== "string"
632
+ || typeof location.project?.directory !== "string" || typeof location.project?.canonical !== "string") throw new Error("OpenCode location protocol has an invalid schema.");
633
+ if (path.resolve(location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode workspace identity mismatch. Select a server serving the configured working directory.");
634
+ } else {
635
+ const location = await read("/path", headers, workingDirectory);
636
+ if (typeof location?.directory !== "string" || !path.isAbsolute(location.directory)) throw new Error("OpenCode workspace protocol has an invalid schema.");
637
+ if (path.resolve(location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode workspace identity mismatch. Select a server serving the configured working directory.");
638
+ const sessions = await read("/session/status", headers, workingDirectory);
639
+ if (!sessions || typeof sessions !== "object" || Array.isArray(sessions)
640
+ || !Object.values(sessions).every((session) => session && typeof session === "object" && typeof session.type === "string")) throw new Error("OpenCode workspace protocol has an invalid status schema.");
641
+ }
642
+ return { ...connection, baseUrl, workingDirectory };
643
+ } catch (error) {
644
+ if (signal?.aborted) throw signal.reason;
645
+ if (!(error instanceof OpenCodeReadinessError) && !isNetworkError(error) && error.name !== "TimeoutError") throw error;
608
646
  }
609
647
  await delay(Math.min(250, Math.max(0, deadline - Date.now())), signal);
610
648
  }
611
- throw new Error("OpenCode workspace readiness check timed out.");
649
+ throw new OpenCodeReadinessError("OpenCode workspace readiness check timed out. Check the server and configured working directory.");
612
650
  }
613
651
 
614
- function readListeningUrl(child, timeoutMs) {
652
+ function readListeningUrl(child, timeoutMs, signal) {
615
653
  return new Promise((resolve, reject) => {
616
654
  let output = "";
617
655
  const cleanup = () => {
618
656
  child.stdout?.off("data", inspect);
619
657
  child.stderr?.off("data", inspect);
658
+ child.off("close", closed);
659
+ signal?.removeEventListener("abort", abort);
620
660
  };
621
661
  const finish = (callback, value) => {
622
662
  clearTimeout(timer);
@@ -629,20 +669,39 @@ function readListeningUrl(child, timeoutMs) {
629
669
  if (!match) return;
630
670
  finish(resolve, normalizeBaseUrl(match[0]));
631
671
  };
632
- const timer = setTimeout(() => finish(reject, new Error("OpenCode server did not report its listening URL.")), timeoutMs);
633
- timer.unref?.();
672
+ const timer = timeoutMs === undefined ? null : setTimeout(() => finish(reject, new Error("OpenCode server did not report its listening URL.")), timeoutMs);
673
+ const closed = () => finish(reject, new Error("OpenCode stopped before reporting its listening URL."));
674
+ const abort = () => finish(reject, signal.reason);
675
+ timer?.unref?.();
634
676
  child.stdout?.on("data", inspect);
635
677
  child.stderr?.on("data", inspect);
678
+ child.once("close", closed);
679
+ if (signal?.aborted) abort();
680
+ else signal?.addEventListener("abort", abort, { once: true });
636
681
  });
637
682
  }
638
683
 
639
- function authenticationHeaders(environment) {
640
- const password = environment.OPENCODE_SERVER_PASSWORD;
684
+ function authenticationHeaders(environment, major = 1) {
685
+ const password = major === 2 ? environment.OPENCODE_PASSWORD || environment.OPENCODE_SERVER_PASSWORD : environment.OPENCODE_SERVER_PASSWORD;
641
686
  if (!password) return {};
642
- const username = environment.OPENCODE_SERVER_USERNAME?.trim() || "opencode";
687
+ const username = major === 2 ? "opencode" : environment.OPENCODE_SERVER_USERNAME?.trim() || "opencode";
643
688
  return { authorization: `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}` };
644
689
  }
645
690
 
691
+ function ownedEnvironment(environment, major) {
692
+ const clean = cleanChildEnvironment(environment);
693
+ const password = (major === 2 ? clean.OPENCODE_PASSWORD || clean.OPENCODE_SERVER_PASSWORD : clean.OPENCODE_SERVER_PASSWORD) || randomBytes(32).toString("hex");
694
+ clean.OPENCODE_SERVER_PASSWORD = password;
695
+ if (major === 2) {
696
+ clean.OPENCODE_PASSWORD = password;
697
+ clean.OPENCODE_SERVER_USERNAME = "opencode";
698
+ // 2.0.29's grouped Base64 regex exhausts Bun's default regexp stack on
699
+ // valid 10 MiB files. This VM ceiling fixes it without changing file bytes.
700
+ clean.BUN_JSC_maxRegExpStackSize ??= String(512 * 1024 * 1024);
701
+ }
702
+ return clean;
703
+ }
704
+
646
705
  function normalizeBaseUrl(value) {
647
706
  const url = new URL(value);
648
707
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("OpenCode server URL must use http or https.");
@@ -677,189 +736,11 @@ function delay(delayMs, signal) {
677
736
  });
678
737
  }
679
738
 
680
- function watchInteractions({ baseUrl, fetchImpl, headers, sessionId, workingDirectory, controller, onInteraction, onPermissionReplied, onPermissionsReconciled, onPermissionRejected, onDismiss, requestTurn }) {
681
- const seenIds = new Set();
682
- const messages = new Map();
683
- const parents = new Map();
684
- const interactionSessionIds = new Set([sessionId]);
685
- let resolveReady;
686
- let rejectReady;
687
- let subscribed = false;
688
- const ready = new Promise((resolve, reject) => {
689
- resolveReady = resolve;
690
- rejectReady = reject;
691
- });
692
- const dispatch = async (event) => {
693
- const type = event.type === "question.asked" ? "question" : event.type === "permission.asked" ? "permission" : null;
694
- const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
695
- const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
696
- const requestId = properties?.requestID ?? properties?.requestId ?? properties?.id;
697
- if (!type || (interactionSessionId !== sessionId && !await belongsToSession(interactionSessionId)) || !requestId || seenIds.has(`${type}:${requestId}`)) return;
698
- seenIds.add(`${type}:${requestId}`);
699
- const request = type === "permission" ? await hydratePermission(properties, interactionSessionId) : properties;
700
- void settleInteraction({ type, requestId, sessionId: interactionSessionId, request, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn });
701
- };
702
-
703
- const belongsToSession = async (candidate) => {
704
- const original = candidate;
705
- const visited = new Set();
706
- while (candidate && !visited.has(candidate)) {
707
- if (candidate === sessionId) {
708
- interactionSessionIds.add(original);
709
- return true;
710
- }
711
- visited.add(candidate);
712
- if (!parents.has(candidate)) parents.set(candidate, requestTurn(`/session/${encodeURIComponent(candidate)}`, { method: "GET" }, workingDirectory, controller)
713
- .then((session) => session?.parentID));
714
- candidate = await parents.get(candidate);
715
- }
716
- return false;
717
- };
718
-
719
- const hydratePermission = async (permission, interactionSessionId) => {
720
- const tool = permission.tool;
721
- if (!tool?.messageID || !tool.callID) return permission;
722
- if (!messages.has(tool.messageID)) {
723
- messages.set(tool.messageID, requestTurn(`/session/${encodeURIComponent(interactionSessionId)}/message?limit=100`, { method: "GET" }, workingDirectory, controller)
724
- .then((items) => items.flatMap((message) => message.info?.id === tool.messageID ? message.parts ?? [] : [])));
725
- }
726
- const part = (await messages.get(tool.messageID)).find((item) => item.callID === tool.callID);
727
- return part ? { ...permission, tool: { ...tool, name: part.tool, input: part.state?.input } } : permission;
728
- };
729
-
730
- const reconcile = async () => {
731
- const permissions = await requestTurn("/permission", { method: "GET" }, workingDirectory, controller);
732
- const pending = (await Promise.all((permissions ?? []).map(async (permission) => {
733
- return await belongsToSession(permission?.sessionID) ? permission : null;
734
- }))).filter(Boolean);
735
- await Promise.all(pending.map((permission) => dispatch({ type: "permission.asked", properties: permission })));
736
- for (const interactionSessionId of interactionSessionIds) {
737
- const requests = pending.filter((permission) => permission.sessionID === interactionSessionId);
738
- onPermissionsReconciled?.({ sessionId: interactionSessionId, requestIds: new Set(requests.map((permission) => permission.id)) });
739
- }
740
- };
741
-
742
- const watching = (async () => {
743
- while (!controller.signal.aborted) {
744
- try {
745
- const url = serverUrl(baseUrl, "/event", workingDirectory);
746
- const response = await fetchImpl(url, {
747
- headers: { ...headers, accept: "text/event-stream" },
748
- signal: controller.signal,
749
- });
750
- if (!response.ok) throw new OpenCodeRequestError(response.status);
751
- await reconcile();
752
- if (!subscribed) {
753
- subscribed = true;
754
- resolveReady();
755
- }
756
- for await (const event of readServerSentEvents(response, controller.signal)) {
757
- if (controller.signal.aborted) return;
758
- const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
759
- const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
760
- if (event.type === "permission.replied" && (interactionSessionId === sessionId || await belongsToSession(interactionSessionId))) {
761
- onPermissionReplied?.({ sessionId: interactionSessionId, requestId: properties?.requestID ?? properties?.requestId, reply: properties?.reply });
762
- await reconcile();
763
- continue;
764
- }
765
- await dispatch(event);
766
- }
767
- await reconcile();
768
- await delay(250, controller.signal).catch(() => undefined);
769
- } catch (error) {
770
- if (controller.signal.aborted) {
771
- if (!subscribed) rejectReady(controller.signal.reason);
772
- return;
773
- }
774
- if (!subscribed) {
775
- rejectReady(error);
776
- return;
777
- }
778
- await delay(250, controller.signal).catch(() => undefined);
779
- }
780
- }
781
- })();
782
- void watching.catch((error) => {
783
- if (!subscribed) rejectReady(error);
784
- else if (!controller.signal.aborted) process.stderr.write("OpenCode interaction watcher failed.\n");
785
- });
786
- return { ready };
787
- }
788
-
789
- async function settleInteraction({ type, requestId, sessionId, request: interactionRequest, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn }) {
790
- try {
791
- const decision = await abortable(Promise.resolve().then(() => onInteraction({
792
- type,
793
- sessionId,
794
- request: interactionRequest,
795
- signal: controller.signal,
796
- })), controller.signal);
797
- if (decision?.type === "cancelled" || decision?.type === "stopped") return;
798
- if (decision?.type === "stop") {
799
- onDismiss?.();
800
- if (type === "question") await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
801
- else await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply: "reject" }) }, workingDirectory, controller, [200, 204, 404], false);
802
- await requestTurn(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, workingDirectory, controller, [200, 204], false);
803
- return;
804
- }
805
- if (type === "question" && decision?.type === "answer") {
806
- await requestTurn(`/question/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ answers: decision.answers }) }, workingDirectory, controller, [200, 204, 404], false);
807
- } else if (type === "question" && decision?.type === "reject") {
808
- await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
809
- } else if (type === "permission" && (decision?.type === "reply" || decision?.type === "reject")) {
810
- const reply = decision.type === "reject" ? "reject" : decision.reply;
811
- if (!["once", "always", "reject"].includes(reply)) throw new Error("Invalid OpenCode permission decision.");
812
- try {
813
- await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply }) }, workingDirectory, controller, [200, 204], false);
814
- } catch (error) {
815
- if (error instanceof OpenCodeRequestError && error.status === 404) return;
816
- throw error;
817
- }
818
- if (reply === "reject") onPermissionRejected?.();
819
- } else {
820
- throw new Error(`Invalid OpenCode ${type} decision.`);
821
- }
822
- } catch (error) {
823
- if (!controller.signal.aborted) process.stderr.write(`OpenCode interaction handler error: ${error.message}\n`);
824
- }
825
- }
826
-
827
- async function* readServerSentEvents(response, signal) {
828
- const reader = response.body?.getReader();
829
- if (!reader) return;
830
- const abort = () => reader.cancel().catch(() => undefined);
831
- signal?.addEventListener("abort", abort, { once: true });
832
- const decoder = new TextDecoder();
833
- let buffer = "";
834
- try {
835
- while (true) {
836
- const { done, value } = await reader.read();
837
- if (done) break;
838
- buffer += decoder.decode(value, { stream: true });
839
- let boundary = buffer.indexOf("\n\n");
840
- while (boundary >= 0) {
841
- const chunk = buffer.slice(0, boundary);
842
- buffer = buffer.slice(boundary + 2);
843
- const lines = chunk.split("\n");
844
- const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
845
- const id = lines.find((line) => line.startsWith("id:"))?.slice(3).trim();
846
- const type = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
847
- if (data) {
848
- try {
849
- const event = JSON.parse(data);
850
- yield type ? { id, type, data: event } : event;
851
- } catch { /* ponytail: skip non-JSON SSE frames */ }
852
- }
853
- boundary = buffer.indexOf("\n\n");
854
- }
855
- }
856
- } finally {
857
- signal?.removeEventListener("abort", abort);
858
- }
859
- }
860
-
861
739
  function abortable(operation, signal) {
862
- if (signal.aborted) return Promise.reject(signal.reason);
740
+ if (signal.aborted) {
741
+ void Promise.resolve(operation).catch(() => undefined);
742
+ return Promise.reject(signal.reason);
743
+ }
863
744
  return new Promise((resolve, reject) => {
864
745
  const settle = (callback, value) => {
865
746
  signal.removeEventListener("abort", abort);