@usepipa/pipa 0.5.6 → 0.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -6
- package/bin/pipa.mjs +4 -12
- package/package.json +6 -2
- package/src/app.mjs +73 -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 +20 -1
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
import { normalizeModel } from "./state.mjs";
|
|
3
|
+
|
|
4
|
+
// The facade owns files, controllers and caller callbacks; this adapter owns v1 wire data.
|
|
5
|
+
export function createV1Adapter({ request, baseUrl, fetchImpl, headers, pollIntervalMs }) {
|
|
6
|
+
let blocked;
|
|
7
|
+
return {
|
|
8
|
+
async ready() { if (blocked) throw blocked; },
|
|
9
|
+
async listModels(workingDirectory, signal) {
|
|
10
|
+
const catalog = await request("/config/providers", { method: "GET" }, workingDirectory, { signal }, [200], false);
|
|
11
|
+
if (!Array.isArray(catalog?.providers)) throw new Error("OpenCode returned an invalid model catalog.");
|
|
12
|
+
const models = catalog.providers.flatMap((provider) => {
|
|
13
|
+
if (!provider?.models || typeof provider.models !== "object" || Array.isArray(provider.models)) throw new Error("Invalid provider models.");
|
|
14
|
+
return Object.entries(provider.models).map(([id, model]) => {
|
|
15
|
+
const selected = normalizeModel({ providerID: provider.id, modelID: model?.id ?? id });
|
|
16
|
+
return { providerID: selected.providerID, id: selected.modelID, name: typeof model?.name === "string" ? model.name : id, variants: ["default"] };
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
const selected = models.find((model) => catalog.default?.[model.providerID] === model.id);
|
|
20
|
+
return { models, defaultModel: selected ? { providerID: selected.providerID, id: selected.id, variant: "default" } : null };
|
|
21
|
+
},
|
|
22
|
+
async resolveSession(sessionId, workingDirectory, controller) {
|
|
23
|
+
let messages = [];
|
|
24
|
+
if (sessionId) {
|
|
25
|
+
while (true) {
|
|
26
|
+
const status = (await request("/session/status", { method: "GET" }, workingDirectory, controller))?.[sessionId]?.type;
|
|
27
|
+
if (status !== "busy" && status !== "retry") break;
|
|
28
|
+
await delay(pollIntervalMs, undefined, { signal: controller.signal });
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
messages = await request(`/session/${encodeURIComponent(sessionId)}/message?limit=1`, { method: "GET" }, workingDirectory, controller);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (error.status !== 404) throw error;
|
|
34
|
+
// A missing message route is not evidence that a migrated session is absent.
|
|
35
|
+
try {
|
|
36
|
+
const session = await request(`/session/${encodeURIComponent(sessionId)}`, { method: "GET" }, workingDirectory, controller);
|
|
37
|
+
if (session?.id !== sessionId) throw new Error("OpenCode returned an invalid session lookup.");
|
|
38
|
+
throw error;
|
|
39
|
+
} catch (lookupError) {
|
|
40
|
+
if (lookupError === error || lookupError.status !== 404) throw lookupError;
|
|
41
|
+
sessionId = null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!sessionId) {
|
|
46
|
+
const session = await request("/session", { method: "POST", body: "{}" }, workingDirectory, controller);
|
|
47
|
+
if (!session?.id) throw new Error("OpenCode did not create a session.");
|
|
48
|
+
sessionId = session.id;
|
|
49
|
+
messages = [];
|
|
50
|
+
}
|
|
51
|
+
if (!Array.isArray(messages)) throw new Error("OpenCode returned an invalid message projection.");
|
|
52
|
+
const last = messages.at(-1)?.info;
|
|
53
|
+
const threadModel = last?.role === "user" ? last.model
|
|
54
|
+
: last?.providerID && last?.modelID ? { providerID: last.providerID, modelID: last.modelID } : null;
|
|
55
|
+
return { sessionId, threadModel, baseline: new Set(messages.map((message) => message?.info?.id).filter(Boolean)) };
|
|
56
|
+
},
|
|
57
|
+
async execute({ sessionId, baseline, threadModel, model, defaultModel, workingDirectory, controller, prompt, files, instructions, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
|
|
58
|
+
const selectedModel = normalizeModel(model ?? threadModel ?? defaultModel);
|
|
59
|
+
let dismissed;
|
|
60
|
+
let permissionRejected = false;
|
|
61
|
+
let watcher;
|
|
62
|
+
let admitting = false;
|
|
63
|
+
try {
|
|
64
|
+
if (onInteraction) {
|
|
65
|
+
watcher = watchInteractions({ baseUrl, fetchImpl, headers, sessionId, workingDirectory, controller,
|
|
66
|
+
onInteraction, onPermissionReplied, onPermissionsReconciled,
|
|
67
|
+
onPermissionRejected: () => { permissionRejected = true; }, onDismiss: (operation) => { dismissed = operation; }, requestTurn: request });
|
|
68
|
+
await watcher.ready;
|
|
69
|
+
}
|
|
70
|
+
controller.signal.throwIfAborted();
|
|
71
|
+
admitting = true;
|
|
72
|
+
// Await bounded admission independently: cancelling its HTTP request could
|
|
73
|
+
// otherwise race a late server acceptance after native abort has returned.
|
|
74
|
+
const admission = new AbortController();
|
|
75
|
+
const timeout = setTimeout(() => admission.abort(new Error("OpenCode prompt admission timed out.")), 5_000);
|
|
76
|
+
try {
|
|
77
|
+
await request(`/session/${encodeURIComponent(sessionId)}/prompt_async`, {
|
|
78
|
+
method: "POST", body: JSON.stringify({ parts: [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))], system: instructions, ...(selectedModel ? { model: selectedModel } : {}) }),
|
|
79
|
+
}, workingDirectory, admission, [204]);
|
|
80
|
+
} catch (cause) {
|
|
81
|
+
if (cause.status === undefined) {
|
|
82
|
+
blocked = new Error("OpenCode prompt admission remains uncertain. New intake is blocked until the native work is reconciled.", { cause });
|
|
83
|
+
controller.abort(blocked);
|
|
84
|
+
}
|
|
85
|
+
throw cause;
|
|
86
|
+
} finally { clearTimeout(timeout); }
|
|
87
|
+
controller.signal.throwIfAborted();
|
|
88
|
+
while (true) {
|
|
89
|
+
const [messages, statuses] = await Promise.all([
|
|
90
|
+
request(`/session/${encodeURIComponent(sessionId)}/message?limit=1`, { method: "GET" }, workingDirectory, controller),
|
|
91
|
+
request("/session/status", { method: "GET" }, workingDirectory, controller),
|
|
92
|
+
]);
|
|
93
|
+
if (!Array.isArray(messages)) throw new Error("OpenCode returned an invalid message projection.");
|
|
94
|
+
const message = messages.findLast((message) => message?.info?.id && !baseline.has(message.info.id) && message.info.role === "assistant");
|
|
95
|
+
const status = statuses?.[sessionId]?.type;
|
|
96
|
+
if (dismissed) {
|
|
97
|
+
await abortable(dismissed, controller.signal);
|
|
98
|
+
if (status !== "busy" && status !== "retry") return "";
|
|
99
|
+
}
|
|
100
|
+
if (message?.info.error) {
|
|
101
|
+
const error = message.info.error;
|
|
102
|
+
const providerID = message.info.providerID ?? selectedModel?.providerID;
|
|
103
|
+
const provider = typeof providerID === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/iu.test(providerID) ? `provider "${providerID}"` : "selected provider";
|
|
104
|
+
const statusCode = error.data?.statusCode;
|
|
105
|
+
const http = Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599 ? ` (HTTP ${statusCode})` : "";
|
|
106
|
+
// Classify failures without forwarding upstream credentials or bodies.
|
|
107
|
+
if (statusCode === 401 || error.name === "ProviderAuthError") {
|
|
108
|
+
const expiredKey = statusCode === 401 && typeof error.data?.message === "string" && /\bAPI key (?:has )?expired\b/iu.test(error.data.message);
|
|
109
|
+
throw new Error(expiredKey
|
|
110
|
+
? `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.`
|
|
111
|
+
: `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.`);
|
|
112
|
+
}
|
|
113
|
+
throw new Error(`OpenCode ${provider} ${http ? `failed${http}` : "failed to complete the turn"}.`);
|
|
114
|
+
}
|
|
115
|
+
if (["error", "failed", "cancelled"].includes(status)) throw new Error("OpenCode failed to complete the turn.");
|
|
116
|
+
const completed = typeof message?.info.time?.completed === "number";
|
|
117
|
+
if (message && ((status !== "retry" && completed && message.info.finish === "stop") || status === "idle" || (!status && completed))) {
|
|
118
|
+
const text = message.parts.filter((part) => part.type === "text" && typeof part.text === "string" && part.text).map((part) => part.text).join("\n").trim();
|
|
119
|
+
if (!text && permissionRejected) return "Stopped after a permission was rejected.";
|
|
120
|
+
if (!text) throw new Error("OpenCode completed without assistant text.");
|
|
121
|
+
return text;
|
|
122
|
+
}
|
|
123
|
+
await delay(pollIntervalMs, undefined, { signal: controller.signal });
|
|
124
|
+
}
|
|
125
|
+
} finally {
|
|
126
|
+
if (controller.signal.aborted && admitting) {
|
|
127
|
+
// Native abort leaves pending v1 questions behind, including child
|
|
128
|
+
// requests. Settle only sessions whose ancestry this turn verified.
|
|
129
|
+
const cleanup = { signal: AbortSignal.timeout(5_000) };
|
|
130
|
+
try {
|
|
131
|
+
await watcher?.done;
|
|
132
|
+
const sessions = watcher?.sessionIds ?? new Set([sessionId]);
|
|
133
|
+
await request(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, workingDirectory, cleanup, [200, 204, 404], false);
|
|
134
|
+
if (watcher) {
|
|
135
|
+
// The watcher stops on local cancellation, but a child may ask while
|
|
136
|
+
// the independent admission acknowledgement is still in flight.
|
|
137
|
+
const pending = await watcher.pending(cleanup);
|
|
138
|
+
await Promise.all([...sessions].filter((id) => id !== sessionId).map((id) => request(`/session/${encodeURIComponent(id)}/abort`, { method: "POST" }, workingDirectory, cleanup, [200, 204, 404], false)));
|
|
139
|
+
await Promise.all(pending.map(({ type, id }) => request(`/${type}/${encodeURIComponent(id)}/${type === "question" ? "reject" : "reply"}`, {
|
|
140
|
+
method: "POST", ...(type === "permission" ? { body: JSON.stringify({ reply: "reject" }) } : {}),
|
|
141
|
+
}, workingDirectory, cleanup, [200, 204, 404], false)));
|
|
142
|
+
}
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
blocked = new Error("Pipa OpenCode cancellation failed. New intake is blocked until the native work is reconciled.", { cause });
|
|
145
|
+
throw blocked;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
// Cancellation is drained by execute before the facade releases its writer.
|
|
151
|
+
async abortTurn() {},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function watchInteractions({ baseUrl, fetchImpl, headers, sessionId, workingDirectory, controller, onInteraction, onPermissionReplied, onPermissionsReconciled, onPermissionRejected, onDismiss, requestTurn }) {
|
|
156
|
+
const seenIds = new Set();
|
|
157
|
+
const messages = new Map();
|
|
158
|
+
const parents = new Map();
|
|
159
|
+
const interactionSessionIds = new Set([sessionId]);
|
|
160
|
+
const settlements = new Map();
|
|
161
|
+
const readiness = Promise.withResolvers();
|
|
162
|
+
let subscribed = false;
|
|
163
|
+
const dispatch = async (event) => {
|
|
164
|
+
const type = event.type === "question.asked" ? "question" : event.type === "permission.asked" ? "permission" : null;
|
|
165
|
+
const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
|
|
166
|
+
const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
|
|
167
|
+
const requestId = properties?.requestID ?? properties?.requestId ?? properties?.id;
|
|
168
|
+
if (!type || (interactionSessionId !== sessionId && !await belongsToSession(interactionSessionId)) || !requestId || seenIds.has(`${type}:${requestId}`)) return;
|
|
169
|
+
seenIds.add(`${type}:${requestId}`);
|
|
170
|
+
const request = type === "permission" ? await hydratePermission(properties, interactionSessionId) : properties;
|
|
171
|
+
const settlement = { type, sessionId: interactionSessionId, requestId, settled: Promise.withResolvers(), external: false, accepted: false };
|
|
172
|
+
settlements.set(`${type}:${requestId}`, settlement);
|
|
173
|
+
void settleInteraction({ type, requestId, sessionId: interactionSessionId, request, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn, settlement });
|
|
174
|
+
};
|
|
175
|
+
const belongsToSession = async (candidate, readController = controller) => {
|
|
176
|
+
const original = candidate;
|
|
177
|
+
const visited = new Set();
|
|
178
|
+
while (candidate && !visited.has(candidate)) {
|
|
179
|
+
if (candidate === sessionId) { interactionSessionIds.add(original); return true; }
|
|
180
|
+
visited.add(candidate);
|
|
181
|
+
if (!parents.has(candidate)) {
|
|
182
|
+
const id = candidate;
|
|
183
|
+
parents.set(id, requestTurn(`/session/${encodeURIComponent(id)}`, { method: "GET" }, workingDirectory, readController)
|
|
184
|
+
.then((session) => !session?.directory || session.directory === workingDirectory ? session?.parentID : undefined)
|
|
185
|
+
.catch((error) => { parents.delete(id); throw error; }));
|
|
186
|
+
}
|
|
187
|
+
candidate = await parents.get(candidate);
|
|
188
|
+
}
|
|
189
|
+
return false;
|
|
190
|
+
};
|
|
191
|
+
const hydratePermission = async (permission, interactionSessionId) => {
|
|
192
|
+
const tool = permission.tool;
|
|
193
|
+
if (!tool?.messageID || !tool.callID) return permission;
|
|
194
|
+
if (!messages.has(tool.messageID)) messages.set(tool.messageID, requestTurn(`/session/${encodeURIComponent(interactionSessionId)}/message?limit=100`, { method: "GET" }, workingDirectory, controller).then((items) => items.flatMap((message) => message.info?.id === tool.messageID ? message.parts ?? [] : [])).catch(() => {
|
|
195
|
+
messages.delete(tool.messageID);
|
|
196
|
+
controller.signal.throwIfAborted();
|
|
197
|
+
return []; // Tool detail is optional; the native permission remains usable.
|
|
198
|
+
}));
|
|
199
|
+
const part = (await messages.get(tool.messageID)).find((item) => item.callID === tool.callID);
|
|
200
|
+
return part ? { ...permission, tool: { ...tool, name: part.tool, input: part.state?.input } } : permission;
|
|
201
|
+
};
|
|
202
|
+
const reconcile = async () => {
|
|
203
|
+
const before = [...settlements.values()];
|
|
204
|
+
const [permissions, questions] = await Promise.all([
|
|
205
|
+
requestTurn("/permission", { method: "GET" }, workingDirectory, controller),
|
|
206
|
+
requestTurn("/question", { method: "GET" }, workingDirectory, controller),
|
|
207
|
+
]);
|
|
208
|
+
const pending = (await Promise.all((permissions ?? []).map(async (permission) => await belongsToSession(permission?.sessionID) ? permission : null))).filter(Boolean);
|
|
209
|
+
await Promise.all(pending.map((permission) => dispatch({ type: "permission.asked", properties: permission })));
|
|
210
|
+
await Promise.all((questions ?? []).map((question) => dispatch({ type: "question.asked", properties: question })));
|
|
211
|
+
for (const entry of before) {
|
|
212
|
+
const requests = entry.type === "permission" ? permissions : questions;
|
|
213
|
+
if (!entry.accepted && !entry.submitting && !entry.external && !requests.some((request) => request.id === entry.requestId && request.sessionID === entry.sessionId)) {
|
|
214
|
+
entry.external = true;
|
|
215
|
+
entry.settled.resolve();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
for (const interactionSessionId of interactionSessionIds) {
|
|
219
|
+
const requests = pending.filter((permission) => permission.sessionID === interactionSessionId);
|
|
220
|
+
onPermissionsReconciled?.({ sessionId: interactionSessionId, requestIds: new Set(requests.map((permission) => permission.id)) });
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
const watching = (async () => {
|
|
224
|
+
while (!controller.signal.aborted) {
|
|
225
|
+
try {
|
|
226
|
+
const url = new URL(`${baseUrl}/event`);
|
|
227
|
+
url.searchParams.set("directory", workingDirectory);
|
|
228
|
+
const response = await fetchImpl(url, { headers: { ...headers, accept: "text/event-stream" }, signal: controller.signal });
|
|
229
|
+
if (!response.ok) throw Object.assign(new Error(`OpenCode request failed with status ${response.status}.`), { status: response.status });
|
|
230
|
+
await reconcile();
|
|
231
|
+
if (!subscribed) { subscribed = true; readiness.resolve(); }
|
|
232
|
+
for await (const event of readServerSentEvents(response, controller.signal)) {
|
|
233
|
+
if (controller.signal.aborted) return;
|
|
234
|
+
const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
|
|
235
|
+
const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
|
|
236
|
+
if (["question.replied", "question.rejected", "permission.replied"].includes(event.type) && (interactionSessionId === sessionId || await belongsToSession(interactionSessionId))) {
|
|
237
|
+
const type = event.type.startsWith("question") ? "question" : "permission";
|
|
238
|
+
const settlement = settlements.get(`${type}:${properties?.requestID ?? properties?.requestId}`);
|
|
239
|
+
if (settlement && !settlement.accepted) {
|
|
240
|
+
settlement.observed = true;
|
|
241
|
+
if (!settlement.submitting) { settlement.external = true; settlement.settled.resolve(); }
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (event.type === "permission.replied" && (interactionSessionId === sessionId || await belongsToSession(interactionSessionId))) {
|
|
245
|
+
onPermissionReplied?.({ sessionId: interactionSessionId, requestId: properties?.requestID ?? properties?.requestId, reply: properties?.reply });
|
|
246
|
+
await reconcile();
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
await dispatch(event);
|
|
250
|
+
}
|
|
251
|
+
await reconcile();
|
|
252
|
+
await delay(250, undefined, { signal: controller.signal }).catch(() => undefined);
|
|
253
|
+
} catch (error) {
|
|
254
|
+
if (controller.signal.aborted) { if (!subscribed) readiness.reject(controller.signal.reason); return; }
|
|
255
|
+
if (!subscribed) { readiness.reject(error); return; }
|
|
256
|
+
await delay(250, undefined, { signal: controller.signal }).catch(() => undefined);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
})();
|
|
260
|
+
void watching.catch(() => {
|
|
261
|
+
if (!subscribed) readiness.reject(controller.signal.reason ?? new Error("OpenCode interaction watcher failed."));
|
|
262
|
+
else if (!controller.signal.aborted) process.stderr.write("OpenCode interaction watcher failed.\n");
|
|
263
|
+
});
|
|
264
|
+
return {
|
|
265
|
+
ready: readiness.promise, done: watching, sessionIds: interactionSessionIds,
|
|
266
|
+
async pending(cleanup) {
|
|
267
|
+
parents.clear(); // Discard ancestry lookups cancelled with the old turn.
|
|
268
|
+
const pending = await Promise.all(["question", "permission"].map(async (type) => {
|
|
269
|
+
const requests = await requestTurn(`/${type}`, { method: "GET" }, workingDirectory, cleanup, [200], false);
|
|
270
|
+
return (await Promise.all(requests.map(async (request) => await belongsToSession(request.sessionID, cleanup) ? { type, id: request.id } : null))).filter(Boolean);
|
|
271
|
+
}));
|
|
272
|
+
return pending.flat();
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function settleInteraction({ type, requestId, sessionId, request: interactionRequest, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn, settlement }) {
|
|
278
|
+
const stillPending = async () => {
|
|
279
|
+
const pending = await requestTurn(`/${type}`, { method: "GET" }, workingDirectory, controller);
|
|
280
|
+
if (!Array.isArray(pending)) throw new Error("OpenCode response could not be reconciled.");
|
|
281
|
+
// A settlement event may be newer than the snapshot read we just awaited.
|
|
282
|
+
if (settlement.observed || !pending.some((request) => request.id === requestId && request.sessionID === sessionId)) {
|
|
283
|
+
settlement.external = true;
|
|
284
|
+
settlement.settled.resolve();
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
settlement.uncertain = false;
|
|
288
|
+
return true;
|
|
289
|
+
};
|
|
290
|
+
const submit = async (decision) => {
|
|
291
|
+
if (settlement.accepted) return;
|
|
292
|
+
if (settlement.external) throw new Error("OpenCode request is already settled.");
|
|
293
|
+
if (settlement.submitting) throw new Error("OpenCode response is already being submitted.");
|
|
294
|
+
controller.signal.throwIfAborted();
|
|
295
|
+
if (["cancelled", "stopped"].includes(decision?.type)) return;
|
|
296
|
+
const reply = decision?.type === "reply" ? decision.reply : "reject";
|
|
297
|
+
if (type === "permission" && (!["reply", "reject", "stop"].includes(decision?.type) || !["once", "always", "reject"].includes(reply))) throw new Error("Invalid OpenCode permission decision.");
|
|
298
|
+
if (type === "question" && !["answer", "reject", "stop"].includes(decision?.type)) throw new Error("Invalid OpenCode question decision.");
|
|
299
|
+
settlement.submitting = true;
|
|
300
|
+
try {
|
|
301
|
+
if (settlement.uncertain && !await stillPending()) return;
|
|
302
|
+
if (type === "permission") {
|
|
303
|
+
await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply }) }, workingDirectory, controller, [200, 204], false);
|
|
304
|
+
if (reply === "reject") onPermissionRejected?.();
|
|
305
|
+
} else {
|
|
306
|
+
const answer = decision.type === "answer";
|
|
307
|
+
await requestTurn(`/question/${encodeURIComponent(requestId)}/${answer ? "reply" : "reject"}`, {
|
|
308
|
+
method: "POST", ...(answer ? { body: JSON.stringify({ answers: decision.answers }) } : {}),
|
|
309
|
+
}, workingDirectory, controller, [200, 204], false);
|
|
310
|
+
}
|
|
311
|
+
settlement.accepted = true;
|
|
312
|
+
if (decision.type === "stop") {
|
|
313
|
+
const cancellation = requestTurn(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, workingDirectory, controller, [200, 204], false);
|
|
314
|
+
onDismiss?.(cancellation);
|
|
315
|
+
await cancellation;
|
|
316
|
+
}
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (settlement.accepted && decision.type === "stop") {
|
|
319
|
+
// Interaction settlement cannot confirm native cancellation; let execute drain it independently.
|
|
320
|
+
const cancellation = new Error("Pipa OpenCode cancellation could not be confirmed.");
|
|
321
|
+
controller.abort(cancellation);
|
|
322
|
+
throw cancellation;
|
|
323
|
+
}
|
|
324
|
+
if (error.status === undefined || error.status === 404 || error.status >= 500) {
|
|
325
|
+
settlement.uncertain = true;
|
|
326
|
+
if (!await stillPending()) return;
|
|
327
|
+
}
|
|
328
|
+
throw error;
|
|
329
|
+
} finally {
|
|
330
|
+
settlement.submitting = false;
|
|
331
|
+
if (settlement.observed && !settlement.accepted) { settlement.external = true; settlement.settled.resolve(); }
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
try {
|
|
335
|
+
const decision = await abortable(Promise.resolve().then(() => onInteraction({ type, sessionId, request: interactionRequest, signal: controller.signal, submit, settled: settlement.settled.promise })), controller.signal);
|
|
336
|
+
if (!settlement.accepted && !settlement.external && !["cancelled", "stopped"].includes(decision?.type)) await submit(decision);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
if (!controller.signal.aborted) process.stderr.write(`OpenCode interaction handler error: ${error.message}\n`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async function* readServerSentEvents(response, signal) {
|
|
343
|
+
const reader = response.body?.getReader();
|
|
344
|
+
if (!reader) return;
|
|
345
|
+
const abort = () => reader.cancel().catch(() => undefined);
|
|
346
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
347
|
+
const decoder = new TextDecoder();
|
|
348
|
+
let buffer = "";
|
|
349
|
+
try {
|
|
350
|
+
while (true) {
|
|
351
|
+
const { done, value } = await reader.read();
|
|
352
|
+
if (done) break;
|
|
353
|
+
buffer += decoder.decode(value, { stream: true });
|
|
354
|
+
let boundary = buffer.indexOf("\n\n");
|
|
355
|
+
while (boundary >= 0) {
|
|
356
|
+
const chunk = buffer.slice(0, boundary);
|
|
357
|
+
buffer = buffer.slice(boundary + 2);
|
|
358
|
+
const lines = chunk.split("\n");
|
|
359
|
+
const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
|
|
360
|
+
const id = lines.find((line) => line.startsWith("id:"))?.slice(3).trim();
|
|
361
|
+
const type = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
|
|
362
|
+
if (data) {
|
|
363
|
+
try { const event = JSON.parse(data); yield type ? { id, type, data: event } : event; }
|
|
364
|
+
catch { /* ponytail: preserve v1's non-JSON frame handling */ }
|
|
365
|
+
}
|
|
366
|
+
boundary = buffer.indexOf("\n\n");
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
} finally { signal?.removeEventListener("abort", abort); }
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function abortable(operation, signal) {
|
|
373
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
374
|
+
return new Promise((resolve, reject) => {
|
|
375
|
+
const settle = (callback, value) => { signal.removeEventListener("abort", abort); callback(value); };
|
|
376
|
+
const abort = () => settle(reject, signal.reason);
|
|
377
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
378
|
+
Promise.resolve(operation).then((value) => settle(resolve, value), (error) => settle(reject, error));
|
|
379
|
+
});
|
|
380
|
+
}
|