@usepipa/pipa 0.5.6 → 0.6.0-beta.2

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,57 @@ 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, backgroundResponses: 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
+ // Legacy v1 can reject subsequent work after uncertain admission or cancellation.
130
+ await adapter.ready?.(workingDirectory);
131
+ }
132
+
133
+ async function prepareArtifacts(sessionId, workingDirectory, persistent = false) {
134
+ if (useDataUrls || !artifactRoot) return;
135
+ try {
136
+ await mkdir(artifactRoot, { recursive: true, mode: 0o700 });
137
+ const directory = await sessionArtifactDirectory(artifactRoot, sessionId, workingDirectory);
138
+ if (!persistent) await remove(directory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
139
+ await mkdir(directory, { recursive: true, mode: 0o700 });
140
+ const stats = await lstat(directory);
141
+ if (!stats.isDirectory() || stats.isSymbolicLink()) throw new Error("Invalid artifact directory.");
142
+ await chmod(directory, 0o700);
143
+ return directory;
144
+ } catch { return undefined; }
145
+ }
146
+
147
+ async function response(text, sessionId, artifactDirectory, slackTurn) {
148
+ const parsed = slackTurn ? parseArtifactDeclaration(text) : { text };
149
+ const files = artifactDirectory && parsed.paths ? await readArtifacts(artifactDirectory, parsed.paths, options.onArtifactOpened) : [];
150
+ return { text: parsed.text, sessionId, ...(files.length ? { files } : {}) };
151
+ }
92
152
 
93
153
  async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
94
154
  const url = serverUrl(baseUrl, pathname, workingDirectory);
@@ -125,135 +185,53 @@ export function createOpenCodeExecutor(options = {}) {
125
185
  }
126
186
  }
127
187
 
128
- async function runTurn({ prompt, sessionId, model, defaultModel, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
188
+ async function runTurn({ prompt, sessionId, model, defaultModel, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled, onResponse, onError }) {
129
189
  if (!prompt?.trim()) throw new Error("A prompt is required.");
130
190
  if (stopReason) throw stopReason;
131
- let selectedModel = normalizeModel(model);
191
+ const legacySession = options.connection?.major === 1 || capabilities?.backgroundResponses === false;
192
+ if (legacySession && sessionId && activeSessions.has(sessionId)) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
193
+ let temporaryDirectory;
194
+ const selectedModel = normalizeModel(model);
132
195
  const newThreadModel = normalizeModel(defaultModel);
133
- const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
134
196
  const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
135
197
  const controller = new AbortController();
136
198
  const abort = () => controller.abort(signal.reason);
137
199
  if (signal?.aborted) abort();
138
200
  else signal?.addEventListener("abort", abort, { once: true });
139
201
  active.add(controller);
202
+ if (sessionId) activeSessions.set(sessionId, { controller, workingDirectory, resolved: false });
140
203
  let artifactDirectory;
141
204
 
142
205
  try {
143
206
  try {
144
- const files = await stageAttachments(attachments, temporaryDirectory, useDataUrls, controller.signal);
207
+ temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
208
+ controller.signal.throwIfAborted();
209
+ const files = await stageAttachments(attachments, temporaryDirectory, useDataUrls || !!onResponse, controller.signal);
145
210
  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
- }
211
+ await abortable(ready(workingDirectory), controller.signal);
212
+ const prepared = await adapter.resolveSession(sessionId, workingDirectory, controller);
213
+ const selectedSessionId = prepared.sessionId;
167
214
 
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 });
215
+ if (!capabilities.backgroundResponses && activeSessions.has(selectedSessionId) && activeSessions.get(selectedSessionId).controller !== controller) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
216
+ activeSessions.set(selectedSessionId, { controller, workingDirectory, resolved: true });
176
217
  await onSession?.(selectedSessionId);
177
218
  if (controller.signal.aborted) throw controller.signal.reason;
178
219
 
179
- if (slackTurn && !useDataUrls && artifactRoot) {
180
- try {
181
- await mkdir(artifactRoot, { recursive: true, mode: 0o700 });
182
- artifactDirectory = await sessionArtifactDirectory(artifactRoot, selectedSessionId, workingDirectory);
183
- await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
184
- await mkdir(artifactDirectory, { mode: 0o700 });
185
- await chmod(artifactDirectory, 0o700);
186
- } catch {}
187
- }
220
+ if (slackTurn) artifactDirectory = await prepareArtifacts(selectedSessionId, workingDirectory, capabilities.backgroundResponses && !!onResponse);
188
221
 
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
- }
222
+ const text = await adapter.execute({ ...prepared, model: selectedModel, defaultModel: newThreadModel, workingDirectory, controller, prompt, files,
223
+ instructions: turnInstructions(contextEnvironment, artifactDirectory), onInteraction, onPermissionReplied, onPermissionsReconciled,
224
+ ...(capabilities.backgroundResponses && onResponse ? {
225
+ onResponse: async (text, messageId, followSignal) => onResponse(await response(text, selectedSessionId, artifactDirectory, slackTurn), followSignal),
226
+ onError,
227
+ } : {}) });
228
+ if (text?.pending) return { pending: true, sessionId: selectedSessionId };
229
+ return await response(text, selectedSessionId, artifactDirectory, slackTurn);
230
+ } catch (error) {
231
+ if (controller.signal.aborted) throw controller.signal.reason;
232
+ throw error;
251
233
  } finally {
252
234
  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
235
  }
258
236
  } catch (error) {
259
237
  if (stopReason) throw stopReason;
@@ -266,7 +244,7 @@ export function createOpenCodeExecutor(options = {}) {
266
244
  process.stderr.write("Pipa could not remove temporary attachment files.\n");
267
245
  }
268
246
  }
269
- if (artifactDirectory) {
247
+ if (artifactDirectory && !(capabilities?.backgroundResponses && onResponse)) {
270
248
  try {
271
249
  await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
272
250
  } catch {
@@ -274,48 +252,82 @@ export function createOpenCodeExecutor(options = {}) {
274
252
  }
275
253
  }
276
254
  signal?.removeEventListener("abort", abort);
255
+ active.delete(controller);
256
+ for (const [sessionId, turn] of activeSessions) {
257
+ if (turn.controller === controller) activeSessions.delete(sessionId);
258
+ }
277
259
  }
278
260
  }
279
261
 
280
262
  return {
263
+ // Unknown until authenticated runtime negotiation has completed.
264
+ get capabilities() { return capabilities; },
265
+ ready,
281
266
  runTurn,
282
- async listModels(workingDirectory) {
267
+ async listModels(input = {}) {
268
+ const flat = typeof input === "string";
269
+ const { workingDirectory, signal } = flat ? { workingDirectory: input } : input;
283
270
  if (stopReason) throw stopReason;
284
271
  const controller = new AbortController();
285
- const timer = setTimeout(() => controller.abort(new Error("Model discovery timed out.")), 1_500);
272
+ const abort = () => controller.abort(signal.reason);
273
+ if (signal?.aborted) abort();
274
+ else signal?.addEventListener("abort", abort, { once: true });
286
275
  active.add(controller);
276
+ // Slack is acknowledged before discovery; allow slow catalogs without waiting forever.
277
+ const timer = setTimeout(() => controller.abort(new Error("Model discovery timed out.")), 30_000);
287
278
  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
- });
279
+ await abortable(ready(workingDirectory), controller.signal);
280
+ controller.signal.throwIfAborted();
281
+ if (!capabilities.modelDiscovery) throw new Error("OpenCode model discovery is not supported by this adapter.");
282
+ const catalog = await abortable(adapter.listModels(workingDirectory, controller.signal), controller.signal);
283
+ controller.signal.throwIfAborted();
284
+ return flat ? catalog.models.map((model) => ({ providerID: model.providerID, modelID: model.id, name: model.name })) : catalog;
297
285
  } finally {
298
286
  clearTimeout(timer);
287
+ controller.abort();
288
+ active.delete(controller);
289
+ signal?.removeEventListener("abort", abort);
290
+ }
291
+ },
292
+ async switchModel({ sessionId, model, workingDirectory, signal } = {}) {
293
+ if (stopReason) throw stopReason;
294
+ const controller = new AbortController();
295
+ const abort = () => controller.abort(signal.reason);
296
+ if (signal?.aborted) abort();
297
+ else signal?.addEventListener("abort", abort, { once: true });
298
+ active.add(controller);
299
+ try {
300
+ await abortable(ready(workingDirectory), controller.signal);
301
+ controller.signal.throwIfAborted();
302
+ if (!capabilities.liveModelSwitch) throw new Error("OpenCode live model switching is not supported by this adapter.");
303
+ return await adapter.switchModel(sessionId, model, workingDirectory, controller.signal);
304
+ } finally {
305
+ controller.abort();
299
306
  active.delete(controller);
307
+ signal?.removeEventListener("abort", abort);
300
308
  }
301
309
  },
302
310
  async abortTurn(sessionId, reason = new Error("OpenCode turn aborted.")) {
303
311
  const turn = activeSessions.get(sessionId);
304
- if (!turn) return;
305
- const abortController = new AbortController();
312
+ if (!turn) {
313
+ if (capabilities?.backgroundResponses) await adapter.abortTurn(sessionId);
314
+ return;
315
+ }
306
316
  try {
307
- await request(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, turn.workingDirectory, abortController, [200, 204, 404], false);
317
+ if (turn.resolved) await adapter.abortTurn(sessionId, turn.workingDirectory);
308
318
  } catch {
309
319
  // Local cancellation still supersedes the turn if OpenCode's abort request fails.
310
320
  } finally {
311
- abortController.abort(reason);
312
321
  turn.controller.abort(reason);
313
322
  }
314
323
  },
315
324
  stopAll(reason = new PipaStoppedError()) {
316
325
  stopReason ??= reason;
326
+ readinessController.abort(stopReason);
317
327
  for (const controller of active) controller.abort(stopReason);
328
+ adapter?.stopAll?.(stopReason);
318
329
  },
330
+ async drain() { await adapter?.drain?.(); },
319
331
  };
320
332
  }
321
333
 
@@ -329,19 +341,22 @@ async function sessionArtifactDirectory(root, sessionId, workingDirectory) {
329
341
  return path.join(resolvedRoot, sessionId);
330
342
  }
331
343
 
332
- export function startOpenCodeServer(config, options = {}) {
344
+ export async function startOpenCodeServer(config, options = {}) {
345
+ const identity = parseOpenCodeVersion(await (options.checkOpenCode ?? runOpenCodeVersion)(options));
346
+ options.signal?.throwIfAborted();
347
+ const environment = ownedEnvironment(options.environment ?? process.env, identity.major);
333
348
  const spawn = options.spawn ?? crossSpawn;
334
349
  const platform = options.platform ?? process.platform;
335
350
  const child = spawn("opencode", [
336
351
  "serve",
337
352
  "--hostname", config.openCodeHostname,
338
353
  "--port", String(config.openCodePort),
339
- "--log-level", "ERROR",
354
+ "--log-level", identity.major === 1 ? "ERROR" : "error",
340
355
  ], {
341
356
  cwd: config.workingDirectory,
342
- env: cleanChildEnvironment(options.environment ?? process.env),
357
+ env: environment,
343
358
  shell: false,
344
- stdio: "inherit",
359
+ stdio: config.openCodePort === 0 ? ["ignore", "pipe", "pipe"] : "inherit",
345
360
  });
346
361
  let stopping = false;
347
362
  const exit = waitForExit(child).then((code) => {
@@ -349,14 +364,19 @@ export function startOpenCodeServer(config, options = {}) {
349
364
  });
350
365
  void exit.catch(() => undefined);
351
366
 
352
- return {
367
+ const listening = config.openCodePort === 0 ? readListeningUrl(child, options.startupTimeoutMs, options.signal) : null;
368
+ void listening?.catch(() => undefined);
369
+ const server = {
353
370
  async ready() {
354
371
  const controller = new AbortController();
355
372
  const hostname = config.openCodeHostname.includes(":") && !config.openCodeHostname.startsWith("[") ? `[${config.openCodeHostname}]` : config.openCodeHostname;
356
373
  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),
374
+ const baseUrl = listening ? await Promise.race([listening, exit.then(() => { throw new Error("OpenCode stopped before reporting its listening URL."); })]) : `http://${hostname}:${config.openCodePort}`;
375
+ child.stdout?.resume();
376
+ child.stderr?.resume();
377
+ server.connection = await Promise.race([
378
+ checkOpenCodeConnection(baseUrl, config.workingDirectory, { ...options, environment, identity,
379
+ signal: AbortSignal.any([controller.signal, ...(options.signal ? [options.signal] : [])]) }),
360
380
  exit.then(() => { throw new Error("OpenCode stopped before workspace readiness."); }),
361
381
  ]);
362
382
  } finally { controller.abort(); }
@@ -368,27 +388,32 @@ export function startOpenCodeServer(config, options = {}) {
368
388
  terminateChild(child, platform, signal);
369
389
  },
370
390
  };
391
+ return server;
371
392
  }
372
393
 
373
394
  export async function runOpenCodeVersion(options = {}) {
395
+ options.signal?.throwIfAborted();
374
396
  const spawn = options.spawn ?? crossSpawn;
375
397
  const platform = options.platform ?? process.platform;
376
- const timeoutMs = options.timeoutMs ?? 30_000;
398
+ const timeoutMs = options.timeoutMs;
377
399
  const child = spawn("opencode", ["--version"], {
378
400
  env: cleanChildEnvironment(options.environment ?? process.env),
379
401
  shell: false,
380
402
  stdio: ["ignore", "pipe", "pipe"],
381
403
  });
382
404
  let timer;
405
+ const abort = () => terminateChild(child, platform);
406
+ options.signal?.addEventListener("abort", abort, { once: true });
383
407
  try {
384
408
  const operation = Promise.all([collect(child.stdout), collect(child.stderr), waitForExit(child)]);
385
- const timeout = new Promise((_, reject) => {
409
+ const timeout = timeoutMs === undefined ? null : new Promise((_, reject) => {
386
410
  timer = setTimeout(() => {
387
411
  terminateChild(child, platform);
388
412
  reject(new Error(`OpenCode version check timed out after ${timeoutMs}ms.`));
389
413
  }, timeoutMs);
390
414
  });
391
- const [stdout, stderr, code] = await Promise.race([operation, timeout]);
415
+ const result = timeout ? Promise.race([operation, timeout]) : operation;
416
+ const [stdout, stderr, code] = await (options.signal ? abortable(result, options.signal) : result);
392
417
  if (code !== 0) throw new Error(stderr.trim() || "OpenCode version check failed.");
393
418
  return stdout.trim();
394
419
  } catch (error) {
@@ -396,19 +421,21 @@ export async function runOpenCodeVersion(options = {}) {
396
421
  throw error;
397
422
  } finally {
398
423
  clearTimeout(timer);
424
+ options.signal?.removeEventListener("abort", abort);
399
425
  }
400
426
  }
401
427
 
402
428
  async function stageAttachments(attachments, temporaryDirectory, useDataUrls, signal) {
403
429
  const files = [];
404
430
  for (const [index, attachment] of attachments.entries()) {
431
+ 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
432
  let data;
406
433
  try {
407
434
  data = await abortable(attachment.fetchData(), signal);
408
435
  } catch {
409
436
  throw new Error("Could not read one of the attached files. Please try uploading it again.");
410
437
  }
411
- if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 100 MB or smaller.");
438
+ if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 10 MiB or smaller.");
412
439
  try {
413
440
  const filename = sanitizeFilename(path.basename(attachment.name || "attachment"), "attachment");
414
441
  const file = path.join(temporaryDirectory, `${index + 1}-${filename}`);
@@ -426,23 +453,15 @@ async function stageAttachments(attachments, temporaryDirectory, useDataUrls, si
426
453
  return files;
427
454
  }
428
455
 
429
- function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
430
- const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
456
+ function turnInstructions(contextEnvironment, artifactDirectory) {
431
457
  const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
432
458
  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
- const restartCommand = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack" && contextEnvironment.PIPA_CURRENT_SLACK_CHANNEL_ID
434
- ? `pipa restart --channel ${contextEnvironment.PIPA_CURRENT_SLACK_CHANNEL_ID}${contextEnvironment.PIPA_CURRENT_SLACK_THREAD_TS ? ` --thread ${contextEnvironment.PIPA_CURRENT_SLACK_THREAD_TS}` : ""}`
435
- : "pipa restart";
436
- instructions.push(`When asked to restart Pipa, run \`${restartCommand}\`; existing messaging authorization is sufficient. It requests a detached restart and may end this turn. Use \`pipa restart --status\` to inspect the durable outcome; do not claim completion from the request alone. Both commands must run on the Pipa host, not a remote attached OpenCode host. If you lack command access to the Pipa host, explain that limitation instead of running them remotely. The Pipa profile home on that host is ${JSON.stringify(path.resolve(process.env.PIPA_HOME || os.homedir()))}; ensure PIPA_HOME has this value in the command environment. Do not use sequential stop/start or OpenCode /instance/dispose: that disposes an instance, not restarts the server.`);
437
459
  if (context.length) instructions.push(`Slack context for this turn (provided here, not as shell environment variables):\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}`);
438
460
  if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
439
461
  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
462
  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
463
  }
442
- return {
443
- parts,
444
- ...(instructions.length ? { system: instructions.join("\n\n") } : {}),
445
- };
464
+ return instructions.join("\n\n");
446
465
  }
447
466
 
448
467
  function parseArtifactDeclaration(text) {
@@ -494,7 +513,7 @@ async function readArtifacts(directory, paths, onOpened) {
494
513
  const before = await handle.stat({ bigint: true });
495
514
  await onOpened?.(filename);
496
515
  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.");
516
+ if (!before.isFile() || size > MAX_ARTIFACT_BYTES || total + size > MAX_ARTIFACT_BYTES) throw new Error("Artifact exceeds delivery limits.");
498
517
  const data = Buffer.alloc(size + 1);
499
518
  let bytesRead = 0;
500
519
  while (bytesRead < data.length) {
@@ -526,25 +545,6 @@ function sanitizeFilename(value, fallback = "artifact") {
526
545
  return Array.from(sanitized).reduce((result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result, "") || fallback;
527
546
  }
528
547
 
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
548
  function ownedServer(baseUrl, child, exit, platform) {
549
549
  let stopping = false;
550
550
  let rejectFailure;
@@ -592,31 +592,89 @@ function externalServer(baseUrl) {
592
592
  };
593
593
  }
594
594
 
595
- async function waitForWorkspace(baseUrl, workingDirectory, fetchImpl, headers, timeoutMs, signal) {
596
- const deadline = Date.now() + timeoutMs;
595
+ export async function checkOpenCodeConnection(baseUrl, workingDirectory, options = {}) {
596
+ baseUrl = normalizeBaseUrl(baseUrl);
597
+ const fetchImpl = options.fetch ?? fetch;
598
+ const environment = options.environment ?? process.env;
599
+ const signal = options.signal;
600
+ const deadline = options.startupTimeoutMs === undefined ? Infinity : Date.now() + options.startupTimeoutMs;
601
+ let connection;
602
+ async function read(pathname, headers, directory, candidate = false) {
603
+ const url = serverUrl(baseUrl, pathname, directory);
604
+ const response = await fetchImpl(url, {
605
+ headers,
606
+ redirect: "manual",
607
+ signal: AbortSignal.any([AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))), ...(signal ? [signal] : [])]),
608
+ });
609
+ if (!response.ok) await response.body?.cancel().catch(() => undefined);
610
+ 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.");
611
+ if ([502, 503, 504].includes(response.status)) throw new OpenCodeReadinessError("OpenCode is temporarily unavailable.");
612
+ if (candidate && [404, 405].includes(response.status)) return null;
613
+ if (!response.ok) throw new Error(`OpenCode protocol check failed (HTTP ${response.status}). Check the server URL and supported runtime.`);
614
+ try { return await response.json(); }
615
+ catch (error) {
616
+ if (!(error instanceof SyntaxError)) throw error;
617
+ if (candidate) return null; // Legacy identity routes on v2 serve the web UI.
618
+ throw new Error("OpenCode protocol check returned invalid JSON. Check the server URL and runtime.");
619
+ }
620
+ }
597
621
  while (Date.now() < deadline) {
622
+ signal?.throwIfAborted();
598
623
  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.
624
+ if (!connection) {
625
+ const v1Headers = authenticationHeaders(environment, 1);
626
+ const health = await read("/global/health", v1Headers, undefined, true);
627
+ if (typeof health?.healthy === "boolean" && typeof health.version === "string") {
628
+ const identity = parseOpenCodeVersion(health.version);
629
+ if (identity.major !== 1) throw new Error("OpenCode identity/protocol mismatch at /global/health.");
630
+ if (!health.healthy) throw new OpenCodeReadinessError("OpenCode is not healthy yet.");
631
+ connection = { ...identity, headers: v1Headers };
632
+ } else {
633
+ const headers = authenticationHeaders(environment, 2);
634
+ const info = await read("/api/info", headers, undefined, true);
635
+ if (!info || typeof info.version !== "string" || !Number.isSafeInteger(info.pid) || info.pid <= 0
636
+ || !Array.isArray(info.urls) || !info.urls.every((url) => typeof url === "string") || typeof info.paths?.tmp !== "string") {
637
+ throw new Error("OpenCode identity protocol is unsupported. Check the selected server URL and install a supported v1 or v2 runtime.");
638
+ }
639
+ const identity = parseOpenCodeVersion(info.version);
640
+ if (identity.major !== 2) throw new Error("OpenCode identity/protocol mismatch at /api/info.");
641
+ connection = { ...identity, headers };
642
+ }
643
+ if (options.identity && options.identity.version !== connection.version) throw new Error("OpenCode CLI/server identity mismatch. Check the executable and selected listening server.");
644
+ }
645
+ const headers = connection.headers;
646
+ if (connection.major === 2) {
647
+ const locationUrl = `/api/location?${new URLSearchParams({ "location[directory]": workingDirectory })}`;
648
+ const location = await read(locationUrl, headers);
649
+ if (typeof location?.directory !== "string" || !path.isAbsolute(location.directory) || typeof location.project?.id !== "string"
650
+ || typeof location.project?.directory !== "string" || typeof location.project?.canonical !== "string") throw new Error("OpenCode location protocol has an invalid schema.");
651
+ if (path.resolve(location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode workspace identity mismatch. Select a server serving the configured working directory.");
652
+ } else {
653
+ const location = await read("/path", headers, workingDirectory);
654
+ if (typeof location?.directory !== "string" || !path.isAbsolute(location.directory)) throw new Error("OpenCode workspace protocol has an invalid schema.");
655
+ if (path.resolve(location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode workspace identity mismatch. Select a server serving the configured working directory.");
656
+ const sessions = await read("/session/status", headers, workingDirectory);
657
+ if (!sessions || typeof sessions !== "object" || Array.isArray(sessions)
658
+ || !Object.values(sessions).every((session) => session && typeof session === "object" && typeof session.type === "string")) throw new Error("OpenCode workspace protocol has an invalid status schema.");
659
+ }
660
+ return { ...connection, baseUrl, workingDirectory };
661
+ } catch (error) {
662
+ if (signal?.aborted) throw signal.reason;
663
+ if (!(error instanceof OpenCodeReadinessError) && !isNetworkError(error) && error.name !== "TimeoutError") throw error;
608
664
  }
609
665
  await delay(Math.min(250, Math.max(0, deadline - Date.now())), signal);
610
666
  }
611
- throw new Error("OpenCode workspace readiness check timed out.");
667
+ throw new OpenCodeReadinessError("OpenCode workspace readiness check timed out. Check the server and configured working directory.");
612
668
  }
613
669
 
614
- function readListeningUrl(child, timeoutMs) {
670
+ function readListeningUrl(child, timeoutMs, signal) {
615
671
  return new Promise((resolve, reject) => {
616
672
  let output = "";
617
673
  const cleanup = () => {
618
674
  child.stdout?.off("data", inspect);
619
675
  child.stderr?.off("data", inspect);
676
+ child.off("close", closed);
677
+ signal?.removeEventListener("abort", abort);
620
678
  };
621
679
  const finish = (callback, value) => {
622
680
  clearTimeout(timer);
@@ -629,20 +687,39 @@ function readListeningUrl(child, timeoutMs) {
629
687
  if (!match) return;
630
688
  finish(resolve, normalizeBaseUrl(match[0]));
631
689
  };
632
- const timer = setTimeout(() => finish(reject, new Error("OpenCode server did not report its listening URL.")), timeoutMs);
633
- timer.unref?.();
690
+ const timer = timeoutMs === undefined ? null : setTimeout(() => finish(reject, new Error("OpenCode server did not report its listening URL.")), timeoutMs);
691
+ const closed = () => finish(reject, new Error("OpenCode stopped before reporting its listening URL."));
692
+ const abort = () => finish(reject, signal.reason);
693
+ timer?.unref?.();
634
694
  child.stdout?.on("data", inspect);
635
695
  child.stderr?.on("data", inspect);
696
+ child.once("close", closed);
697
+ if (signal?.aborted) abort();
698
+ else signal?.addEventListener("abort", abort, { once: true });
636
699
  });
637
700
  }
638
701
 
639
- function authenticationHeaders(environment) {
640
- const password = environment.OPENCODE_SERVER_PASSWORD;
702
+ function authenticationHeaders(environment, major = 1) {
703
+ const password = major === 2 ? environment.OPENCODE_PASSWORD || environment.OPENCODE_SERVER_PASSWORD : environment.OPENCODE_SERVER_PASSWORD;
641
704
  if (!password) return {};
642
- const username = environment.OPENCODE_SERVER_USERNAME?.trim() || "opencode";
705
+ const username = major === 2 ? "opencode" : environment.OPENCODE_SERVER_USERNAME?.trim() || "opencode";
643
706
  return { authorization: `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}` };
644
707
  }
645
708
 
709
+ function ownedEnvironment(environment, major) {
710
+ const clean = cleanChildEnvironment(environment);
711
+ const password = (major === 2 ? clean.OPENCODE_PASSWORD || clean.OPENCODE_SERVER_PASSWORD : clean.OPENCODE_SERVER_PASSWORD) || randomBytes(32).toString("hex");
712
+ clean.OPENCODE_SERVER_PASSWORD = password;
713
+ if (major === 2) {
714
+ clean.OPENCODE_PASSWORD = password;
715
+ clean.OPENCODE_SERVER_USERNAME = "opencode";
716
+ // 2.0.29's grouped Base64 regex exhausts Bun's default regexp stack on
717
+ // valid 10 MiB files. This VM ceiling fixes it without changing file bytes.
718
+ clean.BUN_JSC_maxRegExpStackSize ??= String(512 * 1024 * 1024);
719
+ }
720
+ return clean;
721
+ }
722
+
646
723
  function normalizeBaseUrl(value) {
647
724
  const url = new URL(value);
648
725
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("OpenCode server URL must use http or https.");
@@ -677,189 +754,11 @@ function delay(delayMs, signal) {
677
754
  });
678
755
  }
679
756
 
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
757
  function abortable(operation, signal) {
862
- if (signal.aborted) return Promise.reject(signal.reason);
758
+ if (signal.aborted) {
759
+ void Promise.resolve(operation).catch(() => undefined);
760
+ return Promise.reject(signal.reason);
761
+ }
863
762
  return new Promise((resolve, reject) => {
864
763
  const settle = (callback, value) => {
865
764
  signal.removeEventListener("abort", abort);