@usepipa/pipa 0.6.0-beta.1 → 0.6.0-beta.3
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 +68 -122
- package/bin/pipa.mjs +5 -15
- package/package.json +1 -1
- package/src/app.mjs +79 -31
- package/src/errors.mjs +4 -0
- package/src/models.mjs +46 -54
- package/src/opencode-v2.mjs +398 -659
- package/src/opencode.mjs +48 -33
- package/src/state.mjs +0 -2
package/src/opencode-v2.mjs
CHANGED
|
@@ -1,722 +1,461 @@
|
|
|
1
1
|
import { OpenCode } from "@opencode/client";
|
|
2
|
-
import {
|
|
3
|
-
import { lstat, readFile } from "node:fs/promises";
|
|
4
|
-
import path from "node:path";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
5
3
|
import { setTimeout as delay } from "node:timers/promises";
|
|
6
|
-
import { pipaPaths, writePrivateJson } from "./state.mjs";
|
|
7
4
|
|
|
8
5
|
export function createV2Adapter(options) {
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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;
|
|
6
|
+
const observers = new Map();
|
|
7
|
+
const controllers = new Set();
|
|
8
|
+
let events;
|
|
9
|
+
let eventTask;
|
|
10
|
+
let connected = false;
|
|
11
|
+
let stopped;
|
|
12
|
+
let stopping = [];
|
|
13
|
+
const client = OpenCode.make({ baseUrl: options.baseUrl, headers: options.headers, fetch: options.fetch });
|
|
54
14
|
|
|
55
|
-
function
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
15
|
+
async function lookup(sessionId, signal) {
|
|
16
|
+
let session;
|
|
17
|
+
try { session = await client.session.get({ sessionID: sessionId }, { signal }); }
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error._tag === "SessionNotFoundError" && error.sessionID === sessionId) return null;
|
|
20
|
+
throw error;
|
|
59
21
|
}
|
|
60
|
-
|
|
22
|
+
if (session?.id !== sessionId) throw new Error("OpenCode session identity mismatch.");
|
|
23
|
+
return session;
|
|
61
24
|
}
|
|
62
25
|
|
|
63
|
-
async function
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
-
}
|
|
26
|
+
async function listModels(workingDirectory, signal) {
|
|
27
|
+
const input = { location: { directory: workingDirectory } };
|
|
28
|
+
const catalog = await client.model.list(input, { signal });
|
|
29
|
+
if (!Array.isArray(catalog.data)) throw new Error("OpenCode returned an invalid model catalog.");
|
|
30
|
+
const enabled = catalog.data.filter((model) => model?.enabled);
|
|
31
|
+
if (enabled.some((model) => typeof model.id !== "string" || !model.id
|
|
32
|
+
|| typeof model.providerID !== "string" || !model.providerID)) throw new Error("OpenCode returned an invalid model catalog.");
|
|
33
|
+
const models = enabled.map((model) => ({
|
|
34
|
+
providerID: model.providerID, id: model.id, name: model.name,
|
|
35
|
+
}));
|
|
36
|
+
return { models };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function settleWaiters(observer, value, error) {
|
|
40
|
+
for (const waiter of observer.waiters) {
|
|
41
|
+
if (error) waiter.reject(error);
|
|
42
|
+
else waiter.resolve(value);
|
|
89
43
|
}
|
|
90
44
|
}
|
|
91
45
|
|
|
92
|
-
async function
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
await writePrivateJson(journalFile, { version: 1, records: next });
|
|
96
|
-
records = next;
|
|
97
|
-
committed?.(next);
|
|
98
|
-
});
|
|
99
|
-
mutationTail = operation.catch(() => undefined);
|
|
100
|
-
return operation;
|
|
46
|
+
async function report(observer, error) {
|
|
47
|
+
await observer.onError?.(error, observer.controller.signal);
|
|
48
|
+
settleWaiters(observer, undefined, error);
|
|
101
49
|
}
|
|
102
50
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
51
|
+
function detach(observer, reason = new Error("OpenCode observer stopped.")) {
|
|
52
|
+
observer.controller.abort(reason);
|
|
53
|
+
observer.initialized.reject(reason);
|
|
54
|
+
settleWaiters(observer, undefined, reason);
|
|
55
|
+
for (const entry of observer.interactions.values()) entry.settled.resolve();
|
|
56
|
+
if (observers.get(observer.sessionId) === observer) observers.delete(observer.sessionId);
|
|
57
|
+
if (!observers.size) events?.abort(reason);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function belongs(observer, candidate) {
|
|
61
|
+
const visited = new Set();
|
|
62
|
+
while (candidate && !visited.has(candidate)) {
|
|
63
|
+
visited.add(candidate);
|
|
64
|
+
let session;
|
|
65
|
+
try { session = await client.session.get({ sessionID: candidate }, { signal: observer.controller.signal }); }
|
|
66
|
+
catch (error) { if (error._tag === "SessionNotFoundError") return false; throw error; }
|
|
67
|
+
if (session?.id !== candidate) return false;
|
|
68
|
+
if (candidate === observer.sessionId) return true;
|
|
69
|
+
candidate = session.parentID;
|
|
109
70
|
}
|
|
110
|
-
|
|
111
|
-
|| path.resolve(session.location.directory) !== path.resolve(workingDirectory)) throw new Error("OpenCode session workspace identity mismatch.");
|
|
112
|
-
return session;
|
|
71
|
+
return false;
|
|
113
72
|
}
|
|
114
73
|
|
|
115
|
-
async function
|
|
116
|
-
const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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;
|
|
74
|
+
async function pending(observer, entry) {
|
|
75
|
+
const signal = observer.controller.signal;
|
|
76
|
+
if (entry.kind === "permission") return (await client.permission.list({ sessionID: entry.request.sessionID }, { signal })).some((item) => item.id === entry.request.id);
|
|
77
|
+
try { return (await client.session.form.get({ sessionID: entry.request.sessionID, formID: entry.request.id }, { signal })).state.status === "pending"; }
|
|
78
|
+
catch (error) { if (error._tag === "FormNotFoundError") return false; throw error; }
|
|
136
79
|
}
|
|
137
80
|
|
|
138
|
-
|
|
139
|
-
|
|
81
|
+
function settle(entry) {
|
|
82
|
+
if (entry.accepted || entry.external) return;
|
|
83
|
+
entry.external = true;
|
|
84
|
+
entry.settled.resolve();
|
|
140
85
|
}
|
|
141
86
|
|
|
142
|
-
async function
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
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
|
-
}
|
|
87
|
+
async function dispatch(observer, kind, request) {
|
|
88
|
+
const signal = observer.controller.signal;
|
|
89
|
+
const revision = observer.interactionRevision;
|
|
90
|
+
const key = `${kind}:${request.sessionID}:${request.id}`;
|
|
91
|
+
if (!observer.onInteraction || observer.interactions.has(key) || !await belongs(observer, request.sessionID)) return;
|
|
92
|
+
if (observer.interactions.has(key) || signal.aborted || revision !== observer.interactionRevision) return;
|
|
93
|
+
const fields = request.fields;
|
|
94
|
+
const question = kind === "form" && Array.isArray(fields) && fields.length
|
|
95
|
+
&& fields.every((field) => ["string", "multiselect"].includes(field.type) && !field.hidden && !field.when?.length);
|
|
96
|
+
const type = kind === "permission" ? "permission" : question ? "question" : "form";
|
|
97
|
+
let tool;
|
|
98
|
+
if (kind === "permission" && request.source?.type === "tool") {
|
|
99
|
+
try {
|
|
100
|
+
const message = await client.session.message.get({ sessionID: request.sessionID, messageID: request.source.messageID }, { signal });
|
|
101
|
+
const part = message.content?.find((part) => part.type === "tool" && part.id === request.source.id);
|
|
102
|
+
if (part) tool = { name: part.name, input: part.state?.input };
|
|
103
|
+
} catch (error) { if (error._tag !== "MessageNotFoundError") throw error; }
|
|
176
104
|
}
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
105
|
+
if (observer.interactions.has(key) || signal.aborted || revision !== observer.interactionRevision) return;
|
|
106
|
+
const normalized = question ? { ...request, questions: fields.map((field) => ({
|
|
107
|
+
header: field.title || request.title, question: field.description || field.title || request.title,
|
|
108
|
+
multiple: field.type === "multiselect", custom: field.custom ?? !field.options?.length,
|
|
109
|
+
required: field.required ?? false,
|
|
110
|
+
options: field.options,
|
|
111
|
+
})) } : tool ? { ...request, tool } : request;
|
|
112
|
+
const entry = { kind, request, settled: Promise.withResolvers() };
|
|
113
|
+
observer.interactions.set(key, entry);
|
|
114
|
+
const submitDecision = async (decision) => {
|
|
115
|
+
if (entry.accepted) return;
|
|
116
|
+
if (entry.external) throw new Error("OpenCode request is already settled.");
|
|
117
|
+
if (type === "form") throw new Error("This form requires an OpenCode client response.");
|
|
118
|
+
signal.throwIfAborted();
|
|
119
|
+
entry.submitting = true;
|
|
120
|
+
const native = { sessionID: request.sessionID, ...(kind === "form" ? { formID: request.id } : { requestID: request.id }) };
|
|
121
|
+
try {
|
|
122
|
+
if (!await pending(observer, entry)) { settle(entry); throw new Error("OpenCode request is already settled."); }
|
|
123
|
+
try {
|
|
124
|
+
if (kind === "permission") {
|
|
125
|
+
const value = ["reject", "stop"].includes(decision?.type) ? "reject" : decision?.type === "reply" ? decision.reply : null;
|
|
126
|
+
if (!["once", "always", "reject"].includes(value)) throw new Error("Invalid OpenCode permission decision.");
|
|
127
|
+
await client.permission.reply({ ...native, decision: value }, { signal });
|
|
128
|
+
} else if (["reject", "stop"].includes(decision?.type)) {
|
|
129
|
+
await client.session.form.cancel(native, { signal });
|
|
130
|
+
} else if (question && decision?.type === "answer") {
|
|
131
|
+
if (!Array.isArray(decision.answers) || decision.answers.length !== fields.length) throw new Error("Invalid OpenCode question answers.");
|
|
132
|
+
const answer = Object.fromEntries(fields.flatMap((field, index) => {
|
|
133
|
+
const values = decision.answers[index];
|
|
134
|
+
if (values === null && !field.required) return [];
|
|
135
|
+
if (!Array.isArray(values) || !values.every((value) => typeof value === "string") || (field.type === "string" && values.length !== 1)) throw new Error("Invalid OpenCode question answer.");
|
|
136
|
+
return [[field.key, field.type === "multiselect" ? values : values[0]]];
|
|
137
|
+
}));
|
|
138
|
+
await client.session.form.reply({ ...native, answer }, { signal });
|
|
139
|
+
} else throw new Error("This form requires an OpenCode client response.");
|
|
140
|
+
} catch (error) {
|
|
141
|
+
signal.throwIfAborted();
|
|
142
|
+
if (["Transport", "MalformedResponse"].includes(error.reason)
|
|
143
|
+
|| (error.reason === "UnexpectedStatus" && [502, 503, 504].includes(error.cause?.status))
|
|
144
|
+
|| ["FormAlreadySettledError", "FormNotFoundError", "PermissionNotFoundError"].includes(error._tag)) {
|
|
145
|
+
if (!await pending(observer, entry)) { settle(entry); return; }
|
|
146
|
+
else throw error;
|
|
147
|
+
} else throw error;
|
|
189
148
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
149
|
+
entry.accepted = true;
|
|
150
|
+
// Native rejection/cancellation need not produce an idle event.
|
|
151
|
+
if (decision.type === "stop") {
|
|
152
|
+
try { await client.session.interrupt({ sessionID: request.sessionID, resume: false }, { signal }); }
|
|
153
|
+
finally { settleWaiters(observer, ""); }
|
|
154
|
+
} else if (decision.type === "reject" || decision.reply === "reject") settleWaiters(observer, "Stopped after a request was rejected.");
|
|
155
|
+
} finally { entry.submitting = false; }
|
|
156
|
+
};
|
|
157
|
+
const submit = (decision) => {
|
|
158
|
+
if (entry.submitting) return Promise.reject(new Error("OpenCode response is already being submitted."));
|
|
159
|
+
const submission = submitDecision(decision);
|
|
160
|
+
observer.handlers.add(submission);
|
|
161
|
+
void submission.then(() => observer.handlers.delete(submission), () => observer.handlers.delete(submission));
|
|
162
|
+
return submission;
|
|
163
|
+
};
|
|
164
|
+
const handler = Promise.resolve().then(() => {
|
|
165
|
+
signal.throwIfAborted();
|
|
166
|
+
return observer.onInteraction({ type, request: normalized, sessionId: request.sessionID, signal, submit, settled: entry.settled.promise });
|
|
167
|
+
})
|
|
168
|
+
.then(async (decision) => {
|
|
169
|
+
if (!entry.accepted && !entry.external && !signal.aborted && !["cancelled", "stopped"].includes(decision?.type)) await submit(decision);
|
|
170
|
+
}).catch(() => { if (!signal.aborted) process.stderr.write("OpenCode interaction handler failed.\n"); });
|
|
171
|
+
observer.handlers.add(handler);
|
|
172
|
+
void handler.finally(() => observer.handlers.delete(handler));
|
|
193
173
|
}
|
|
194
174
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
}
|
|
209
|
-
throw error;
|
|
210
|
-
}
|
|
175
|
+
function reconcile(observer) {
|
|
176
|
+
observer.reconcileRequested = true;
|
|
177
|
+
if (observer.reconciliation) return observer.reconciliation;
|
|
178
|
+
observer.reconciliation = Promise.resolve().then(async () => {
|
|
179
|
+
try {
|
|
180
|
+
while (observer.reconcileRequested && !observer.controller.signal.aborted) {
|
|
181
|
+
observer.reconcileRequested = false;
|
|
182
|
+
try { await reconcilePending(observer); }
|
|
183
|
+
catch (error) { if (!observer.reconcileRequested) throw error; }
|
|
184
|
+
}
|
|
185
|
+
} finally { observer.reconciliation = undefined; }
|
|
186
|
+
});
|
|
187
|
+
return observer.reconciliation;
|
|
211
188
|
}
|
|
212
189
|
|
|
213
|
-
async function
|
|
214
|
-
if (
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
if (
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
await mutate((items) => items.map((item) => item.key === record.key ? { ...record } : item));
|
|
190
|
+
async function reconcilePending(observer) {
|
|
191
|
+
if (!observer.onInteraction && !observer.onPermissionsReconciled) return;
|
|
192
|
+
const signal = observer.controller.signal;
|
|
193
|
+
const revision = observer.interactionRevision;
|
|
194
|
+
const sessionIds = new Set([observer.sessionId]);
|
|
195
|
+
for (const sessionId of sessionIds) {
|
|
196
|
+
signal.throwIfAborted();
|
|
197
|
+
const input = { sessionID: sessionId };
|
|
198
|
+
const results = await Promise.allSettled(["form", "permission"].map(async (kind) => {
|
|
199
|
+
let snapshot;
|
|
200
|
+
try {
|
|
201
|
+
snapshot = await (kind === "form"
|
|
202
|
+
? client.session.form.list(input, { signal }) : client.permission.list(input, { signal }));
|
|
203
|
+
if (!Array.isArray(snapshot) || snapshot.some((request) => request.sessionID !== sessionId)) throw new Error("OpenCode returned an invalid interaction projection.");
|
|
204
|
+
} catch {
|
|
205
|
+
if (!signal.aborted) process.stderr.write(`OpenCode ${kind} reconciliation read failed.\n`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (signal.aborted || revision !== observer.interactionRevision) return;
|
|
209
|
+
for (const request of snapshot) await dispatch(observer, kind, request);
|
|
210
|
+
if (signal.aborted || revision !== observer.interactionRevision) return;
|
|
211
|
+
for (const [key, entry] of observer.interactions) {
|
|
212
|
+
if (entry.kind === kind && entry.request.sessionID === sessionId && !entry.submitting && !snapshot.some((request) => request.id === entry.request.id)) {
|
|
213
|
+
settle(entry);
|
|
214
|
+
observer.interactions.delete(key);
|
|
239
215
|
}
|
|
240
216
|
}
|
|
241
|
-
if (
|
|
242
|
-
|
|
243
|
-
|
|
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);
|
|
217
|
+
if (kind === "permission" && observer.onPermissionsReconciled && await belongs(observer, sessionId)
|
|
218
|
+
&& !signal.aborted && revision === observer.interactionRevision) {
|
|
219
|
+
await observer.onPermissionsReconciled({ sessionId, requestIds: new Set(snapshot.map((request) => request.id)) });
|
|
255
220
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
221
|
+
}));
|
|
222
|
+
for (const result of results) if (result.status === "rejected") throw result.reason;
|
|
223
|
+
if (signal.aborted || revision !== observer.interactionRevision) return;
|
|
224
|
+
let cursor;
|
|
225
|
+
do {
|
|
226
|
+
try {
|
|
227
|
+
const page = await client.session.list({ parentID: sessionId, ...(cursor ? { cursor } : {}) }, { signal });
|
|
228
|
+
if (!Array.isArray(page.data)) throw new Error("OpenCode returned an invalid session projection.");
|
|
229
|
+
for (const child of page.data) if (typeof child.id === "string" && child.parentID === sessionId) sessionIds.add(child.id);
|
|
230
|
+
cursor = page.cursor.next;
|
|
231
|
+
} catch {
|
|
232
|
+
if (!signal.aborted) process.stderr.write("OpenCode descendant discovery failed.\n");
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
} while (cursor);
|
|
236
|
+
}
|
|
268
237
|
}
|
|
269
238
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
if (
|
|
273
|
-
|
|
274
|
-
|
|
239
|
+
// Native 2.2.5's experimental session log emits no responses; forward live events only.
|
|
240
|
+
function watchEvents() {
|
|
241
|
+
if (events && !events.signal.aborted) return;
|
|
242
|
+
events = new AbortController();
|
|
243
|
+
connected = false;
|
|
244
|
+
const signal = events.signal;
|
|
245
|
+
eventTask = (async () => {
|
|
246
|
+
while (!signal.aborted) {
|
|
275
247
|
try {
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
248
|
+
for await (const event of client.event.subscribe({ signal })) {
|
|
249
|
+
if (event.type === "server.connected") {
|
|
250
|
+
connected = true;
|
|
251
|
+
for (const observer of observers.values()) {
|
|
252
|
+
queueResponse(observer, async () => {
|
|
253
|
+
if (!await lookup(observer.sessionId, observer.controller.signal)) throw new Error("OpenCode session is unavailable.");
|
|
254
|
+
observer.initialized.resolve();
|
|
255
|
+
}, true);
|
|
256
|
+
void reconcile(observer).catch(() => undefined);
|
|
257
|
+
}
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
for (const observer of observers.values()) {
|
|
261
|
+
if (event.data?.sessionID === observer.sessionId) {
|
|
262
|
+
if (event.type === "session.step.ended" && event.data.finish === "stop") queueResponse(observer, async () => {
|
|
263
|
+
const message = await client.session.message.get({ sessionID: observer.sessionId, messageID: event.data.assistantMessageID }, { signal: observer.controller.signal });
|
|
264
|
+
await deliverResponse(observer, message);
|
|
265
|
+
});
|
|
266
|
+
if (event.type === "session.execution.failed") queueResponse(observer, () => report(observer, Object.assign(new Error(event.data.error.message), event.data.error)));
|
|
267
|
+
if (event.type === "session.execution.interrupted") settleWaiters(observer, "");
|
|
268
|
+
if (event.type === "session.tool.called") void reconcile(observer).catch(() => undefined);
|
|
269
|
+
}
|
|
270
|
+
if (!["form.created", "permission.asked", "form.replied", "form.cancelled", "permission.replied", "location.shutdown", "session.created", "session.forked", "session.moved"].includes(event.type)) continue;
|
|
271
|
+
observer.interactionTask = (observer.interactionTask ?? Promise.resolve()).then(async () => {
|
|
272
|
+
if (observer.controller.signal.aborted) return;
|
|
273
|
+
if (["session.created", "session.forked", "session.moved"].includes(event.type)
|
|
274
|
+
&& await belongs(observer, event.data.parentID ?? event.data.sessionID)) void reconcile(observer).catch(() => undefined);
|
|
275
|
+
if (event.type === "form.created") await dispatch(observer, "form", event.data.form);
|
|
276
|
+
if (event.type === "permission.asked") await dispatch(observer, "permission", event.data);
|
|
277
|
+
if (event.type === "permission.replied" && await belongs(observer, event.data.sessionID)) {
|
|
278
|
+
const key = `${event.data.sessionID}:${event.data.requestID}`;
|
|
279
|
+
if (!observer.replied.has(key)) {
|
|
280
|
+
await observer.onPermissionReplied?.({ sessionId: event.data.sessionID, requestId: event.data.requestID, reply: event.data.reply });
|
|
281
|
+
observer.replied.add(key);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (["form.replied", "form.cancelled", "permission.replied", "location.shutdown"].includes(event.type)) {
|
|
285
|
+
observer.interactionRevision++;
|
|
286
|
+
const kind = event.type.startsWith("form.") ? "form" : "permission";
|
|
287
|
+
const id = kind === "form" ? event.data?.id : event.data?.requestID;
|
|
288
|
+
const entry = observer.interactions.get(`${kind}:${event.data?.sessionID}:${id}`);
|
|
289
|
+
if (entry && !entry.submitting) settle(entry);
|
|
290
|
+
void reconcile(observer).catch(() => undefined);
|
|
291
|
+
}
|
|
292
|
+
}).catch(() => { if (!observer.controller.signal.aborted) process.stderr.write("OpenCode interaction event failed.\n"); });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
} catch { if (signal.aborted) return; }
|
|
296
|
+
connected = false;
|
|
297
|
+
await delay(options.pollIntervalMs ?? 100, undefined, { signal }).catch(() => undefined);
|
|
301
298
|
}
|
|
302
299
|
})();
|
|
303
|
-
await readiness;
|
|
304
300
|
}
|
|
305
301
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
302
|
+
function queueResponse(observer, operation, fatal = false) {
|
|
303
|
+
observer.task = (observer.task ?? Promise.resolve()).then(async () => {
|
|
304
|
+
const signal = observer.controller.signal;
|
|
305
|
+
if (signal.aborted) return;
|
|
306
|
+
try { await operation(); }
|
|
307
|
+
catch (error) {
|
|
308
|
+
if (signal.aborted) return;
|
|
309
|
+
if (fatal) {
|
|
310
|
+
observer.initialized.reject(error);
|
|
311
|
+
await report(observer, error).catch(() => undefined);
|
|
312
|
+
detach(observer, error);
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
await report(observer, error).catch(() => process.stderr.write("Pipa could not deliver an OpenCode response.\n"));
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function deliverResponse(observer, message) {
|
|
321
|
+
if (observer.controller.signal.aborted || observer.delivered.has(message.id)) return;
|
|
322
|
+
if (message.type !== "assistant" || message.finish !== "stop" || typeof message.time?.completed !== "number") return;
|
|
323
|
+
if (!Array.isArray(message.content)) throw new Error("OpenCode returned an invalid assistant message.");
|
|
324
|
+
const text = message.content.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n").trim();
|
|
325
|
+
// A failed Slack post may have sent earlier chunks; never replay the whole response.
|
|
326
|
+
observer.delivered.add(message.id);
|
|
327
|
+
if (text) {
|
|
328
|
+
await observer.onResponse?.(text, message.id, observer.controller.signal);
|
|
313
329
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
330
|
+
settleWaiters(observer, text);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function follow(input, persistent, waiter) {
|
|
334
|
+
if (stopped) throw stopped;
|
|
335
|
+
if (typeof input.sessionId !== "string" || !input.sessionId || typeof input.workingDirectory !== "string" || !input.workingDirectory) throw new Error("Invalid OpenCode session context.");
|
|
336
|
+
let observer = observers.get(input.sessionId);
|
|
337
|
+
const created = !observer;
|
|
338
|
+
if (!observer) {
|
|
339
|
+
observer = { sessionId: input.sessionId, controller: new AbortController(), initialized: Promise.withResolvers(), delivered: new Set(), replied: new Set(), waiters: new Set(), handlers: new Set(), interactions: new Map(), interactionRevision: 0, persistent };
|
|
340
|
+
observers.set(input.sessionId, observer);
|
|
341
|
+
// Observe rejection immediately, including shutdown during initial attachment.
|
|
342
|
+
void observer.initialized.promise.catch(() => undefined);
|
|
343
|
+
observer.registration = (async () => {
|
|
344
|
+
const signal = observer.controller.signal;
|
|
345
|
+
if (!await lookup(input.sessionId, signal)) throw new Error("OpenCode session is unavailable.");
|
|
346
|
+
try {
|
|
347
|
+
const entries = await client.session.instructions.entry.list({ sessionID: input.sessionId }, { signal });
|
|
348
|
+
observer.instructions = entries.find((entry) => entry.key === "pipa.slack")?.value;
|
|
349
|
+
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 })));
|
|
350
|
+
} catch { signal.throwIfAborted(); /* Old context migration is best effort and session-local. */ }
|
|
351
|
+
watchEvents();
|
|
352
|
+
if (connected) observer.initialized.resolve();
|
|
353
|
+
await observer.initialized.promise;
|
|
354
|
+
})();
|
|
355
|
+
}
|
|
356
|
+
if (waiter) observer.waiters.add(waiter);
|
|
357
|
+
observer.persistent ||= persistent;
|
|
358
|
+
for (const key of ["onResponse", "onError", "onInteraction", "onPermissionReplied", "onPermissionsReconciled"]) if (input[key] !== undefined) observer[key] = input[key];
|
|
359
|
+
try {
|
|
360
|
+
await observer.registration;
|
|
361
|
+
observer.contextUpdate = (observer.contextUpdate ?? Promise.resolve()).catch(() => undefined).then(async () => {
|
|
362
|
+
if (input.instructions !== undefined && observer.instructions !== input.instructions) {
|
|
363
|
+
await client.session.instructions.entry.put({ sessionID: input.sessionId, key: "pipa.slack", value: input.instructions }, { signal: observer.controller.signal });
|
|
364
|
+
observer.instructions = input.instructions;
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
await observer.contextUpdate;
|
|
368
|
+
if (observer.onInteraction || observer.onPermissionReplied || observer.onPermissionsReconciled) {
|
|
369
|
+
watchEvents();
|
|
370
|
+
await reconcile(observer).catch(() => undefined);
|
|
371
|
+
}
|
|
372
|
+
return observer;
|
|
373
|
+
} catch (error) { if (created) detach(observer, error); throw error; }
|
|
326
374
|
}
|
|
327
375
|
|
|
328
376
|
return {
|
|
329
|
-
ready,
|
|
377
|
+
async ready(workingDirectory) { if (stopped) throw stopped; },
|
|
330
378
|
listModels,
|
|
331
379
|
async switchModel(sessionId, model, workingDirectory, signal) {
|
|
332
380
|
if (typeof sessionId !== "string" || !sessionId) throw new Error("Invalid OpenCode session ID.");
|
|
333
381
|
if (model !== null && (!model || typeof model.providerID !== "string" || !model.providerID || typeof model.id !== "string" || !model.id
|
|
334
382
|
|| (model.variant !== undefined && (typeof model.variant !== "string" || !model.variant)))) throw new Error("Invalid OpenCode model selection.");
|
|
335
|
-
const
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
if (!
|
|
341
|
-
if (!await lookup(sessionId, workingDirectory, signal)) throw new Error("OpenCode session is unavailable; model selection did not create a replacement.");
|
|
383
|
+
const session = await lookup(sessionId, signal);
|
|
384
|
+
if (!session) throw new Error("OpenCode session is unavailable; model selection did not create a replacement.");
|
|
385
|
+
const selection = model === null ? (await client.model.default({ location: { directory: session.location.directory } }, { signal })).data
|
|
386
|
+
: model;
|
|
387
|
+
if (selection !== null && (!selection || typeof selection.providerID !== "string" || typeof selection.id !== "string")) throw new Error("OpenCode returned an invalid default model.");
|
|
388
|
+
if (!selection) throw new Error("OpenCode default model is unavailable.");
|
|
342
389
|
signal.throwIfAborted();
|
|
343
|
-
|
|
344
|
-
// in-flight step. Native switching applies to subsequent provider steps.
|
|
345
|
-
await client.session.switchModel({ sessionID: sessionId, model: selection }, { signal });
|
|
390
|
+
await client.session.switchModel({ sessionID: sessionId, model: { providerID: selection.providerID, id: selection.id, variant: model?.variant ?? "default" } }, { signal });
|
|
346
391
|
},
|
|
347
392
|
async resolveSession(sessionId, workingDirectory, controller) {
|
|
348
393
|
const signal = controller.signal;
|
|
349
|
-
let session = sessionId ? await lookup(sessionId,
|
|
394
|
+
let session = sessionId ? await lookup(sessionId, signal) : null;
|
|
395
|
+
const created = !session;
|
|
350
396
|
if (!session) {
|
|
351
397
|
session = await client.session.create({ location: { directory: workingDirectory } }, { signal });
|
|
352
|
-
if (typeof session?.id !== "string" || session.
|
|
353
|
-
sessionId = session.id;
|
|
398
|
+
if (typeof session?.id !== "string" || !session.id) throw new Error("OpenCode did not return a usable session identity.");
|
|
354
399
|
}
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
|
|
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) };
|
|
400
|
+
const history = !created && !session.model ? await client.message.list({ sessionID: session.id, limit: 1 }, { signal }) : null;
|
|
401
|
+
if (history && !Array.isArray(history.data)) throw new Error("OpenCode returned an invalid message projection.");
|
|
402
|
+
return { sessionId: session.id, defaultEligible: !session.model && (created || !history.data.length) };
|
|
365
403
|
},
|
|
366
|
-
async
|
|
367
|
-
|
|
368
|
-
const signal = controller.signal;
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
const
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
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
|
-
}
|
|
404
|
+
async followSession(input) { await follow(input, true); },
|
|
405
|
+
async execute(input) {
|
|
406
|
+
const signal = input.controller.signal;
|
|
407
|
+
signal.throwIfAborted();
|
|
408
|
+
controllers.add(input.controller);
|
|
409
|
+
const waiter = input.onResponse ? null : Promise.withResolvers();
|
|
410
|
+
if (waiter) void waiter.promise.catch(() => undefined);
|
|
411
|
+
const cancelled = Promise.withResolvers();
|
|
412
|
+
void cancelled.promise.catch(() => undefined);
|
|
413
|
+
let observer;
|
|
414
|
+
const abort = () => {
|
|
415
|
+
cancelled.reject(signal.reason);
|
|
416
|
+
if (waiter) waiter.reject(signal.reason);
|
|
417
|
+
const current = observer ?? observers.get(input.sessionId);
|
|
418
|
+
if (current && !current.persistent && current.waiters.size <= 1) detach(current, signal.reason);
|
|
419
|
+
};
|
|
420
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
555
421
|
try {
|
|
556
|
-
await
|
|
422
|
+
observer = await Promise.race([follow(input, Boolean(input.onResponse), waiter), cancelled.promise]);
|
|
557
423
|
signal.throwIfAborted();
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
const
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
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
|
-
}
|
|
424
|
+
const selected = input.model ?? (input.defaultEligible ? input.defaultModel : null);
|
|
425
|
+
if (selected) await client.session.switchModel({ sessionID: input.sessionId, model: { providerID: selected.providerID, id: selected.modelID ?? selected.id, variant: selected.variant ?? "default" } }, { signal });
|
|
426
|
+
const id = options.inputId?.() ?? `msg_${randomUUID().replaceAll("-", "")}`;
|
|
427
|
+
await client.session.prompt({ sessionID: input.sessionId, id, text: input.prompt,
|
|
428
|
+
...(input.files?.length ? { files: input.files.map((file) => ({ uri: file.url, name: file.filename })) } : {}),
|
|
429
|
+
}, { signal });
|
|
430
|
+
if (input.onResponse) return { pending: true };
|
|
431
|
+
return await waiter.promise;
|
|
693
432
|
} catch (error) {
|
|
694
433
|
if (signal.aborted) throw signal.reason;
|
|
695
434
|
throw error;
|
|
696
435
|
} finally {
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
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.");
|
|
436
|
+
controllers.delete(input.controller);
|
|
437
|
+
signal.removeEventListener("abort", abort);
|
|
438
|
+
if (waiter) observer?.waiters.delete(waiter);
|
|
439
|
+
if (observer && !observer.persistent && !observer.waiters.size) detach(observer);
|
|
713
440
|
}
|
|
714
441
|
},
|
|
715
|
-
|
|
716
|
-
|
|
442
|
+
async abortTurn(sessionId) {
|
|
443
|
+
if (stopped) throw stopped;
|
|
444
|
+
const observer = observers.get(sessionId);
|
|
445
|
+
if (observer) settleWaiters(observer, "");
|
|
446
|
+
const controller = new AbortController();
|
|
447
|
+
controllers.add(controller);
|
|
448
|
+
try { await client.session.interrupt({ sessionID: sessionId, resume: false }, { signal: controller.signal }); }
|
|
449
|
+
finally { controllers.delete(controller); }
|
|
450
|
+
},
|
|
451
|
+
stopAll(reason = new Error("OpenCode bridge stopped.")) {
|
|
452
|
+
stopped = reason;
|
|
453
|
+
const current = [...observers.values()];
|
|
454
|
+
stopping = [...stopping, eventTask, ...current.flatMap((observer) => [observer.task, observer.interactionTask, observer.registration, observer.contextUpdate, observer.reconciliation, ...observer.handlers])];
|
|
455
|
+
for (const controller of controllers) controller.abort(reason);
|
|
456
|
+
for (const observer of current) detach(observer, reason);
|
|
457
|
+
events?.abort(reason);
|
|
458
|
+
},
|
|
459
|
+
async drain() { await Promise.allSettled(stopping); },
|
|
717
460
|
};
|
|
718
461
|
}
|
|
719
|
-
|
|
720
|
-
function retryable(error) {
|
|
721
|
-
return error.reason === "Transport" || (error.reason === "UnexpectedStatus" && [502, 503, 504].includes(error.cause?.status));
|
|
722
|
-
}
|