@usepipa/pipa 0.5.5 → 0.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +109 -15
- package/bin/pipa.mjs +8 -13
- package/package.json +6 -2
- package/src/app.mjs +75 -23
- package/src/opencode-v1.mjs +380 -0
- package/src/opencode-v2.mjs +722 -0
- package/src/opencode.mjs +244 -363
- package/src/state.mjs +23 -1
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
import { OpenCode } from "@opencode/client";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
+
import { pipaPaths, writePrivateJson } from "./state.mjs";
|
|
7
|
+
|
|
8
|
+
export function createV2Adapter(options) {
|
|
9
|
+
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)]);
|
|
11
|
+
const response = await options.fetch(url, { ...init, signal });
|
|
12
|
+
if (!response.body) return response;
|
|
13
|
+
const reader = response.body.getReader();
|
|
14
|
+
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
|
+
return new Response(new ReadableStream({
|
|
18
|
+
start(controller) {
|
|
19
|
+
abort = () => {
|
|
20
|
+
controller.error(signal.reason);
|
|
21
|
+
void reader.cancel(signal.reason).catch(() => undefined);
|
|
22
|
+
};
|
|
23
|
+
if (signal.aborted) abort();
|
|
24
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
25
|
+
},
|
|
26
|
+
async pull(controller) {
|
|
27
|
+
try {
|
|
28
|
+
const next = await reader.read();
|
|
29
|
+
signal.throwIfAborted();
|
|
30
|
+
if (next.done) {
|
|
31
|
+
signal.removeEventListener("abort", abort);
|
|
32
|
+
reader.releaseLock();
|
|
33
|
+
controller.close();
|
|
34
|
+
} else controller.enqueue(next.value);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
signal.removeEventListener("abort", abort);
|
|
37
|
+
controller.error(error);
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
cancel(reason) {
|
|
41
|
+
signal.removeEventListener("abort", abort);
|
|
42
|
+
void reader.cancel(reason).catch(() => undefined);
|
|
43
|
+
},
|
|
44
|
+
}), { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
45
|
+
} });
|
|
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
|
+
|
|
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;
|
|
65
|
+
while (true) {
|
|
66
|
+
if (fatalError) throw fatalError;
|
|
67
|
+
try { return await operation(signal); }
|
|
68
|
+
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
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
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
|
+
async function lookup(sessionId, workingDirectory, signal) {
|
|
104
|
+
let session;
|
|
105
|
+
try { session = await readWithRecovery((readSignal) => client.session.get({ sessionID: sessionId }, { signal: readSignal }), signal); }
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (error._tag === "SessionNotFoundError" && error.sessionID === sessionId) return null;
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
if (session?.id !== sessionId || typeof session.location?.directory !== "string"
|
|
111
|
+
|| path.resolve(session.location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode session workspace identity mismatch.");
|
|
112
|
+
return session;
|
|
113
|
+
}
|
|
114
|
+
|
|
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;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function projection(record, signal) {
|
|
139
|
+
return readWithRecovery((readSignal) => readProjection(record, readSignal), signal);
|
|
140
|
+
}
|
|
141
|
+
|
|
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 };
|
|
193
|
+
}
|
|
194
|
+
|
|
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
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
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;
|
|
218
|
+
}
|
|
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);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function ready(workingDirectory) {
|
|
271
|
+
if (blocked) throw blocked;
|
|
272
|
+
if (fatalError) throw fatalError;
|
|
273
|
+
readiness ??= (async () => {
|
|
274
|
+
try {
|
|
275
|
+
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;
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (error.code !== "ENOENT") throw error;
|
|
283
|
+
records = [];
|
|
284
|
+
}
|
|
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);
|
|
297
|
+
}
|
|
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;
|
|
301
|
+
}
|
|
302
|
+
})();
|
|
303
|
+
await readiness;
|
|
304
|
+
}
|
|
305
|
+
|
|
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.");
|
|
313
|
+
}
|
|
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 };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
ready,
|
|
330
|
+
listModels,
|
|
331
|
+
async switchModel(sessionId, model, workingDirectory, signal) {
|
|
332
|
+
if (typeof sessionId !== "string" || !sessionId) throw new Error("Invalid OpenCode session ID.");
|
|
333
|
+
if (model !== null && (!model || typeof model.providerID !== "string" || !model.providerID || typeof model.id !== "string" || !model.id
|
|
334
|
+
|| (model.variant !== undefined && (typeof model.variant !== "string" || !model.variant)))) throw new Error("Invalid OpenCode model selection.");
|
|
335
|
+
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
|
+
const selection = model === null ? catalog.defaultModel : { providerID: model.providerID, id: model.id, variant: model.variant ?? "default" };
|
|
339
|
+
const available = selection && catalog.models.find((item) => item.providerID === selection.providerID && item.id === selection.id);
|
|
340
|
+
if (!available || !available.variants.includes(selection.variant)) throw new Error("OpenCode model or variant is unavailable.");
|
|
341
|
+
if (!await lookup(sessionId, workingDirectory, signal)) throw new Error("OpenCode session is unavailable; model selection did not create a replacement.");
|
|
342
|
+
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
|
+
await client.session.switchModel({ sessionID: sessionId, model: selection }, { signal });
|
|
346
|
+
},
|
|
347
|
+
async resolveSession(sessionId, workingDirectory, controller) {
|
|
348
|
+
const signal = controller.signal;
|
|
349
|
+
let session = sessionId ? await lookup(sessionId, workingDirectory, signal) : null;
|
|
350
|
+
if (!session) {
|
|
351
|
+
session = await client.session.create({ location: { directory: workingDirectory } }, { signal });
|
|
352
|
+
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
|
+
}
|
|
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) };
|
|
365
|
+
},
|
|
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
|
+
}
|
|
555
|
+
try {
|
|
556
|
+
await mutate((items) => [...items, { ...record }]);
|
|
557
|
+
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
|
+
}
|
|
693
|
+
} catch (error) {
|
|
694
|
+
if (signal.aborted) throw signal.reason;
|
|
695
|
+
throw error;
|
|
696
|
+
} 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.");
|
|
713
|
+
}
|
|
714
|
+
},
|
|
715
|
+
// Local cancellation causes execute's independent cleanup to cancel only owned input.
|
|
716
|
+
async abortTurn() {},
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function retryable(error) {
|
|
721
|
+
return error.reason === "Transport" || (error.reason === "UnexpectedStatus" && [502, 503, 504].includes(error.cause?.status));
|
|
722
|
+
}
|