@usepipa/pipa 0.6.0-beta.1 → 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.
@@ -1,19 +1,25 @@
1
1
  import { OpenCode } from "@opencode/client";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import { lstat, readFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
4
3
  import path from "node:path";
5
4
  import { setTimeout as delay } from "node:timers/promises";
6
- import { pipaPaths, writePrivateJson } from "./state.mjs";
7
5
 
8
6
  export function createV2Adapter(options) {
7
+ const observers = new Map();
8
+ const controllers = new Set();
9
+ let events;
10
+ let eventTask;
11
+ let connected = false;
12
+ let stopped;
13
+ let stopping = [];
9
14
  const client = OpenCode.make({ baseUrl: options.baseUrl, headers: options.headers, fetch: async (url, init) => {
10
- const signal = AbortSignal.any([...(init.signal ? [init.signal] : []), AbortSignal.timeout(options.connectionRequestTimeoutMs ?? 5_000)]);
15
+ const pathname = new URL(url).pathname;
16
+ const streaming = pathname === "/api/event";
17
+ const modelRead = (init.method ?? "GET").toUpperCase() === "GET" && ["/api/model", "/api/model/default"].includes(pathname);
18
+ const signal = streaming ? init.signal : AbortSignal.any([...(init.signal ? [init.signal] : []), AbortSignal.timeout(options.connectionRequestTimeoutMs ?? (modelRead ? 30_000 : 5_000))]);
11
19
  const response = await options.fetch(url, { ...init, signal });
12
- if (!response.body) return response;
20
+ if (!response.body || streaming) return response;
13
21
  const reader = response.body.getReader();
14
22
  let abort;
15
- // Compressed native responses can stop reading without rejecting on network
16
- // abort. Settle the SDK body independently so admission recovery can proceed.
17
23
  return new Response(new ReadableStream({
18
24
  start(controller) {
19
25
  abort = () => {
@@ -43,66 +49,23 @@ export function createV2Adapter(options) {
43
49
  },
44
50
  }), { status: response.status, statusText: response.statusText, headers: response.headers });
45
51
  } });
46
- const journalFile = options.recoveryFile ?? pipaPaths(options.environment.PIPA_HOME).openCodeRecovery;
47
- const prefix = `pipa-${createHash("sha256").update(path.resolve(journalFile)).digest("hex").slice(0, 16)}-`;
48
- const turns = new Map();
49
- let records;
50
- let mutationTail = Promise.resolve();
51
- let readiness;
52
- let blocked;
53
- let fatalError;
54
52
 
55
- function unavailable(cause) {
56
- if (!fatalError) {
57
- fatalError = new Error("OpenCode server became unavailable after bounded connection recovery.", { cause });
58
- options.onFatal?.(fatalError);
59
- }
60
- return fatalError;
61
- }
62
-
63
- async function readWithRecovery(operation, signal, confirming = false) {
64
- let disconnectedAt;
53
+ async function readWithRecovery(operation, signal) {
54
+ const start = Date.now();
65
55
  while (true) {
66
- if (fatalError) throw fatalError;
56
+ signal?.throwIfAborted();
67
57
  try { return await operation(signal); }
68
58
  catch (error) {
69
- if (confirming && signal.aborted && retryable(error)) throw unavailable(error);
70
- signal.throwIfAborted();
71
- if (!retryable(error)) throw error;
72
- disconnectedAt ??= Date.now();
73
- if (Date.now() - disconnectedAt >= (options.connectionRecoveryTimeoutMs ?? 10_000)) {
74
- // Confirm through the same authenticated authoritative read, using a
75
- // fresh bounded probe. Healthy long-running agent work has no deadline.
76
- const probe = AbortSignal.any([signal, AbortSignal.timeout(options.connectionProbeTimeoutMs ?? 1_000)]);
77
- try { return await operation(probe); }
78
- catch (cause) {
79
- signal.throwIfAborted();
80
- if (!retryable(cause) && !probe.aborted) throw cause;
81
- throw unavailable(cause);
82
- }
83
- }
84
- await delay(options.pollIntervalMs, undefined, { signal }).catch((cause) => {
85
- if (confirming && signal.aborted) throw unavailable(error);
86
- throw cause;
87
- });
59
+ signal?.throwIfAborted();
60
+ if (!retryable(error) || Date.now() - start >= (options.connectionRecoveryTimeoutMs ?? 10_000)) throw error;
61
+ await delay(options.pollIntervalMs ?? 100, undefined, { signal });
88
62
  }
89
63
  }
90
64
  }
91
65
 
92
- async function mutate(change, committed) {
93
- const operation = mutationTail.then(async () => {
94
- const next = change(records);
95
- await writePrivateJson(journalFile, { version: 1, records: next });
96
- records = next;
97
- committed?.(next);
98
- });
99
- mutationTail = operation.catch(() => undefined);
100
- return operation;
101
- }
102
-
103
66
  async function lookup(sessionId, workingDirectory, signal) {
104
67
  let session;
105
- try { session = await readWithRecovery((readSignal) => client.session.get({ sessionID: sessionId }, { signal: readSignal }), signal); }
68
+ try { session = await readWithRecovery((signal) => client.session.get({ sessionID: sessionId }, { signal }), signal); }
106
69
  catch (error) {
107
70
  if (error._tag === "SessionNotFoundError" && error.sessionID === sessionId) return null;
108
71
  throw error;
@@ -112,611 +75,429 @@ export function createV2Adapter(options) {
112
75
  return session;
113
76
  }
114
77
 
115
- async function messages(sessionId, signal) {
116
- const result = [];
117
- const ids = new Set();
118
- const cursors = new Set();
119
- let cursor;
120
- do {
121
- const page = await client.message.list({ sessionID: sessionId, limit: 100, ...(cursor ? { cursor } : { order: "asc" }) }, { signal });
122
- if (!Array.isArray(page?.data) || !page.cursor || (page.cursor.next !== null && typeof page.cursor.next !== "string")) throw new Error("OpenCode returned an invalid message projection.");
123
- for (const message of page.data) {
124
- if (typeof message?.id !== "string" || typeof message.type !== "string" || typeof message.time?.created !== "number"
125
- || (message.type === "assistant" && !Array.isArray(message.content))
126
- || (message.type === "idle" && !["succeeded", "failed", "interrupted"].includes(message.outcome))) throw new Error("OpenCode returned an invalid message projection.");
127
- if (ids.has(message.id)) throw new Error("OpenCode returned duplicate projected messages.");
128
- ids.add(message.id);
129
- result.push(message);
130
- }
131
- cursor = page.cursor.next;
132
- if (cursor && cursors.has(cursor)) throw new Error("OpenCode repeated a message cursor.");
133
- cursors.add(cursor);
134
- } while (cursor);
135
- return result;
78
+ async function listModels(workingDirectory, signal) {
79
+ const input = { location: { directory: workingDirectory } };
80
+ const [catalog, defaults] = await readWithRecovery((signal) => Promise.all([
81
+ client.model.list(input, { signal }), client.model.default(input, { signal }),
82
+ ]), signal);
83
+ for (const snapshot of [catalog, defaults]) {
84
+ if (typeof snapshot?.location?.directory !== "string" || path.resolve(snapshot.location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode model workspace identity mismatch.");
85
+ }
86
+ if (!Array.isArray(catalog.data) || catalog.data.some((model) => !model || typeof model.id !== "string" || !model.id
87
+ || typeof model.providerID !== "string" || !model.providerID || typeof model.name !== "string" || typeof model.enabled !== "boolean"
88
+ || !Array.isArray(model.variants) || model.variants.some((variant) => typeof variant?.id !== "string" || !variant.id))) throw new Error("OpenCode returned an invalid model catalog.");
89
+ const models = catalog.data.filter((model) => model.enabled).map((model) => ({
90
+ providerID: model.providerID, id: model.id, name: model.name, variants: [...new Set(["default", ...model.variants.map((variant) => variant.id)])],
91
+ }));
92
+ const selected = defaults.data;
93
+ if (selected !== null && (!selected || typeof selected.providerID !== "string" || typeof selected.id !== "string")) throw new Error("OpenCode returned an invalid default model.");
94
+ const defaultModel = selected && models.find((model) => model.providerID === selected.providerID && model.id === selected.id);
95
+ return { models, defaultModel: defaultModel ? { providerID: defaultModel.providerID, id: defaultModel.id, variant: "default" } : null };
136
96
  }
137
97
 
138
- async function projection(record, signal) {
139
- return readWithRecovery((readSignal) => readProjection(record, readSignal), signal);
98
+ function settleWaiters(observer, value, error) {
99
+ for (const waiter of observer.waiters) {
100
+ if (error) waiter.reject(error);
101
+ else waiter.resolve(value);
102
+ }
140
103
  }
141
104
 
142
- async function readProjection(record, signal) {
143
- // Native promotion atomically removes pending input and projects its message.
144
- // Read inbox first so a lost cancel reply cannot hide that handoff between reads.
145
- // KTD3's single-writer contract applies during the turn; observed foreign
146
- // input prevents session-wide interruption and suppresses local delivery.
147
- const inbox = await client.session.inbox.list({ sessionID: record.sessionId }, { signal });
148
- const timeline = await messages(record.sessionId, signal);
149
- if (!Array.isArray(inbox) || inbox.some((item) => typeof item?.id !== "string" || item.sessionID !== record.sessionId || typeof item.type !== "string")) throw new Error("OpenCode returned an invalid inbox projection.");
150
- const baseline = new Set(record.baseline);
151
- const fresh = timeline.filter((message) => !baseline.has(message.id));
152
- const foreign = fresh.some((message) => ["user", "synthetic", "shell"].includes(message.type) && message.id !== record.id)
153
- || inbox.some((item) => item.id !== record.id);
154
- const index = fresh.findIndex((message) => message.id === record.id && message.type === "user");
155
- const own = index >= 0 ? fresh[index] : null;
156
- const idle = index >= 0 ? fresh.slice(index + 1).find((message) => message.type === "idle") : null;
157
- const assistant = idle ? fresh.slice(index + 1, fresh.indexOf(idle)).findLast((message) => message.type === "assistant") : null;
158
- let dismissed = false;
159
- let rejected = false;
160
- let uncertainRejection = false;
161
- if (own && !idle && !foreign && record.dismissal && !inbox.length) {
162
- const message = fresh.slice(index + 1).find((message) => message.id === record.dismissal.messageId && message.type === "assistant");
163
- const tool = message?.content.find((part) => part.type === "tool" && part.id === record.dismissal.toolId && part.name === "question");
164
- if (typeof message?.time.completed === "number" && message.error?.type === "aborted" && tool?.state.status === "error" && tool.state.error?.type === "aborted") {
165
- let cancelled;
166
- try {
167
- const form = await client.session.form.get({ sessionID: record.sessionId, formID: record.dismissal.formId }, { signal });
168
- cancelled = form.id === record.dismissal.formId && form.sessionID === record.sessionId && form.state.status === "cancelled";
169
- } catch (error) { if (error._tag !== "FormNotFoundError" || error.id !== record.dismissal.formId) throw error; cancelled = true; }
170
- // Native question cancellation can stop execution with reason=shutdown,
171
- // which deliberately has no idle projection. This is not general success:
172
- // require journaled dismissal intent, its exact aborted tool/assistant,
173
- // native cancellation/absence and no active execution before cleanup.
174
- if (cancelled) dismissed = !(await client.session.active({ signal }))[record.sessionId];
175
- }
176
- }
177
- if (own && !idle && !foreign && record.rejection && !inbox.length) {
178
- const rejection = record.rejection;
179
- const message = fresh.slice(index + 1).find((message) => message.id === rejection.messageId && message.type === "assistant");
180
- const tool = message?.content.find((part) => part.type === "tool" && part.id === rejection.toolId);
181
- if (typeof message?.time.completed === "number" && message.error?.type === "aborted" && tool?.state.status === "error" && tool.state.error?.type === "aborted") {
182
- const pending = await client.permission.list({ sessionID: record.sessionId }, { signal });
183
- if (!Array.isArray(pending)) throw new Error("OpenCode returned an invalid permission projection.");
184
- // A root permission denial can abort without idle, just like dismissal.
185
- // Confirm the journaled tool and native settlement, never infer success.
186
- if (!pending.length && !(await client.session.active({ signal }))[record.sessionId]) {
187
- rejected = rejection.confirmed;
188
- uncertainRejection = !rejection.confirmed;
189
- }
190
- }
191
- }
192
- return { foreign, own, idle, assistant, inbox, dismissed, rejected, uncertainRejection };
105
+ async function report(observer, error) {
106
+ await observer.onError?.(error, observer.controller.signal);
107
+ settleWaiters(observer, undefined, error);
193
108
  }
194
109
 
195
- async function cleanup(record) {
196
- // Turn cancellation must never cancel removal of trusted context or recovery state.
197
- const signal = AbortSignal.timeout(options.cleanupTimeoutMs ?? 5_000);
198
- try {
199
- return await cleanupOwned(record, signal);
200
- } catch (error) {
201
- if (!fatalError && (retryable(error) || signal.aborted)) {
202
- // Cleanup can expire before the ordinary recovery window. Confirm through
203
- // a fresh read-only authenticated probe, independent of both expired cleanup
204
- // and cancelled turn signals. This adds at most one bounded probe window.
205
- const probe = AbortSignal.timeout(options.connectionProbeTimeoutMs ?? 1_000);
206
- try { await readWithRecovery((probeSignal) => client.session.get({ sessionID: record.sessionId }, { signal: probeSignal }), probe, true); }
207
- catch { if (fatalError) throw fatalError; }
208
- }
209
- throw error;
210
- }
110
+ function detach(observer, reason = new Error("OpenCode observer stopped.")) {
111
+ observer.controller.abort(reason);
112
+ observer.initialized.reject(reason);
113
+ settleWaiters(observer, undefined, reason);
114
+ for (const entry of observer.interactions.values()) entry.settled.resolve();
115
+ if (observers.get(observer.sessionId) === observer) observers.delete(observer.sessionId);
116
+ if (!observers.size) events?.abort(reason);
211
117
  }
212
118
 
213
- async function cleanupOwned(record, signal) {
214
- if (fatalError) throw fatalError;
215
- if (!await lookup(record.sessionId, record.workingDirectory, signal)) {
216
- await mutate((items) => items.filter((item) => item.key !== record.key));
217
- return;
119
+ async function belongs(observer, candidate) {
120
+ const original = candidate;
121
+ const visited = new Set();
122
+ while (candidate && !visited.has(candidate)) {
123
+ visited.add(candidate);
124
+ let session;
125
+ try { session = await client.session.get({ sessionID: candidate }, { signal: observer.controller.signal }); }
126
+ catch (error) { if (error._tag === "SessionNotFoundError") return false; throw error; }
127
+ if (session?.id !== candidate || typeof session.location?.directory !== "string"
128
+ || path.resolve(session.location.directory) !== path.resolve(observer.workingDirectory)) return false;
129
+ if (candidate === observer.sessionId) { observer.interactionSessions.add(original); return true; }
130
+ candidate = session.parentID;
218
131
  }
219
- let failure;
220
- let foreign = Boolean(record.foreign);
221
- try {
222
- if (record.phase !== "prepared") {
223
- let state = await projection(record, signal);
224
- foreign ||= state.foreign;
225
- if (state.uncertainRejection) throw new Error("OpenCode permission rejection acknowledgement remains uncertain.");
226
- if (state.inbox.some((item) => item.id === record.id)) {
227
- try { await client.session.inbox.cancel({ sessionID: record.sessionId, inboxID: record.id }, { signal }); }
228
- catch (error) {
229
- // Delivery can race cancellation; a lost reply is reconciled rather than
230
- // treated as either an acknowledged cancellation or a missing session.
231
- if (!retryable(error) && !["ConflictError", "MessageNotFoundError"].includes(error._tag)) throw error;
232
- }
233
- state = await projection(record, signal);
234
- foreign ||= state.foreign;
235
- if (state.inbox.some((item) => item.id === record.id)) throw new Error("Pipa input cancellation is not acknowledged.");
236
- if (!state.own) {
237
- record.phase = "cancelled";
238
- await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
239
- }
240
- }
241
- if (state.own && !state.idle && !state.dismissed && !state.rejected) {
242
- if (foreign || record.foreign) throw new Error("OpenCode attribution conflict: a foreign writer is still active.");
243
- // Native interrupt acknowledges acceptance, not settlement. Under KTD3's
244
- // single-writer contract it stops our active execution; never use it to
245
- // recover attribution after observing a foreign admission.
246
- try { await client.session.interrupt({ sessionID: record.sessionId, resume: false }, { signal }); }
247
- catch (error) { if (!retryable(error)) throw error; }
248
- do {
249
- state = await projection(record, signal);
250
- foreign ||= state.foreign;
251
- if (state.uncertainRejection) throw new Error("OpenCode permission rejection acknowledgement remains uncertain.");
252
- if (foreign || record.foreign) throw new Error("OpenCode attribution conflict: foreign input entered during cancellation.");
253
- if (!state.idle && !state.dismissed && !state.rejected) await delay(options.pollIntervalMs, undefined, { signal });
254
- } while (!state.idle && !state.dismissed && !state.rejected);
255
- }
256
- if (!state.own && record.phase !== "cancelled") throw new Error("OpenCode prompt admission remains uncertain.");
257
- }
258
- } catch (error) { failure = error; }
259
- // Native 2.0.29's received-body PUT handler executes its SQL mutation inline,
260
- // before replying; it does not enqueue a background instruction write. Live
261
- // cleanup follows the independently settled PUT request (including lost reply),
262
- // and startup removes abandoned namespaced entries without replaying that PUT.
263
- // A failed DELETE still retains ownership and blocks intake.
264
- if (record.instruction !== "absent") await client.session.instructions.entry.remove({ sessionID: record.sessionId, key: record.key }, { signal });
265
- if (failure) throw failure;
266
- await mutate((items) => items.filter((item) => item.key !== record.key));
267
- return foreign || Boolean(record.foreign);
132
+ return false;
133
+ }
134
+
135
+ async function pending(observer, entry) {
136
+ const signal = observer.controller.signal;
137
+ if (entry.kind === "permission") return (await client.permission.list({ sessionID: entry.request.sessionID }, { signal })).some((item) => item.id === entry.request.id);
138
+ try { return (await client.session.form.get({ sessionID: entry.request.sessionID, formID: entry.request.id }, { signal })).state.status === "pending"; }
139
+ catch (error) { if (error._tag === "FormNotFoundError") return false; throw error; }
140
+ }
141
+
142
+ function settle(entry) {
143
+ if (entry.accepted || entry.external) return;
144
+ entry.external = true;
145
+ entry.settled.resolve();
268
146
  }
269
147
 
270
- async function ready(workingDirectory) {
271
- if (blocked) throw blocked;
272
- if (fatalError) throw fatalError;
273
- readiness ??= (async () => {
148
+ async function dispatch(observer, kind, request) {
149
+ const signal = observer.controller.signal;
150
+ const revision = observer.interactionRevision;
151
+ const key = `${kind}:${request.sessionID}:${request.id}`;
152
+ if (!observer.onInteraction || observer.interactions.has(key) || !await belongs(observer, request.sessionID)) return;
153
+ if (observer.interactions.has(key) || signal.aborted || revision !== observer.interactionRevision) return;
154
+ const fields = request.fields;
155
+ const question = kind === "form" && request.metadata?.kind === "question" && Array.isArray(fields) && fields.length
156
+ && fields.every((field, index) => field.key === `q${index}` && ["string", "multiselect"].includes(field.type) && !field.hidden && !field.when?.length);
157
+ const type = kind === "permission" ? "permission" : question ? "question" : "form";
158
+ let tool;
159
+ if (kind === "permission" && request.source?.type === "tool") {
274
160
  try {
161
+ const message = await client.session.message.get({ sessionID: request.sessionID, messageID: request.source.messageID }, { signal });
162
+ const part = message.content?.find((part) => part.type === "tool" && part.id === request.source.id);
163
+ if (part) tool = { name: part.name, input: part.state?.input };
164
+ } catch (error) { if (error._tag !== "MessageNotFoundError") throw error; }
165
+ }
166
+ if (observer.interactions.has(key) || signal.aborted || revision !== observer.interactionRevision) return;
167
+ const normalized = question ? { ...request, questions: fields.map((field) => ({
168
+ header: field.title || request.title, question: field.description || field.title || request.title,
169
+ multiple: field.type === "multiselect", custom: field.custom ?? !field.options?.length,
170
+ options: field.options?.map((option) => ({ label: option.label, description: option.description })),
171
+ })) } : tool ? { ...request, tool } : request;
172
+ const entry = { kind, request, settled: Promise.withResolvers() };
173
+ observer.interactions.set(key, entry);
174
+ const submitDecision = async (decision) => {
175
+ if (entry.accepted) return;
176
+ if (entry.external) throw new Error("OpenCode request is already settled.");
177
+ if (type === "form") throw new Error("This form requires an OpenCode client response.");
178
+ signal.throwIfAborted();
179
+ entry.submitting = true;
180
+ const native = { sessionID: request.sessionID, ...(kind === "form" ? { formID: request.id } : { requestID: request.id }) };
181
+ try {
182
+ if (!await pending(observer, entry)) { settle(entry); throw new Error("OpenCode request is already settled."); }
275
183
  try {
276
- const stats = await lstat(journalFile);
277
- if (!stats.isFile() || stats.isSymbolicLink()) throw new Error("Invalid Pipa OpenCode recovery file.");
278
- const saved = JSON.parse(await readFile(journalFile, "utf8"));
279
- if (saved?.version !== 1 || !Array.isArray(saved.records)) throw new Error("Invalid Pipa OpenCode recovery file.");
280
- records = saved.records;
184
+ if (kind === "permission") {
185
+ const value = ["reject", "stop"].includes(decision?.type) ? "reject" : decision?.type === "reply" ? decision.reply : null;
186
+ if (!["once", "always", "reject"].includes(value)) throw new Error("Invalid OpenCode permission decision.");
187
+ await client.permission.reply({ ...native, decision: value }, { signal });
188
+ } else if (["reject", "stop"].includes(decision?.type)) {
189
+ await client.session.form.cancel(native, { signal });
190
+ } else if (question && decision?.type === "answer") {
191
+ if (!Array.isArray(decision.answers) || decision.answers.length !== fields.length) throw new Error("Invalid OpenCode question answers.");
192
+ const answer = Object.fromEntries(fields.map((field, index) => {
193
+ const values = decision.answers[index];
194
+ if (!Array.isArray(values) || !values.every((value) => typeof value === "string") || (field.type === "string" && values.length !== 1)) throw new Error("Invalid OpenCode question answer.");
195
+ const encoded = values.map((value) => field.options?.find((option) => option.label === value)?.value ?? value);
196
+ return [field.key, field.type === "multiselect" ? encoded : encoded[0]];
197
+ }));
198
+ await client.session.form.reply({ ...native, answer }, { signal });
199
+ } else throw new Error("This form requires an OpenCode client response.");
281
200
  } catch (error) {
282
- if (error.code !== "ENOENT") throw error;
283
- records = [];
201
+ signal.throwIfAborted();
202
+ if (retryable(error) || error.reason === "MalformedResponse" || ["FormAlreadySettledError", "FormNotFoundError", "PermissionNotFoundError"].includes(error._tag)) {
203
+ if (!await pending(observer, entry)) { settle(entry); return; }
204
+ else throw error;
205
+ } else throw error;
284
206
  }
285
- const keys = new Set();
286
- for (const record of [...records]) {
287
- if (typeof record.key !== "string" || !record.key.startsWith(prefix) || !/^pipa-[a-f0-9]{16}-[a-f0-9-]{36}$/u.test(record.key)
288
- || keys.has(record.key) || typeof record.sessionId !== "string" || typeof record.id !== "string"
289
- || !Array.isArray(record.baseline) || !record.baseline.every((id) => typeof id === "string")
290
- || !["prepared", "admitting", "admitted", "cancelled"].includes(record.phase)
291
- || (record.instruction !== undefined && !["absent", "putting", "present"].includes(record.instruction))
292
- || (record.dismissal !== undefined && (!record.dismissal || ![record.dismissal.formId, record.dismissal.messageId, record.dismissal.toolId].every((id) => typeof id === "string" && id.length)))
293
- || (record.rejection !== undefined && (!record.rejection || typeof record.rejection.confirmed !== "boolean" || ![record.rejection.requestId, record.rejection.messageId, record.rejection.toolId].every((id) => typeof id === "string" && id.length)))
294
- || typeof record.workingDirectory !== "string" || path.resolve(record.workingDirectory) !== path.resolve(workingDirectory)) throw new Error("Invalid or mismatched Pipa OpenCode recovery ownership.");
295
- keys.add(record.key);
296
- await cleanup(record);
207
+ entry.accepted = true;
208
+ // Native rejection/cancellation need not produce an idle event.
209
+ if (decision.type === "stop") {
210
+ try { await client.session.interrupt({ sessionID: request.sessionID, resume: false }, { signal }); }
211
+ finally { settleWaiters(observer, ""); }
212
+ } else if (decision.type === "reject" || decision.reply === "reject") settleWaiters(observer, "Stopped after a request was rejected.");
213
+ } finally { entry.submitting = false; }
214
+ };
215
+ const submit = (decision) => {
216
+ if (entry.submitting) return Promise.reject(new Error("OpenCode response is already being submitted."));
217
+ const submission = submitDecision(decision);
218
+ observer.handlers.add(submission);
219
+ void submission.then(() => observer.handlers.delete(submission), () => observer.handlers.delete(submission));
220
+ return submission;
221
+ };
222
+ const handler = Promise.resolve().then(() => {
223
+ signal.throwIfAborted();
224
+ return observer.onInteraction({ type, request: normalized, sessionId: request.sessionID, signal, submit, settled: entry.settled.promise });
225
+ })
226
+ .then(async (decision) => {
227
+ if (!entry.accepted && !entry.external && !signal.aborted && !["cancelled", "stopped"].includes(decision?.type)) await submit(decision);
228
+ }).catch(() => { if (!signal.aborted) process.stderr.write("OpenCode interaction handler failed.\n"); });
229
+ observer.handlers.add(handler);
230
+ void handler.finally(() => observer.handlers.delete(handler));
231
+ }
232
+
233
+ function reconcile(observer) {
234
+ observer.reconciliation = (observer.reconciliation ?? Promise.resolve()).catch(() => undefined).then(() => reconcilePending(observer));
235
+ return observer.reconciliation;
236
+ }
237
+
238
+ async function reconcilePending(observer) {
239
+ if (!observer.onInteraction && !observer.onPermissionsReconciled) return;
240
+ const signal = observer.controller.signal;
241
+ const revision = observer.interactionRevision;
242
+ const input = { location: { directory: observer.workingDirectory } };
243
+ const snapshots = await readWithRecovery((signal) => Promise.all([client.form.list(input, { signal }), client.permission.request.list(input, { signal })]), signal);
244
+ if (revision !== observer.interactionRevision) return;
245
+ for (const [index, snapshot] of snapshots.entries()) {
246
+ if (revision !== observer.interactionRevision) return;
247
+ if (path.resolve(snapshot.location?.directory ?? "") !== path.resolve(observer.workingDirectory) || !Array.isArray(snapshot.data)) throw new Error("OpenCode returned invalid interaction location projections.");
248
+ const kind = index === 0 ? "form" : "permission";
249
+ for (const request of snapshot.data) await dispatch(observer, kind, request);
250
+ if (revision !== observer.interactionRevision) return;
251
+ for (const [key, entry] of observer.interactions) {
252
+ if (entry.kind === kind && !entry.submitting && !snapshot.data.some((request) => request.id === entry.request.id && request.sessionID === entry.request.sessionID)) {
253
+ settle(entry);
254
+ observer.interactions.delete(key);
297
255
  }
298
- } catch (cause) {
299
- blocked = new Error("Pipa could not reconcile abandoned OpenCode context/admissions. New intake is blocked; recovery records have been retained.", { cause });
300
- throw blocked;
256
+ }
257
+ if (kind === "permission" && observer.onPermissionsReconciled) {
258
+ const scoped = [];
259
+ for (const request of snapshot.data) if (await belongs(observer, request.sessionID)) scoped.push(request);
260
+ for (const sessionId of observer.interactionSessions) await observer.onPermissionsReconciled({ sessionId, requestIds: new Set(scoped.filter((request) => request.sessionID === sessionId).map((request) => request.id)) });
261
+ }
262
+ }
263
+ }
264
+
265
+ // Native 2.2.5's experimental session log emits no responses; forward live events only.
266
+ function watchEvents() {
267
+ if (events && !events.signal.aborted) return;
268
+ events = new AbortController();
269
+ connected = false;
270
+ const signal = events.signal;
271
+ eventTask = (async () => {
272
+ while (!signal.aborted) {
273
+ try {
274
+ for await (const event of client.event.subscribe({ signal })) {
275
+ if (event.type === "server.connected") {
276
+ connected = true;
277
+ for (const observer of observers.values()) {
278
+ queueResponse(observer, async () => {
279
+ if (!await lookup(observer.sessionId, observer.workingDirectory, observer.controller.signal)) throw new Error("OpenCode session is unavailable.");
280
+ observer.initialized.resolve();
281
+ }, true);
282
+ void reconcile(observer).catch(() => undefined);
283
+ }
284
+ continue;
285
+ }
286
+ for (const observer of observers.values()) {
287
+ if (event.location && path.resolve(event.location.directory ?? "") !== path.resolve(observer.workingDirectory)) continue;
288
+ if (event.data?.sessionID === observer.sessionId) {
289
+ if (event.type === "session.step.ended" && event.data.finish === "stop") queueResponse(observer, async () => {
290
+ const message = await readWithRecovery((signal) => client.session.message.get({ sessionID: observer.sessionId, messageID: event.data.assistantMessageID }, { signal }), observer.controller.signal);
291
+ await deliverResponse(observer, message);
292
+ });
293
+ if (event.type === "session.execution.failed") queueResponse(observer, () => report(observer, executionError(event.data.error)));
294
+ if (event.type === "session.execution.interrupted") settleWaiters(observer, "");
295
+ if (event.type === "session.tool.called") void reconcile(observer).catch(() => undefined);
296
+ }
297
+ if (!["form.created", "permission.asked", "form.replied", "form.cancelled", "permission.replied", "location.shutdown"].includes(event.type)) continue;
298
+ observer.interactionTask = (observer.interactionTask ?? Promise.resolve()).then(async () => {
299
+ if (observer.controller.signal.aborted) return;
300
+ if (event.type === "form.created") await dispatch(observer, "form", event.data.form);
301
+ if (event.type === "permission.asked") await dispatch(observer, "permission", event.data);
302
+ if (event.type === "permission.replied" && await belongs(observer, event.data.sessionID)) {
303
+ const key = `${event.data.sessionID}:${event.data.requestID}`;
304
+ if (!observer.replied.has(key)) {
305
+ await observer.onPermissionReplied?.({ sessionId: event.data.sessionID, requestId: event.data.requestID, reply: event.data.reply });
306
+ observer.replied.add(key);
307
+ }
308
+ }
309
+ if (["form.replied", "form.cancelled", "permission.replied", "location.shutdown"].includes(event.type)) {
310
+ observer.interactionRevision++;
311
+ const kind = event.type.startsWith("form.") ? "form" : "permission";
312
+ const id = kind === "form" ? event.data?.id : event.data?.requestID;
313
+ const entry = observer.interactions.get(`${kind}:${event.data?.sessionID}:${id}`);
314
+ if (entry && !entry.submitting) settle(entry);
315
+ await reconcile(observer);
316
+ }
317
+ }).catch(() => { if (!observer.controller.signal.aborted) process.stderr.write("OpenCode interaction event failed.\n"); });
318
+ }
319
+ }
320
+ } catch { if (signal.aborted) return; }
321
+ connected = false;
322
+ await delay(options.pollIntervalMs ?? 100, undefined, { signal }).catch(() => undefined);
301
323
  }
302
324
  })();
303
- await readiness;
304
325
  }
305
326
 
306
- async function listModels(workingDirectory, signal) {
307
- const input = { location: { directory: workingDirectory } };
308
- const [catalog, defaults] = await readWithRecovery((readSignal) => Promise.all([
309
- client.model.list(input, { signal: readSignal }), client.model.default(input, { signal: readSignal }),
310
- ]), signal);
311
- for (const snapshot of [catalog, defaults]) {
312
- if (typeof snapshot?.location?.directory !== "string" || path.resolve(snapshot.location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode model workspace identity mismatch.");
327
+ function queueResponse(observer, operation, fatal = false) {
328
+ observer.task = (observer.task ?? Promise.resolve()).then(async () => {
329
+ const signal = observer.controller.signal;
330
+ if (signal.aborted) return;
331
+ try { await operation(); }
332
+ catch {
333
+ if (signal.aborted) return;
334
+ if (fatal) {
335
+ const safe = new Error("OpenCode session responses are unavailable.");
336
+ observer.initialized.reject(safe);
337
+ await report(observer, safe).catch(() => undefined);
338
+ detach(observer, safe);
339
+ return;
340
+ }
341
+ const safe = new Error("OpenCode response could not be delivered; it will not be replayed.");
342
+ await report(observer, safe).catch(() => process.stderr.write("Pipa could not deliver an OpenCode response.\n"));
343
+ }
344
+ });
345
+ }
346
+
347
+ async function deliverResponse(observer, message) {
348
+ if (observer.controller.signal.aborted || observer.delivered.has(message.id)) return;
349
+ if (message.type !== "assistant" || message.finish !== "stop" || typeof message.time?.completed !== "number") return;
350
+ if (!Array.isArray(message.content)) throw new Error("OpenCode returned an invalid assistant message.");
351
+ const text = message.content.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n").trim();
352
+ // A failed Slack post may have sent earlier chunks; never replay the whole response.
353
+ observer.delivered.add(message.id);
354
+ if (text) {
355
+ await observer.onResponse?.(text, message.id, observer.controller.signal);
313
356
  }
314
- if (!Array.isArray(catalog.data) || catalog.data.some((model) => !model || typeof model.id !== "string" || !model.id
315
- || typeof model.providerID !== "string" || !model.providerID || typeof model.name !== "string" || typeof model.enabled !== "boolean"
316
- || !Array.isArray(model.variants) || model.variants.some((variant) => typeof variant?.id !== "string" || !variant.id))) throw new Error("OpenCode returned an invalid model catalog.");
317
- // Native discovery resolves configured/connected providers. Never expose its
318
- // settings/headers/body: these can contain provider credentials.
319
- const models = catalog.data.filter((model) => model.enabled).map((model) => ({
320
- providerID: model.providerID, id: model.id, name: model.name, variants: [...new Set(["default", ...model.variants.map((variant) => variant.id)])],
321
- }));
322
- const selected = defaults.data;
323
- if (selected !== null && (!selected || typeof selected.providerID !== "string" || typeof selected.id !== "string")) throw new Error("OpenCode returned an invalid default model.");
324
- const defaultModel = selected && models.find((model) => model.providerID === selected.providerID && model.id === selected.id);
325
- return { models, defaultModel: defaultModel ? { providerID: defaultModel.providerID, id: defaultModel.id, variant: "default" } : null };
357
+ settleWaiters(observer, text);
358
+ }
359
+
360
+ async function follow(input, persistent, waiter) {
361
+ if (stopped) throw stopped;
362
+ if (typeof input.sessionId !== "string" || !input.sessionId || typeof input.workingDirectory !== "string" || !input.workingDirectory) throw new Error("Invalid OpenCode session context.");
363
+ let observer = observers.get(input.sessionId);
364
+ const created = !observer;
365
+ if (!observer) {
366
+ observer = { sessionId: input.sessionId, workingDirectory: input.workingDirectory, controller: new AbortController(), initialized: Promise.withResolvers(), delivered: new Set(), replied: new Set(), waiters: new Set(), handlers: new Set(), interactions: new Map(), interactionSessions: new Set([input.sessionId]), interactionRevision: 0, persistent };
367
+ observers.set(input.sessionId, observer);
368
+ // Observe rejection immediately, including shutdown during initial attachment.
369
+ void observer.initialized.promise.catch(() => undefined);
370
+ observer.registration = (async () => {
371
+ const signal = observer.controller.signal;
372
+ if (!await lookup(input.sessionId, input.workingDirectory, signal)) throw new Error("OpenCode session is unavailable.");
373
+ try {
374
+ const entries = await client.session.instructions.entry.list({ sessionID: input.sessionId }, { signal });
375
+ observer.instructions = entries.find((entry) => entry.key === "pipa.slack")?.value;
376
+ await Promise.all(entries.filter((entry) => /^pipa-[a-f0-9]{16}-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(entry.key)).map((entry) => client.session.instructions.entry.remove({ sessionID: input.sessionId, key: entry.key }, { signal })));
377
+ } catch { signal.throwIfAborted(); /* Old context migration is best effort and session-local. */ }
378
+ watchEvents();
379
+ if (connected) observer.initialized.resolve();
380
+ const timer = setTimeout(() => observer.initialized.reject(new Error("OpenCode event attachment timed out.")), options.connectionRecoveryTimeoutMs ?? 10_000);
381
+ try { await observer.initialized.promise; } finally { clearTimeout(timer); }
382
+ })();
383
+ }
384
+ if (path.resolve(observer.workingDirectory) !== path.resolve(input.workingDirectory)) throw new Error("OpenCode session workspace identity mismatch.");
385
+ if (waiter) observer.waiters.add(waiter);
386
+ observer.persistent ||= persistent;
387
+ for (const key of ["onResponse", "onError", "onInteraction", "onPermissionReplied", "onPermissionsReconciled"]) if (input[key] !== undefined) observer[key] = input[key];
388
+ try {
389
+ await observer.registration;
390
+ observer.contextUpdate = (observer.contextUpdate ?? Promise.resolve()).catch(() => undefined).then(async () => {
391
+ if (input.instructions !== undefined && observer.instructions !== input.instructions) {
392
+ await client.session.instructions.entry.put({ sessionID: input.sessionId, key: "pipa.slack", value: input.instructions }, { signal: observer.controller.signal });
393
+ observer.instructions = input.instructions;
394
+ }
395
+ });
396
+ await observer.contextUpdate;
397
+ if (observer.onInteraction || observer.onPermissionReplied || observer.onPermissionsReconciled) {
398
+ watchEvents();
399
+ await reconcile(observer).catch(() => undefined);
400
+ }
401
+ return observer;
402
+ } catch (error) { if (created) detach(observer, error); throw error; }
326
403
  }
327
404
 
328
405
  return {
329
- ready,
406
+ async ready(workingDirectory) { if (stopped) throw stopped; },
330
407
  listModels,
331
408
  async switchModel(sessionId, model, workingDirectory, signal) {
332
409
  if (typeof sessionId !== "string" || !sessionId) throw new Error("Invalid OpenCode session ID.");
333
410
  if (model !== null && (!model || typeof model.providerID !== "string" || !model.providerID || typeof model.id !== "string" || !model.id
334
411
  || (model.variant !== undefined && (typeof model.variant !== "string" || !model.variant)))) throw new Error("Invalid OpenCode model selection.");
335
412
  const catalog = await listModels(workingDirectory, signal);
336
- // 2.0.29 has no nullable switch/reset operation. Reset resolves the native
337
- // default now, then selects it explicitly; it does not clear a stored override.
338
413
  const selection = model === null ? catalog.defaultModel : { providerID: model.providerID, id: model.id, variant: model.variant ?? "default" };
339
414
  const available = selection && catalog.models.find((item) => item.providerID === selection.providerID && item.id === selection.id);
340
415
  if (!available || !available.variants.includes(selection.variant)) throw new Error("OpenCode model or variant is unavailable.");
341
416
  if (!await lookup(sessionId, workingDirectory, signal)) throw new Error("OpenCode session is unavailable; model selection did not create a replacement.");
342
417
  signal.throwIfAborted();
343
- // Do not retry a mutation with an uncertain acknowledgement or interrupt an
344
- // in-flight step. Native switching applies to subsequent provider steps.
345
418
  await client.session.switchModel({ sessionID: sessionId, model: selection }, { signal });
346
419
  },
347
420
  async resolveSession(sessionId, workingDirectory, controller) {
348
421
  const signal = controller.signal;
349
422
  let session = sessionId ? await lookup(sessionId, workingDirectory, signal) : null;
423
+ const created = !session;
350
424
  if (!session) {
351
425
  session = await client.session.create({ location: { directory: workingDirectory } }, { signal });
352
426
  if (typeof session?.id !== "string" || session.location?.directory !== workingDirectory) throw new Error("OpenCode did not create a session in the configured workspace.");
353
- sessionId = session.id;
354
427
  }
355
- const [baseline, inbox, active] = await Promise.all([
356
- readWithRecovery((readSignal) => messages(sessionId, readSignal), signal),
357
- readWithRecovery((readSignal) => client.session.inbox.list({ sessionID: sessionId }, { signal: readSignal }), signal),
358
- readWithRecovery((readSignal) => client.session.active({ signal: readSignal }), signal),
359
- ]);
360
- if (!Array.isArray(inbox) || !active || typeof active !== "object") throw new Error("OpenCode returned invalid session projections.");
361
- if (inbox.length || active[sessionId] || turns.has(sessionId)) throw new Error("OpenCode attribution conflict: the session already has an active writer.");
362
- // onSession can persist the mapping before selection. Retry defaults only
363
- // while neither native session metadata nor history establishes a choice.
364
- return { sessionId, defaultEligible: !session.model && !baseline.length, baseline: baseline.map((message) => message.id) };
428
+ const history = !created && !session.model ? await readWithRecovery((signal) => client.message.list({ sessionID: session.id, limit: 1 }, { signal }), signal) : null;
429
+ if (history && !Array.isArray(history.data)) throw new Error("OpenCode returned an invalid message projection.");
430
+ return { sessionId: session.id, defaultEligible: !session.model && (created || !history.data.length) };
365
431
  },
366
- async execute({ sessionId, defaultEligible, baseline, model, defaultModel, workingDirectory, controller, prompt, files, instructions, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
367
- if (blocked) throw blocked;
368
- const signal = controller.signal;
369
- const selectedModel = model ?? (defaultEligible ? defaultModel : null);
370
- if (selectedModel) {
371
- signal.throwIfAborted();
372
- // Prompt has no model field in the native client. Select once before
373
- // admission, retaining native session selection on ordinary continuations.
374
- await client.session.switchModel({ sessionID: sessionId, model: { providerID: selectedModel.providerID, id: selectedModel.modelID, variant: "default" } }, { signal });
375
- }
376
- const record = { sessionId, workingDirectory, baseline, id: options.inputId?.() ?? `msg_${randomUUID().replaceAll("-", "")}`,
377
- key: `${prefix}${randomUUID()}`, phase: "prepared", instruction: "absent" };
378
- turns.set(sessionId, record);
379
- let stream;
380
- let watching;
381
- let streamError;
382
- let dismissed = false;
383
- let permissionRejected = false;
384
- const interactions = new Map();
385
- const interactionSessions = new Set([sessionId]);
386
- const permissionReplies = new Set();
387
- async function belongs(candidate) {
388
- const original = candidate;
389
- const visited = new Set();
390
- while (candidate && !visited.has(candidate)) {
391
- visited.add(candidate);
392
- let session;
393
- try { session = await readWithRecovery((readSignal) => client.session.get({ sessionID: candidate }, { signal: readSignal }), signal); }
394
- catch (error) { if (error._tag === "SessionNotFoundError") return false; throw error; }
395
- if (session?.id !== candidate || typeof session.location?.directory !== "string" || path.resolve(session.location.directory) !== path.resolve(workingDirectory)) return false;
396
- if (candidate === sessionId) { interactionSessions.add(original); return true; }
397
- candidate = session.parentID;
398
- }
399
- return false;
400
- }
401
- function settle(entry) {
402
- if (entry.accepted || entry.external) return;
403
- entry.external = true;
404
- entry.settled.resolve();
405
- }
406
- async function awaitSubmissions() {
407
- while (true) {
408
- const submissions = [...interactions.values()].filter((entry) => entry.submitting).map((entry) => entry.submission);
409
- if (!submissions.length) return;
410
- // HTTP acknowledgements have the client's request deadline; uncertain
411
- // responses use bounded authoritative recovery before this resolves.
412
- await Promise.allSettled(submissions);
413
- }
414
- }
415
- async function saveRejection(rejection, requestId = rejection?.requestId) {
416
- try {
417
- await mutate((items) => items.map((item) => {
418
- if (item.key !== record.key) return item;
419
- if (rejection) return { ...item, rejection };
420
- if (item.rejection?.requestId !== requestId) return item;
421
- const next = { ...item };
422
- delete next.rejection;
423
- return next;
424
- }), (next) => {
425
- const saved = next.find((item) => item.key === record.key)?.rejection;
426
- if (saved) record.rejection = saved;
427
- else delete record.rejection;
428
- });
429
- } catch (cause) {
430
- blocked = new Error("Pipa could not persist permission recovery state. New intake is blocked; recovery records have been retained.", { cause });
431
- streamError = blocked;
432
- throw blocked;
433
- }
434
- }
435
- async function dispatch(kind, request) {
436
- const key = `${kind}:${request.sessionID}:${request.id}`;
437
- if (!onInteraction || interactions.has(key) || !await belongs(request.sessionID)) return;
438
- if (interactions.has(key) || signal.aborted) return;
439
- const fields = request.fields;
440
- const question = kind === "form" && request.metadata?.kind === "question" && Array.isArray(fields) && fields.length
441
- && fields.every((field, index) => field.key === `q${index}` && ["string", "multiselect"].includes(field.type) && !field.hidden && !field.when?.length);
442
- const type = kind === "permission" ? "permission" : question ? "question" : "form";
443
- let tool;
444
- if (kind === "permission" && request.source?.type === "tool") {
445
- try {
446
- const message = await readWithRecovery((readSignal) => client.session.message.get({ sessionID: request.sessionID, messageID: request.source.messageID }, { signal: readSignal }), signal);
447
- const part = message.content?.find((part) => part.type === "tool" && part.id === request.source.id);
448
- if (part) tool = { name: part.name, input: part.state?.input };
449
- } catch (error) { if (error._tag !== "MessageNotFoundError") throw error; }
450
- }
451
- if (interactions.has(key) || signal.aborted) return;
452
- const normalized = question ? { ...request, questions: fields.map((field) => ({
453
- header: field.title || request.title, question: field.description || field.title || request.title,
454
- multiple: field.type === "multiselect", custom: field.custom ?? !field.options?.length,
455
- options: field.options?.map((option) => ({ label: option.label, description: option.description })),
456
- })) } : tool ? { ...request, tool } : request;
457
- const entry = { kind, request, settled: Promise.withResolvers() };
458
- interactions.set(key, entry);
459
- const submitDecision = async (decision) => {
460
- if (entry.accepted) return;
461
- if (entry.external) throw new Error("OpenCode request is already settled.");
462
- if (type === "form") throw new Error("This form requires an OpenCode client response.");
463
- signal.throwIfAborted();
464
- entry.submitting = true;
465
- const native = { sessionID: request.sessionID, ...(kind === "form" ? { formID: request.id } : { requestID: request.id }) };
466
- try {
467
- // Reconcile an earlier lost reply before permitting another mutation.
468
- if (!await pending(entry)) { settle(entry); throw new Error("OpenCode request is already settled."); }
469
- try {
470
- if (kind === "permission") {
471
- const decisionValue = ["reject", "stop"].includes(decision?.type) ? "reject" : decision?.type === "reply" ? decision.reply : null;
472
- if (!["once", "always", "reject"].includes(decisionValue)) throw new Error("Invalid OpenCode permission decision.");
473
- const rejection = decisionValue === "reject" && request.sessionID === sessionId && request.source?.type === "tool"
474
- && typeof request.source.messageID === "string" && request.source.messageID.length && typeof request.source.id === "string" && request.source.id.length
475
- ? { requestId: request.id, messageId: request.source.messageID, toolId: request.source.id, confirmed: false } : null;
476
- if (rejection) await saveRejection(rejection);
477
- else if (record.rejection?.requestId === request.id) await saveRejection(undefined, request.id);
478
- try { await client.permission.reply({ ...native, decision: decisionValue }, { signal }); }
479
- catch (error) {
480
- if (!retryable(error) && error.reason !== "MalformedResponse" && error._tag !== "PermissionNotFoundError") await saveRejection(undefined, request.id);
481
- throw error;
482
- }
483
- if (rejection) await saveRejection({ ...rejection, confirmed: true });
484
- } else if (["reject", "stop"].includes(decision?.type)) {
485
- if (decision.type === "stop" && request.sessionID === sessionId && typeof request.metadata?.tool?.messageID === "string" && typeof request.metadata.tool.id === "string") {
486
- record.dismissal = { formId: request.id, messageId: request.metadata.tool.messageID, toolId: request.metadata.tool.id };
487
- await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
488
- }
489
- await client.session.form.cancel(native, { signal });
490
- } else if (question && decision?.type === "answer") {
491
- if (!Array.isArray(decision.answers) || decision.answers.length !== fields.length) throw new Error("Invalid OpenCode question answers.");
492
- const answer = Object.fromEntries(fields.map((field, index) => {
493
- const values = decision.answers[index];
494
- if (!Array.isArray(values) || !values.every((value) => typeof value === "string") || (field.type === "string" && values.length !== 1)) throw new Error("Invalid OpenCode question answer.");
495
- const encoded = values.map((value) => field.options?.find((option) => option.label === value)?.value ?? value);
496
- return [field.key, field.type === "multiselect" ? encoded : encoded[0]];
497
- }));
498
- await client.session.form.reply({ ...native, answer }, { signal });
499
- } else throw new Error("This form requires an OpenCode client response.");
500
- } catch (error) {
501
- signal.throwIfAborted();
502
- if (retryable(error) || error.reason === "MalformedResponse" || ["FormAlreadySettledError", "FormNotFoundError", "PermissionNotFoundError"].includes(error._tag)) {
503
- if (!await pending(entry)) { settle(entry); return; }
504
- }
505
- throw error;
506
- }
507
- entry.accepted = true;
508
- if (kind === "permission" && (decision.type === "reject" || decision.reply === "reject")) permissionRejected = true;
509
- if (decision.type === "stop") {
510
- dismissed = true;
511
- await client.session.interrupt({ sessionID: request.sessionID, resume: false }, { signal });
512
- }
513
- } finally { entry.submitting = false; }
514
- };
515
- const submit = (decision) => {
516
- if (entry.submitting) return Promise.reject(new Error("OpenCode response is already being submitted."));
517
- entry.submission = submitDecision(decision);
518
- return entry.submission;
519
- };
520
- void Promise.resolve().then(() => onInteraction({ type, request: normalized, sessionId: request.sessionID, signal, submit, settled: entry.settled.promise }))
521
- .then(async (decision) => {
522
- if (!entry.accepted && !entry.external && !signal.aborted && !["cancelled", "stopped"].includes(decision?.type)) await submit(decision);
523
- }).catch((error) => { if (!signal.aborted) process.stderr.write(`OpenCode interaction handler error: ${error.message}\n`); });
524
- }
525
- async function pending(entry) {
526
- return readWithRecovery(async (readSignal) => {
527
- if (!await belongs(entry.request.sessionID)) return false;
528
- if (entry.kind === "permission") return (await client.permission.list({ sessionID: entry.request.sessionID }, { signal: readSignal })).some((item) => item.id === entry.request.id);
529
- try { return (await client.session.form.get({ sessionID: entry.request.sessionID, formID: entry.request.id }, { signal: readSignal })).state.status === "pending"; }
530
- catch (error) { if (error._tag === "FormNotFoundError") return false; throw error; }
531
- }, signal);
532
- }
533
- async function reconcileInteractions() {
534
- if (!onInteraction && !onPermissionsReconciled) return;
535
- const before = [...interactions.values()];
536
- const input = { location: { directory: workingDirectory } };
537
- const snapshots = await readWithRecovery(async (readSignal) => Promise.all([
538
- client.form.list(input, { signal: readSignal }), client.permission.request.list(input, { signal: readSignal }),
539
- ]), signal);
540
- for (const [index, snapshot] of snapshots.entries()) {
541
- if (path.resolve(snapshot.location?.directory ?? "") !== path.resolve(workingDirectory) || !Array.isArray(snapshot.data)) throw new Error("OpenCode returned invalid interaction location projections.");
542
- const kind = index === 0 ? "form" : "permission";
543
- for (const request of snapshot.data) await dispatch(kind, request);
544
- for (const entry of before) {
545
- if (entry.kind === kind && !entry.accepted && !entry.submitting && !entry.external
546
- && !snapshot.data.some((request) => request.id === entry.request.id && request.sessionID === entry.request.sessionID)) settle(entry);
547
- }
548
- if (kind === "permission" && onPermissionsReconciled) {
549
- const scoped = [];
550
- for (const request of snapshot.data) if (await belongs(request.sessionID)) scoped.push(request);
551
- for (const sessionId of interactionSessions) onPermissionsReconciled({ sessionId, requestIds: new Set(scoped.filter((request) => request.sessionID === sessionId).map((request) => request.id)) });
552
- }
553
- }
554
- }
432
+ async followSession(input) { await follow(input, true); },
433
+ async execute(input) {
434
+ const signal = input.controller.signal;
435
+ signal.throwIfAborted();
436
+ controllers.add(input.controller);
437
+ const waiter = input.onResponse ? null : Promise.withResolvers();
438
+ if (waiter) void waiter.promise.catch(() => undefined);
439
+ const cancelled = Promise.withResolvers();
440
+ void cancelled.promise.catch(() => undefined);
441
+ let observer;
442
+ const abort = () => {
443
+ cancelled.reject(signal.reason);
444
+ if (waiter) waiter.reject(signal.reason);
445
+ const current = observer ?? observers.get(input.sessionId);
446
+ if (current && !current.persistent && current.waiters.size <= 1) detach(current, signal.reason);
447
+ };
448
+ signal.addEventListener("abort", abort, { once: true });
555
449
  try {
556
- await mutate((items) => [...items, { ...record }]);
450
+ observer = await Promise.race([follow(input, Boolean(input.onResponse), waiter), cancelled.promise]);
557
451
  signal.throwIfAborted();
558
- const subscribed = Promise.withResolvers();
559
- stream = new AbortController();
560
- const streamSignal = stream.signal;
561
- const events = OpenCode.make({ baseUrl: options.baseUrl, headers: options.headers, fetch: async (url, init) => {
562
- const response = await options.fetch(url, init);
563
- if (response.ok && response.headers.get("content-type")?.includes("text/event-stream")) subscribed.resolve();
564
- return response;
565
- } });
566
- watching = (async () => {
567
- while (!streamSignal.aborted && !fatalError) {
568
- try {
569
- for await (const event of events.event.subscribe({ signal: streamSignal })) {
570
- if (typeof event?.type !== "string" || !event.data || typeof event.id !== "string") throw new Error("OpenCode returned an invalid event.");
571
- if (event.type === "session.inbox.enqueued" && event.data.sessionID === sessionId && event.data.inboxID !== record.id) record.foreign = true;
572
- if ((onInteraction || onPermissionReplied || onPermissionsReconciled) && (!event.location || path.resolve(event.location.directory ?? "") === path.resolve(workingDirectory))) {
573
- if (event.type === "form.created") await dispatch("form", event.data.form);
574
- if (event.type === "permission.asked") await dispatch("permission", event.data);
575
- if (event.type === "permission.replied" && onPermissionReplied && await belongs(event.data.sessionID)) {
576
- const key = `${event.data.sessionID}:${event.data.requestID}`;
577
- if (!permissionReplies.has(key)) {
578
- permissionReplies.add(key);
579
- onPermissionReplied({ sessionId: event.data.sessionID, requestId: event.data.requestID, reply: event.data.reply });
580
- }
581
- }
582
- if (["form.replied", "form.cancelled", "permission.replied", "location.shutdown"].includes(event.type)) await reconcileInteractions();
583
- }
584
- }
585
- } catch (error) {
586
- if (streamSignal.aborted) return;
587
- if (!retryable(error)) { streamError = error; subscribed.reject(error); return; }
588
- }
589
- await delay(options.pollIntervalMs, undefined, { signal: streamSignal }).catch(() => undefined);
590
- }
591
- })();
592
- const subscriptionTimer = setTimeout(() => subscribed.reject(new Error("OpenCode event subscription recovery timed out.")), options.connectionRecoveryTimeoutMs ?? 10_000);
593
- try {
594
- await Promise.race([subscribed.promise, new Promise((_, reject) => {
595
- if (signal.aborted) reject(signal.reason);
596
- else signal.addEventListener("abort", () => reject(signal.reason), { once: true, signal: stream.signal });
597
- })]);
598
- } catch (error) {
599
- signal.throwIfAborted();
600
- await lookup(sessionId, workingDirectory, signal);
601
- throw error;
602
- } finally { clearTimeout(subscriptionTimer); }
603
- signal.throwIfAborted();
604
- await reconcileInteractions();
605
- record.instruction = "putting";
606
- await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
607
- // Cancellation waits for this independently bounded mutation before cleanup.
608
- // A lost reply retains `putting` until acknowledged namespaced removal.
609
- await client.session.instructions.entry.put({ sessionID: sessionId, key: record.key, value: instructions }, { signal: AbortSignal.timeout(options.instructionMutationTimeoutMs ?? 5_000) });
610
- record.instruction = "present";
611
- await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
612
- signal.throwIfAborted();
613
- const input = { sessionID: sessionId, id: record.id, text: prompt, ...(files.length ? { files: files.map((file) => ({ uri: file.url, name: file.filename })) } : {}) };
614
- let admissionDisconnectedAt;
615
- while (true) {
616
- if (streamError) throw streamError;
617
- await reconcileInteractions();
618
- const state = await projection(record, signal);
619
- if (state.foreign || record.foreign) throw new Error("OpenCode attribution conflict: foreign input entered the Pipa turn.");
620
- if (state.own || state.inbox.some((item) => item.id === record.id)) break;
621
- try {
622
- if (record.phase === "prepared") {
623
- record.phase = "admitting";
624
- await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
625
- }
626
- const admitted = await client.session.prompt(input, { signal });
627
- if (admitted?.id !== record.id || admitted.sessionID !== sessionId || admitted.type !== "user" || admitted.payload?.text !== prompt) throw new Error("OpenCode returned an invalid prompt admission.");
628
- break;
629
- } catch (error) {
630
- signal.throwIfAborted();
631
- if (!retryable(error) && error.reason !== "MalformedResponse") {
632
- if (["AttachmentError", "SessionNotFoundError", "AgentNotFoundError", "SkillNotFoundError"].includes(error._tag)) {
633
- record.phase = "prepared";
634
- await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
635
- }
636
- throw error;
637
- }
638
- admissionDisconnectedAt ??= Date.now();
639
- if (Date.now() - admissionDisconnectedAt >= (options.connectionRecoveryTimeoutMs ?? 10_000)) {
640
- const state = await projection(record, signal);
641
- if (state.foreign || record.foreign) throw new Error("OpenCode attribution conflict: foreign input entered the Pipa turn.");
642
- if (state.own || state.inbox.some((item) => item.id === record.id)) break;
643
- throw new Error("OpenCode prompt admission remains uncertain after bounded connection recovery.");
644
- }
645
- await delay(options.pollIntervalMs, undefined, { signal });
646
- }
647
- }
648
- record.phase = "admitted";
649
- await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
650
- while (true) {
651
- if (streamError) throw streamError;
652
- await reconcileInteractions();
653
- const state = await projection(record, signal);
654
- if (state.foreign || record.foreign) throw new Error("OpenCode attribution conflict: foreign input entered the Pipa turn.");
655
- if (state.own?.text !== undefined && state.own.text !== prompt) throw new Error("OpenCode attribution conflict: projected input differs from the admitted prompt.");
656
- if (state.dismissed || state.rejected || state.uncertainRejection || state.idle) await awaitSubmissions();
657
- if (streamError) throw streamError;
658
- if (state.dismissed) return "";
659
- if (state.rejected || state.uncertainRejection) {
660
- const settled = await projection(record, signal);
661
- if (settled.foreign || record.foreign) throw new Error("OpenCode attribution conflict: foreign input entered the Pipa turn.");
662
- if (settled.idle) continue;
663
- if (!settled.rejected) throw new Error("OpenCode permission rejection acknowledgement remains uncertain.");
664
- return dismissed ? "" : "Stopped after a permission was rejected.";
665
- }
666
- if (state.idle) {
667
- if (dismissed) return "";
668
- if (state.assistant?.error) {
669
- const error = state.assistant.error;
670
- const providerID = state.assistant.model?.providerID ?? selectedModel?.providerID;
671
- const provider = typeof providerID === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/iu.test(providerID) ? `provider "${providerID}"` : "selected provider";
672
- const status = error.status;
673
- const http = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
674
- // Native errors use type/status/message, not v1's name/data.
675
- // Classify only; never forward messages, response bodies or types.
676
- if (status === 401 || error.type === "provider.auth") {
677
- const expiredKey = status === 401 && typeof error.message === "string" && /\bAPI key (?:has )?expired\b/iu.test(error.message);
678
- throw new Error(expiredKey
679
- ? `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.`
680
- : `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.`);
681
- }
682
- throw new Error(`OpenCode ${provider} ${http ? `failed${http}` : "failed to complete the turn"}.`);
683
- }
684
- if (state.idle.outcome !== "succeeded" || state.assistant?.finish !== "stop"
685
- || typeof state.assistant.time?.completed !== "number" || state.assistant.retry) throw new Error("OpenCode failed to complete the turn.");
686
- const text = state.assistant.content.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n").trim();
687
- if (!text && permissionRejected) return "Stopped after a permission was rejected.";
688
- if (!text) throw new Error("OpenCode completed without assistant text.");
689
- return text;
690
- }
691
- await delay(options.pollIntervalMs, undefined, { signal });
692
- }
452
+ const selected = input.model ?? (input.defaultEligible ? input.defaultModel : null);
453
+ if (selected) await client.session.switchModel({ sessionID: input.sessionId, model: { providerID: selected.providerID, id: selected.modelID ?? selected.id, variant: selected.variant ?? "default" } }, { signal });
454
+ const id = options.inputId?.() ?? `msg_${randomUUID().replaceAll("-", "")}`;
455
+ const admitted = await client.session.prompt({ sessionID: input.sessionId, id, text: input.prompt,
456
+ ...(input.files?.length ? { files: input.files.map((file) => ({ uri: file.url, name: file.filename })) } : {}),
457
+ }, { signal });
458
+ if (admitted?.id !== id || admitted.sessionID !== input.sessionId || admitted.type !== "user" || admitted.payload?.text !== input.prompt) throw new Error("OpenCode returned an invalid prompt admission.");
459
+ if (input.onResponse) return { pending: true };
460
+ return await waiter.promise;
693
461
  } catch (error) {
694
462
  if (signal.aborted) throw signal.reason;
695
463
  throw error;
696
464
  } finally {
697
- await awaitSubmissions();
698
- for (const entry of interactions.values()) settle(entry);
699
- let foreign;
700
- try {
701
- try {
702
- if (records.some((item) => item.key === record.key)) foreign = await cleanup(record);
703
- } catch (cause) {
704
- blocked = new Error(`${cause.message.startsWith("OpenCode attribution conflict") ? "OpenCode attribution conflict. " : ""}Pipa OpenCode cleanup failed. New intake is blocked; recovery records have been retained.`, { cause });
705
- throw blocked;
706
- }
707
- } finally {
708
- stream?.abort();
709
- await watching;
710
- turns.delete(sessionId);
711
- }
712
- if (foreign || record.foreign) throw new Error("OpenCode attribution conflict: foreign input observed during final cleanup.");
465
+ controllers.delete(input.controller);
466
+ signal.removeEventListener("abort", abort);
467
+ if (waiter) observer?.waiters.delete(waiter);
468
+ if (observer && !observer.persistent && !observer.waiters.size) detach(observer);
713
469
  }
714
470
  },
715
- // Local cancellation causes execute's independent cleanup to cancel only owned input.
716
- async abortTurn() {},
471
+ async abortTurn(sessionId) {
472
+ const observer = observers.get(sessionId);
473
+ if (observer) settleWaiters(observer, "");
474
+ await client.session.interrupt({ sessionID: sessionId, resume: false });
475
+ },
476
+ stopAll(reason = new Error("OpenCode bridge stopped.")) {
477
+ stopped = reason;
478
+ const current = [...observers.values()];
479
+ stopping = [...stopping, eventTask, ...current.flatMap((observer) => [observer.task, observer.interactionTask, observer.registration, observer.contextUpdate, observer.reconciliation, ...observer.handlers])];
480
+ for (const controller of controllers) controller.abort(reason);
481
+ for (const observer of current) detach(observer, reason);
482
+ events?.abort(reason);
483
+ },
484
+ async drain() { await Promise.allSettled(stopping); },
717
485
  };
718
486
  }
719
487
 
720
488
  function retryable(error) {
721
489
  return error.reason === "Transport" || (error.reason === "UnexpectedStatus" && [502, 503, 504].includes(error.cause?.status));
722
490
  }
491
+
492
+ function executionError(error) {
493
+ const status = error?.status;
494
+ const http = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
495
+ // Classify native structured errors; provider messages/bodies can contain credentials.
496
+ if (status === 401 || error?.type === "provider.auth") {
497
+ const expired = status === 401 && typeof error.message === "string" && /\bAPI key (?:has )?expired\b/iu.test(error.message);
498
+ return new Error(expired
499
+ ? "OpenCode selected 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."
500
+ : `OpenCode selected provider authentication failed${http}. Reconnect that provider in OpenCode, or choose another provider with your installation's model command, then start a new thread.`);
501
+ }
502
+ return new Error(`OpenCode selected provider ${http ? `failed${http}` : "failed to complete the turn"}.`);
503
+ }