@usepipa/pipa 0.3.2 → 0.4.0
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 +2 -18
- package/bin/pipa.mjs +30 -19
- package/package.json +2 -2
- package/src/app.mjs +317 -14
- package/src/opencode.mjs +224 -12
- package/src/state.mjs +13 -0
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
[](https://github.com/lunchpaillola/pipa/actions/workflows/ci.yml)
|
|
4
4
|
[](LICENSE)
|
|
5
5
|
|
|
6
|
-
Pipa runs
|
|
6
|
+
Pipa runs Slack through one persistent private OpenCode server with no hosted relay, database, public endpoint, or sandbox.
|
|
7
7
|
|
|
8
8
|
**Pipa is in early preview. Features may break unintentionally, and CLI commands, configuration, and Slack behavior may continue to change.**
|
|
9
9
|
|
|
@@ -67,27 +67,11 @@ export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
|
|
|
67
67
|
pipa start
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
-
## Managed Mode
|
|
71
|
-
|
|
72
|
-
Managed mode starts exactly one persistent `opencode serve` child and does not connect to Slack or require Slack tokens. Create `~/.pipa/config.json` (or `$PIPA_HOME/.pipa/config.json`) with a private hostname and TCP port:
|
|
73
|
-
|
|
74
|
-
```json
|
|
75
|
-
{
|
|
76
|
-
"botName": "Pipa",
|
|
77
|
-
"workingDirectory": "/workspace",
|
|
78
|
-
"slackMode": "managed",
|
|
79
|
-
"openCodeHostname": "127.0.0.1",
|
|
80
|
-
"openCodePort": 4096
|
|
81
|
-
}
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
Then run `pipa start`. The OpenCode child inherits the working process environment, so runtime credentials and service configuration should remain in environment variables rather than the profile. `SIGINT` and `SIGTERM` are forwarded to the child.
|
|
85
|
-
|
|
86
70
|
## Commands
|
|
87
71
|
|
|
88
72
|
```text
|
|
89
73
|
pipa init Configure Slack and the local working directory
|
|
90
|
-
pipa start Start the configured
|
|
74
|
+
pipa start Start the configured Slack runtime
|
|
91
75
|
pipa --version Print the installed version
|
|
92
76
|
```
|
|
93
77
|
|
package/bin/pipa.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { readFile } from "node:fs/promises";
|
|
|
5
5
|
import { createInterface } from "node:readline/promises";
|
|
6
6
|
import { Writable } from "node:stream";
|
|
7
7
|
import { stdin, stdout } from "node:process";
|
|
8
|
-
import { acquireInstanceLock, createManifest, createManifestUrl, loadConfig } from "../src/state.mjs";
|
|
8
|
+
import { acquireInstanceLock, createManifest, createManifestUrl, loadConfig, stopInstance } from "../src/state.mjs";
|
|
9
9
|
import { initializePipa, startPipa } from "../src/app.mjs";
|
|
10
10
|
import { startOpenCodeServer } from "../src/opencode.mjs";
|
|
11
11
|
|
|
@@ -19,7 +19,13 @@ async function main(argv = process.argv.slice(2), io = { input: stdin, output: s
|
|
|
19
19
|
}
|
|
20
20
|
if (command === "init") return init(io);
|
|
21
21
|
if (command === "start") return start(io);
|
|
22
|
-
|
|
22
|
+
if (command === "stop") return stop(io);
|
|
23
|
+
throw new Error("Usage: pipa init | pipa start | pipa stop | pipa --version");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function stop(io) {
|
|
27
|
+
const pid = await stopInstance();
|
|
28
|
+
io.output.write(pid ? `Pipa is stopping (PID ${pid}).\n` : "Pipa is not running.\n");
|
|
23
29
|
}
|
|
24
30
|
|
|
25
31
|
async function init(io) {
|
|
@@ -102,21 +108,19 @@ function openUrl(url) {
|
|
|
102
108
|
|
|
103
109
|
async function start(io) {
|
|
104
110
|
const releaseLock = await acquireInstanceLock();
|
|
111
|
+
let stop;
|
|
112
|
+
let stopWithSigint;
|
|
113
|
+
let stopWithSigterm;
|
|
105
114
|
try {
|
|
106
115
|
const config = await loadConfig();
|
|
107
116
|
if (config.slackMode === "managed") {
|
|
108
117
|
const server = startOpenCodeServer(config);
|
|
109
118
|
io.output.write(`Pipa is starting OpenCode on ${config.openCodeHostname}:${config.openCodePort}.\n`);
|
|
110
|
-
|
|
111
|
-
|
|
119
|
+
stopWithSigint = () => server.stop("SIGINT");
|
|
120
|
+
stopWithSigterm = () => server.stop("SIGTERM");
|
|
112
121
|
process.on("SIGINT", stopWithSigint);
|
|
113
122
|
process.on("SIGTERM", stopWithSigterm);
|
|
114
|
-
|
|
115
|
-
await server.wait();
|
|
116
|
-
} finally {
|
|
117
|
-
process.off("SIGINT", stopWithSigint);
|
|
118
|
-
process.off("SIGTERM", stopWithSigterm);
|
|
119
|
-
}
|
|
123
|
+
await server.wait();
|
|
120
124
|
return;
|
|
121
125
|
}
|
|
122
126
|
|
|
@@ -125,22 +129,29 @@ async function start(io) {
|
|
|
125
129
|
? `Pipa started a private OpenCode server at ${app.server.baseUrl}.\n`
|
|
126
130
|
: `Pipa is using the configured OpenCode server at ${app.server.baseUrl}.\n`);
|
|
127
131
|
io.output.write("Pipa is connected through Slack Socket Mode.\n");
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
+
const { promise: signal, resolve: resolveSignal } = Promise.withResolvers();
|
|
133
|
+
stop = () => {
|
|
134
|
+
app.stop();
|
|
135
|
+
resolveSignal();
|
|
136
|
+
};
|
|
137
|
+
process.on("SIGINT", stop);
|
|
138
|
+
process.on("SIGTERM", stop);
|
|
132
139
|
try {
|
|
133
140
|
await Promise.race([signal, app.wait()]);
|
|
134
141
|
} finally {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
142
|
+
await app.shutdown();
|
|
143
|
+
}
|
|
144
|
+
} finally {
|
|
145
|
+
try {
|
|
146
|
+
await releaseLock();
|
|
147
|
+
} finally {
|
|
148
|
+
if (stop) {
|
|
138
149
|
process.off("SIGINT", stop);
|
|
139
150
|
process.off("SIGTERM", stop);
|
|
140
151
|
}
|
|
152
|
+
if (stopWithSigint) process.off("SIGINT", stopWithSigint);
|
|
153
|
+
if (stopWithSigterm) process.off("SIGTERM", stopWithSigterm);
|
|
141
154
|
}
|
|
142
|
-
} finally {
|
|
143
|
-
await releaseLock();
|
|
144
155
|
}
|
|
145
156
|
}
|
|
146
157
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usepipa/pipa",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Run Pipa through Slack Socket Mode
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Run Pipa through Slack Socket Mode with OpenCode",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"slack",
|
|
7
7
|
"opencode",
|
package/src/app.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Chat, Modal, TextInput } from "chat";
|
|
2
3
|
import { createSlackAdapter } from "@chat-adapter/slack";
|
|
3
4
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
4
5
|
import { canonicalWorkingDirectory, createManifest, createSessionStore, loadConfig, pipaPaths, saveConfig } from "./state.mjs";
|
|
5
|
-
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
6
|
+
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
6
7
|
|
|
7
8
|
export async function initializePipa(input, options = {}) {
|
|
8
9
|
const paths = options.paths ?? pipaPaths();
|
|
@@ -60,6 +61,9 @@ export async function startPipa(options = {}) {
|
|
|
60
61
|
}
|
|
61
62
|
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
62
63
|
let accepting = true;
|
|
64
|
+
const interactions = createPendingInteractions();
|
|
65
|
+
chat.onAction?.(interactions.onAction);
|
|
66
|
+
chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
|
|
63
67
|
|
|
64
68
|
const handle = async (thread, message, subscribe) => {
|
|
65
69
|
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
|
|
@@ -75,23 +79,30 @@ export async function startPipa(options = {}) {
|
|
|
75
79
|
|
|
76
80
|
await react(thread, message, "eyes");
|
|
77
81
|
try {
|
|
82
|
+
const interactionContext = { thread };
|
|
78
83
|
const result = await runner.enqueue(thread.id, {
|
|
79
84
|
prompt,
|
|
80
85
|
attachments,
|
|
81
86
|
workingDirectory: config.workingDirectory,
|
|
82
87
|
contextEnvironment: slackContext(thread, message),
|
|
88
|
+
onSession: () => undefined,
|
|
89
|
+
onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
|
|
90
|
+
onPermissionReplied: interactions.onPermissionReplied,
|
|
91
|
+
onPermissionsReconciled: interactions.onPermissionsReconciled,
|
|
83
92
|
deliver: (text) => postInChunks(thread, text),
|
|
84
|
-
deliverFailure: (error) => thread.post(
|
|
93
|
+
deliverFailure: (error) => thread.post(error instanceof PipaStoppedError
|
|
94
|
+
? `${config.botName} stopped before finishing this request.`
|
|
95
|
+
: `${config.botName} failed: ${safeError(error)}`),
|
|
85
96
|
});
|
|
86
|
-
await finishReaction(thread, message, result.error ? "warning" : "white_check_mark");
|
|
97
|
+
await finishReaction(thread, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
|
|
87
98
|
} catch (error) {
|
|
88
99
|
await finishReaction(thread, message, "warning");
|
|
89
100
|
process.stderr.write("Pipa could not complete or deliver a Slack turn.\n");
|
|
90
101
|
}
|
|
91
102
|
};
|
|
92
103
|
|
|
93
|
-
chat.onNewMention((thread, message) => handle(thread, message, true));
|
|
94
|
-
chat.onSubscribedMessage((thread, message) => handle(thread, message, false));
|
|
104
|
+
chat.onNewMention((thread, message) => { void handle(thread, message, true); });
|
|
105
|
+
chat.onSubscribedMessage((thread, message) => { void handle(thread, message, false); });
|
|
95
106
|
try {
|
|
96
107
|
await state.connect();
|
|
97
108
|
for (const conversationKey of sessionStore.keys()) {
|
|
@@ -99,6 +110,7 @@ export async function startPipa(options = {}) {
|
|
|
99
110
|
}
|
|
100
111
|
await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
|
|
101
112
|
} catch (error) {
|
|
113
|
+
await interactions.close();
|
|
102
114
|
executor.stopAll();
|
|
103
115
|
await withTimeout(chat.shutdown(), options.shutdownTimeoutMs ?? 15_000, "Slack shutdown timed out.").catch(() => undefined);
|
|
104
116
|
server?.stop();
|
|
@@ -106,13 +118,27 @@ export async function startPipa(options = {}) {
|
|
|
106
118
|
throw error;
|
|
107
119
|
}
|
|
108
120
|
|
|
121
|
+
const stop = (reason = new PipaStoppedError()) => {
|
|
122
|
+
if (!accepting) return;
|
|
123
|
+
accepting = false;
|
|
124
|
+
runner.close(reason);
|
|
125
|
+
executor.stopAll(reason);
|
|
126
|
+
};
|
|
127
|
+
|
|
109
128
|
return {
|
|
110
129
|
server: server ? { baseUrl: server.baseUrl, owned: server.owned } : null,
|
|
111
|
-
|
|
130
|
+
async wait() {
|
|
131
|
+
try {
|
|
132
|
+
return await (server?.wait() ?? new Promise(() => undefined));
|
|
133
|
+
} catch (error) {
|
|
134
|
+
stop(error);
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
stop: () => stop(),
|
|
112
139
|
async shutdown() {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
executor.stopAll();
|
|
140
|
+
stop();
|
|
141
|
+
await interactions.close();
|
|
116
142
|
try {
|
|
117
143
|
await withTimeout((async () => {
|
|
118
144
|
await runner.drain();
|
|
@@ -127,18 +153,295 @@ export async function startPipa(options = {}) {
|
|
|
127
153
|
};
|
|
128
154
|
}
|
|
129
155
|
|
|
156
|
+
function createPendingInteractions() {
|
|
157
|
+
const pending = new Map();
|
|
158
|
+
const permissionRequests = new Map();
|
|
159
|
+
const tails = new Map();
|
|
160
|
+
|
|
161
|
+
async function onInteraction(context, interaction) {
|
|
162
|
+
const token = randomUUID().replaceAll("-", "");
|
|
163
|
+
const entry = {
|
|
164
|
+
token,
|
|
165
|
+
type: interaction.type,
|
|
166
|
+
request: interaction.request,
|
|
167
|
+
sessionId: interaction.sessionId,
|
|
168
|
+
requestId: interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id,
|
|
169
|
+
questionIndex: 0,
|
|
170
|
+
answers: [],
|
|
171
|
+
resolve: null,
|
|
172
|
+
};
|
|
173
|
+
const decision = new Promise((resolve, reject) => {
|
|
174
|
+
const abort = () => reject(interaction.signal.reason);
|
|
175
|
+
entry.resolve = (value) => {
|
|
176
|
+
if (entry.decision !== undefined) return;
|
|
177
|
+
entry.decision = value;
|
|
178
|
+
interaction.signal.removeEventListener("abort", abort);
|
|
179
|
+
resolve(value);
|
|
180
|
+
};
|
|
181
|
+
if (interaction.signal.aborted) abort();
|
|
182
|
+
else interaction.signal.addEventListener("abort", abort, { once: true });
|
|
183
|
+
});
|
|
184
|
+
pending.set(token, entry);
|
|
185
|
+
const requestId = interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id;
|
|
186
|
+
const permissionKey = interaction.type === "permission" && requestId ? `${interaction.sessionId}:${requestId}` : null;
|
|
187
|
+
if (permissionKey) permissionRequests.set(permissionKey, entry);
|
|
188
|
+
const conversationKey = context.thread.id;
|
|
189
|
+
const previous = tails.get(conversationKey) ?? Promise.resolve();
|
|
190
|
+
let release;
|
|
191
|
+
const tail = new Promise((resolve) => { release = resolve; });
|
|
192
|
+
tails.set(conversationKey, tail);
|
|
193
|
+
try {
|
|
194
|
+
await previous;
|
|
195
|
+
if (entry.decision === undefined) {
|
|
196
|
+
entry.message = await postInteraction(context.thread, entry);
|
|
197
|
+
if (interaction.signal.aborted) throw interaction.signal.reason;
|
|
198
|
+
}
|
|
199
|
+
const result = await decision;
|
|
200
|
+
await submit(entry, result);
|
|
201
|
+
return result;
|
|
202
|
+
} finally {
|
|
203
|
+
pending.delete(token);
|
|
204
|
+
if (permissionKey) permissionRequests.delete(permissionKey);
|
|
205
|
+
release();
|
|
206
|
+
if (tails.get(conversationKey) === tail) tails.delete(conversationKey);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function onPermissionReplied({ sessionId, requestId, reply }) {
|
|
211
|
+
const entry = permissionRequests.get(`${sessionId}:${requestId}`);
|
|
212
|
+
entry?.resolve?.(reply === "reject" ? { type: "reject" } : { type: "reply", reply });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function onPermissionsReconciled({ sessionId, requestIds }) {
|
|
216
|
+
for (const entry of permissionRequests.values()) {
|
|
217
|
+
if (entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function close() {
|
|
222
|
+
const entries = [...pending.values()];
|
|
223
|
+
for (const entry of entries) entry.resolve?.({ type: "stopped" });
|
|
224
|
+
await Promise.all(entries.map((entry) => submit(entry, { type: "stopped" })));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function onAction(event) {
|
|
228
|
+
const token = interactionToken(event);
|
|
229
|
+
const entry = pending.get(token);
|
|
230
|
+
if (!entry) return;
|
|
231
|
+
if (event.actionId?.startsWith("pipa_dismiss_")) {
|
|
232
|
+
entry.resolve?.({ type: "stop" });
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (entry.type === "permission") {
|
|
236
|
+
const reply = String(event.value ?? "").split(".")[1];
|
|
237
|
+
if (!["once", "always", "reject"].includes(reply)) return;
|
|
238
|
+
const selectedBy = displayName(event.user?.fullName ?? event.user?.userName);
|
|
239
|
+
entry.resolve?.(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (event.actionId?.startsWith("pipa_custom_")) {
|
|
243
|
+
await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: token, title: "Custom answer", submitLabel: "Submit", children: [TextInput({ id: "answer", label: "Answer" })] }));
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (entry.type !== "question") return;
|
|
247
|
+
if (event.actionId?.startsWith("pipa_select_")) {
|
|
248
|
+
const answers = selectedAnswers(event);
|
|
249
|
+
if (!answers.length) return;
|
|
250
|
+
entry.answers[entry.questionIndex] = answers;
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (event.actionId?.startsWith("pipa_submit_")) {
|
|
254
|
+
if (!entry.answers[entry.questionIndex]?.length) return;
|
|
255
|
+
advance(entry, event.user);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function onCustomAnswer(event) {
|
|
261
|
+
const entry = pending.get(event.privateMetadata);
|
|
262
|
+
if (!entry) return;
|
|
263
|
+
const answer = event.values?.answer?.trim();
|
|
264
|
+
if (!answer) return { action: "errors", errors: { answer: "Enter an answer." } };
|
|
265
|
+
entry.answers[entry.questionIndex] = [answer];
|
|
266
|
+
advance(entry, event.user);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function advance(entry, user) {
|
|
270
|
+
if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
|
|
271
|
+
const selectedBy = displayName(user?.fullName ?? user?.userName);
|
|
272
|
+
entry.resolve?.({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
|
|
273
|
+
}
|
|
274
|
+
else entry.message?.edit();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return { onInteraction, onPermissionReplied, onPermissionsReconciled, onAction, onCustomAnswer, close };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function submit(entry, decision) {
|
|
281
|
+
if (entry.submitted) return;
|
|
282
|
+
entry.submitted = true;
|
|
283
|
+
if (decision?.type === "cancelled" || decision?.type === "stopped") {
|
|
284
|
+
await entry.message?.delete?.();
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
await entry.message?.edit(decision);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function renderSubmitted(entry, decision) {
|
|
291
|
+
let content = "Answered.";
|
|
292
|
+
let title = entry.type === "permission" ? "Permission requested" : (entry.request.questions?.[0]?.header || "Question");
|
|
293
|
+
if (decision?.type === "stop") content = "Dismissed.";
|
|
294
|
+
else if (entry.type === "permission") ({ title, content } = permissionOutcome(entry.request, decision));
|
|
295
|
+
else {
|
|
296
|
+
const answers = decision?.answers?.flat().filter(Boolean) ?? [];
|
|
297
|
+
content = `${decision?.selectedBy ? `${decision.selectedBy} selected` : "Selected"}: ${answers.map((answer) => `“${answer}”`).join(", ")}.`;
|
|
298
|
+
}
|
|
299
|
+
return { title, content };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function postInteraction(thread, entry) {
|
|
303
|
+
const [, channel, threadTs] = thread.id.split(":");
|
|
304
|
+
const client = thread.adapter?.webClient;
|
|
305
|
+
if (!client || !channel || !threadTs) throw new Error("Slack interaction context is unavailable.");
|
|
306
|
+
const message = await client.chat.postMessage({
|
|
307
|
+
channel,
|
|
308
|
+
thread_ts: threadTs,
|
|
309
|
+
text: interactionFallback(entry),
|
|
310
|
+
blocks: renderSlackInteraction(entry),
|
|
311
|
+
});
|
|
312
|
+
return {
|
|
313
|
+
edit: (decision) => client.chat.update({
|
|
314
|
+
channel,
|
|
315
|
+
ts: message.ts,
|
|
316
|
+
text: decision ? submittedText(entry, decision) : interactionFallback(entry),
|
|
317
|
+
blocks: decision ? renderSlackSubmitted(entry, decision) : renderSlackInteraction(entry),
|
|
318
|
+
}),
|
|
319
|
+
delete: () => client.chat.delete({ channel, ts: message.ts }),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function renderSlackInteraction(entry) {
|
|
324
|
+
if (entry.type === "permission") {
|
|
325
|
+
const resources = entry.request.patterns ?? entry.request.resources ?? [];
|
|
326
|
+
return [
|
|
327
|
+
slackHeader("Permission requested"),
|
|
328
|
+
slackText(permissionDetail(entry.request, resources)),
|
|
329
|
+
slackActions([
|
|
330
|
+
slackButton(`pipa_permission_once_${entry.token}`, "Allow once", `${entry.token}.once`, "primary"),
|
|
331
|
+
slackButton(`pipa_permission_always_${entry.token}`, "Always allow", `${entry.token}.always`),
|
|
332
|
+
slackButton(`pipa_permission_reject_${entry.token}`, "Reject", `${entry.token}.reject`, "danger"),
|
|
333
|
+
]),
|
|
334
|
+
];
|
|
335
|
+
}
|
|
336
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
337
|
+
const options = (question.options ?? []).map((option) => ({
|
|
338
|
+
text: { type: "plain_text", text: option.label ?? option },
|
|
339
|
+
value: `${entry.token}.${option.label ?? option}`,
|
|
340
|
+
}));
|
|
341
|
+
const selector = options.length && (question.multiple
|
|
342
|
+
? { type: "checkboxes", action_id: `pipa_select_${entry.token}`, options }
|
|
343
|
+
: { type: "radio_buttons", action_id: `pipa_select_${entry.token}`, options });
|
|
344
|
+
const actions = [
|
|
345
|
+
...(question.custom || !options.length ? [slackButton(`pipa_custom_${entry.token}`, "Custom answer", entry.token)] : []),
|
|
346
|
+
...(options.length ? [slackButton(`pipa_submit_${entry.token}`, "Submit", entry.token, "primary")] : []),
|
|
347
|
+
slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
|
|
348
|
+
];
|
|
349
|
+
return [slackHeader(question.header || "Question"), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [slackActions([selector])] : []), slackActions(actions)];
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function renderSlackSubmitted(entry, decision) {
|
|
353
|
+
const submitted = renderSubmitted(entry, decision);
|
|
354
|
+
return [slackHeader(submitted.title), slackText(submitted.content)];
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function submittedText(entry, decision) {
|
|
358
|
+
return renderSubmitted(entry, decision).content;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function permissionDetail(request, resources) {
|
|
362
|
+
const input = request.tool?.input;
|
|
363
|
+
const tool = request.tool?.name ? [`Tool: ${request.tool.name}`] : [];
|
|
364
|
+
if (request.tool?.name === "read" && input?.filePath) tool.push(`File: ${input.filePath}`);
|
|
365
|
+
if (request.tool?.name === "glob" && input?.pattern) tool.push(`Pattern: ${input.pattern}`);
|
|
366
|
+
return [`Action: ${request.permission ?? request.action ?? "Unknown"}`, ...tool, ...(resources.length ? ["Resources:", ...resources.map((resource) => `- ${resource}`)] : [])].join("\n");
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function permissionOutcome(request, decision) {
|
|
370
|
+
const action = permissionAction(request);
|
|
371
|
+
const detail = permissionDetail(request, request.patterns ?? request.resources ?? []);
|
|
372
|
+
const actor = decision?.selectedBy ? ` by ${decision.selectedBy}` : "";
|
|
373
|
+
if (decision?.type === "reject") return {
|
|
374
|
+
title: "Permission rejected",
|
|
375
|
+
content: `Rejected${actor}. Blocked ${action}. OpenCode may cancel related requests from the same batch.\n\n${detail}`,
|
|
376
|
+
};
|
|
377
|
+
if (decision?.reply === "always") return {
|
|
378
|
+
title: "Permission allowed",
|
|
379
|
+
content: `Allowed${actor} in this workspace. Pipa will not ask again for matching access.\n\n${detail}`,
|
|
380
|
+
};
|
|
381
|
+
return {
|
|
382
|
+
title: "Permission allowed once",
|
|
383
|
+
content: `Allowed${actor} for this request. Pipa will ask again for later protected access.\n\n${detail}`,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function permissionAction(request) {
|
|
388
|
+
const input = request.tool?.input;
|
|
389
|
+
if (request.tool?.name === "read" && input?.filePath) return `\`read ${input.filePath}\``;
|
|
390
|
+
if (request.tool?.name === "glob" && input?.pattern) return `\`glob ${input.pattern}\``;
|
|
391
|
+
return `the ${request.permission ?? request.action ?? "requested"} action`;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function interactionFallback(entry) {
|
|
395
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
396
|
+
return question.question ?? question.header ?? "Action required";
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function slackHeader(text) {
|
|
400
|
+
return { type: "header", text: { type: "plain_text", text } };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function slackText(text) {
|
|
404
|
+
return { type: "section", text: { type: "mrkdwn", text } };
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function slackActions(elements) {
|
|
408
|
+
return { type: "actions", elements };
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function slackButton(actionId, text, value, style) {
|
|
412
|
+
return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function selectedAnswers(event) {
|
|
416
|
+
const action = event.raw?.actions?.find((item) => item.action_id === event.actionId);
|
|
417
|
+
const values = action?.selected_options?.map((option) => option.value) ?? [event.value];
|
|
418
|
+
return values.filter(Boolean).map((value) => String(value).split(".").slice(1).join(".")).filter(Boolean);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function interactionToken(event) {
|
|
422
|
+
const value = String(event.value ?? "").split(".")[0];
|
|
423
|
+
return value || event.actionId?.split("_").at(-1) || "";
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function displayName(value) {
|
|
427
|
+
const name = String(value ?? "").trim();
|
|
428
|
+
return name ? name[0].toUpperCase() + name.slice(1) : "";
|
|
429
|
+
}
|
|
430
|
+
|
|
130
431
|
export function createConversationRunner({ sessionStore, runTurn }) {
|
|
131
432
|
const tails = new Map();
|
|
132
433
|
let closed = false;
|
|
434
|
+
let closeReason;
|
|
133
435
|
|
|
134
436
|
function enqueue(conversationKey, input) {
|
|
135
|
-
if (closed) return Promise.
|
|
437
|
+
if (closed && input.deliverFailure) return Promise.resolve(input.deliverFailure(closeReason)).then(() => ({ error: closeReason }));
|
|
438
|
+
if (closed) return Promise.reject(closeReason);
|
|
136
439
|
const previous = tails.get(conversationKey) ?? Promise.resolve();
|
|
137
440
|
const current = previous.catch(() => undefined).then(async () => {
|
|
138
|
-
if (closed) throw new Error("Pipa is shutting down.");
|
|
139
441
|
const { deliver, deliverFailure, ...turn } = input;
|
|
140
442
|
let result;
|
|
141
443
|
try {
|
|
444
|
+
if (closed) throw closeReason;
|
|
142
445
|
result = await runTurn({ ...turn, sessionId: sessionStore.get(conversationKey) });
|
|
143
446
|
if (result.sessionId) await sessionStore.set(conversationKey, result.sessionId);
|
|
144
447
|
} catch (error) {
|
|
@@ -161,7 +464,7 @@ export function createConversationRunner({ sessionStore, runTurn }) {
|
|
|
161
464
|
|
|
162
465
|
return {
|
|
163
466
|
enqueue,
|
|
164
|
-
close() { closed = true; },
|
|
467
|
+
close(reason = new PipaStoppedError()) { closed = true; closeReason ??= reason; },
|
|
165
468
|
drain: () => Promise.all([...tails.values()]),
|
|
166
469
|
};
|
|
167
470
|
}
|
|
@@ -256,7 +559,7 @@ async function react(thread, message, emoji) {
|
|
|
256
559
|
async function finishReaction(thread, message, emoji) {
|
|
257
560
|
if (!message.id) return;
|
|
258
561
|
await thread.adapter.removeReaction(thread.id, message.id, "eyes").catch(() => undefined);
|
|
259
|
-
await react(thread, message, emoji);
|
|
562
|
+
if (emoji) await react(thread, message, emoji);
|
|
260
563
|
}
|
|
261
564
|
|
|
262
565
|
async function withTimeout(promise, timeoutMs, message) {
|
package/src/opencode.mjs
CHANGED
|
@@ -14,6 +14,12 @@ const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
|
|
|
14
14
|
|
|
15
15
|
export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
|
|
16
16
|
|
|
17
|
+
export class PipaStoppedError extends Error {
|
|
18
|
+
constructor(message = "Pipa is shutting down.") {
|
|
19
|
+
super(message);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
17
23
|
export function cleanChildEnvironment(environment = process.env) {
|
|
18
24
|
return Object.fromEntries(Object.entries(environment).filter(([key]) => !SECRET_ENV_KEYS.has(key.toUpperCase())));
|
|
19
25
|
}
|
|
@@ -75,9 +81,9 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
75
81
|
const pollIntervalMs = options.pollIntervalMs ?? 1_000;
|
|
76
82
|
const useDataUrls = !isLoopbackUrl(baseUrl);
|
|
77
83
|
const active = new Set();
|
|
78
|
-
let
|
|
84
|
+
let stopReason;
|
|
79
85
|
|
|
80
|
-
async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200]) {
|
|
86
|
+
async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
|
|
81
87
|
const url = serverUrl(baseUrl, pathname, workingDirectory);
|
|
82
88
|
let response;
|
|
83
89
|
try {
|
|
@@ -92,7 +98,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
92
98
|
});
|
|
93
99
|
} catch (error) {
|
|
94
100
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
95
|
-
if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
101
|
+
if (reportFatal && isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
96
102
|
throw error;
|
|
97
103
|
}
|
|
98
104
|
let text;
|
|
@@ -100,7 +106,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
100
106
|
text = await response.text();
|
|
101
107
|
} catch (error) {
|
|
102
108
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
103
|
-
if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
109
|
+
if (reportFatal && isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
104
110
|
throw error;
|
|
105
111
|
}
|
|
106
112
|
if (!acceptedStatuses.includes(response.status)) throw new OpenCodeRequestError(response.status);
|
|
@@ -112,15 +118,15 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
112
118
|
}
|
|
113
119
|
}
|
|
114
120
|
|
|
115
|
-
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [] }) {
|
|
121
|
+
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [], onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
|
|
116
122
|
if (!prompt?.trim()) throw new Error("A prompt is required.");
|
|
117
|
-
if (
|
|
123
|
+
if (stopReason) throw stopReason;
|
|
118
124
|
const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
|
|
119
125
|
let turnError;
|
|
120
126
|
|
|
121
127
|
try {
|
|
122
128
|
const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls);
|
|
123
|
-
if (
|
|
129
|
+
if (stopReason) throw stopReason;
|
|
124
130
|
const controller = new AbortController();
|
|
125
131
|
const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
|
|
126
132
|
active.add(controller);
|
|
@@ -148,7 +154,29 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
148
154
|
messages = [];
|
|
149
155
|
}
|
|
150
156
|
|
|
157
|
+
await onSession?.(selectedSessionId);
|
|
158
|
+
|
|
151
159
|
const baseline = new Set(messages.map((message) => message?.info?.id).filter(Boolean));
|
|
160
|
+
let dismissed = false;
|
|
161
|
+
let permissionRejected = false;
|
|
162
|
+
if (onInteraction) {
|
|
163
|
+
const watcher = watchInteractions({
|
|
164
|
+
baseUrl,
|
|
165
|
+
fetchImpl,
|
|
166
|
+
headers,
|
|
167
|
+
requestTimeoutMs,
|
|
168
|
+
sessionId: selectedSessionId,
|
|
169
|
+
workingDirectory,
|
|
170
|
+
controller,
|
|
171
|
+
onInteraction,
|
|
172
|
+
onPermissionReplied,
|
|
173
|
+
onPermissionsReconciled,
|
|
174
|
+
onPermissionRejected: () => { permissionRejected = true; },
|
|
175
|
+
onDismiss: () => { dismissed = true; },
|
|
176
|
+
requestTurn: request,
|
|
177
|
+
});
|
|
178
|
+
await watcher.ready;
|
|
179
|
+
}
|
|
152
180
|
await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
|
|
153
181
|
method: "POST",
|
|
154
182
|
body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment)),
|
|
@@ -161,8 +189,10 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
161
189
|
]);
|
|
162
190
|
const finalMessage = latestAssistantMessage(currentMessages, baseline);
|
|
163
191
|
const status = statuses?.[selectedSessionId]?.type;
|
|
192
|
+
if (dismissed && status !== "busy" && status !== "retry") return { text: "", sessionId: selectedSessionId };
|
|
164
193
|
if (["error", "failed", "cancelled"].includes(status) || finalMessage?.error) throw new Error("OpenCode failed to complete the turn.");
|
|
165
194
|
if (finalMessage && (status === "idle" || (!status && finalMessage.completed))) {
|
|
195
|
+
if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
|
|
166
196
|
if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
|
|
167
197
|
return { text: finalMessage.text, sessionId: selectedSessionId };
|
|
168
198
|
}
|
|
@@ -175,7 +205,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
175
205
|
}
|
|
176
206
|
} catch (error) {
|
|
177
207
|
turnError = error;
|
|
178
|
-
if (
|
|
208
|
+
if (stopReason) throw stopReason;
|
|
179
209
|
throw error;
|
|
180
210
|
} finally {
|
|
181
211
|
if (temporaryDirectory) {
|
|
@@ -191,9 +221,9 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
191
221
|
|
|
192
222
|
return {
|
|
193
223
|
runTurn,
|
|
194
|
-
stopAll() {
|
|
195
|
-
|
|
196
|
-
for (const controller of active) controller.abort(
|
|
224
|
+
stopAll(reason = new PipaStoppedError()) {
|
|
225
|
+
stopReason ??= reason;
|
|
226
|
+
for (const controller of active) controller.abort(stopReason);
|
|
197
227
|
},
|
|
198
228
|
};
|
|
199
229
|
}
|
|
@@ -294,7 +324,7 @@ function promptBody(prompt, files, contextEnvironment) {
|
|
|
294
324
|
const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
|
|
295
325
|
return {
|
|
296
326
|
parts,
|
|
297
|
-
...(context.length ? { system: `
|
|
327
|
+
...(context.length ? { system: `Slack context for this turn (provided here, not as shell environment variables):\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}` } : {}),
|
|
298
328
|
};
|
|
299
329
|
}
|
|
300
330
|
|
|
@@ -453,6 +483,188 @@ function delay(delayMs, signal) {
|
|
|
453
483
|
});
|
|
454
484
|
}
|
|
455
485
|
|
|
486
|
+
function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sessionId, workingDirectory, controller, onInteraction, onPermissionReplied, onPermissionsReconciled, onPermissionRejected, onDismiss, requestTurn }) {
|
|
487
|
+
const seenIds = new Set();
|
|
488
|
+
const messages = new Map();
|
|
489
|
+
const parents = new Map();
|
|
490
|
+
const interactionSessionIds = new Set([sessionId]);
|
|
491
|
+
let resolveReady;
|
|
492
|
+
let rejectReady;
|
|
493
|
+
let subscribed = false;
|
|
494
|
+
const ready = new Promise((resolve, reject) => {
|
|
495
|
+
resolveReady = resolve;
|
|
496
|
+
rejectReady = reject;
|
|
497
|
+
});
|
|
498
|
+
const dispatch = async (event) => {
|
|
499
|
+
const type = event.type === "question.asked" ? "question" : event.type === "permission.asked" ? "permission" : null;
|
|
500
|
+
const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
|
|
501
|
+
const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
|
|
502
|
+
const requestId = properties?.requestID ?? properties?.requestId ?? properties?.id;
|
|
503
|
+
if (!type || (interactionSessionId !== sessionId && !await belongsToSession(interactionSessionId)) || !requestId || seenIds.has(`${type}:${requestId}`)) return;
|
|
504
|
+
seenIds.add(`${type}:${requestId}`);
|
|
505
|
+
const request = type === "permission" ? await hydratePermission(properties, interactionSessionId) : properties;
|
|
506
|
+
void settleInteraction({ type, requestId, sessionId: interactionSessionId, request, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn });
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
const belongsToSession = async (candidate) => {
|
|
510
|
+
const original = candidate;
|
|
511
|
+
const visited = new Set();
|
|
512
|
+
while (candidate && !visited.has(candidate)) {
|
|
513
|
+
if (candidate === sessionId) {
|
|
514
|
+
interactionSessionIds.add(original);
|
|
515
|
+
return true;
|
|
516
|
+
}
|
|
517
|
+
visited.add(candidate);
|
|
518
|
+
if (!parents.has(candidate)) parents.set(candidate, requestTurn(`/session/${encodeURIComponent(candidate)}`, { method: "GET" }, workingDirectory, controller)
|
|
519
|
+
.then((session) => session?.parentID));
|
|
520
|
+
candidate = await parents.get(candidate);
|
|
521
|
+
}
|
|
522
|
+
return false;
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
const hydratePermission = async (permission, interactionSessionId) => {
|
|
526
|
+
const tool = permission.tool;
|
|
527
|
+
if (!tool?.messageID || !tool.callID) return permission;
|
|
528
|
+
if (!messages.has(tool.messageID)) {
|
|
529
|
+
messages.set(tool.messageID, requestTurn(`/session/${encodeURIComponent(interactionSessionId)}/message?limit=100`, { method: "GET" }, workingDirectory, controller)
|
|
530
|
+
.then((items) => items.flatMap((message) => message.info?.id === tool.messageID ? message.parts ?? [] : [])));
|
|
531
|
+
}
|
|
532
|
+
const part = (await messages.get(tool.messageID)).find((item) => item.callID === tool.callID);
|
|
533
|
+
return part ? { ...permission, tool: { ...tool, name: part.tool, input: part.state?.input } } : permission;
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
const reconcile = async () => {
|
|
537
|
+
const permissions = await requestTurn("/permission", { method: "GET" }, workingDirectory, controller);
|
|
538
|
+
const pending = (await Promise.all((permissions ?? []).map(async (permission) => {
|
|
539
|
+
return await belongsToSession(permission?.sessionID) ? permission : null;
|
|
540
|
+
}))).filter(Boolean);
|
|
541
|
+
await Promise.all(pending.map((permission) => dispatch({ type: "permission.asked", properties: permission })));
|
|
542
|
+
for (const interactionSessionId of interactionSessionIds) {
|
|
543
|
+
const requests = pending.filter((permission) => permission.sessionID === interactionSessionId);
|
|
544
|
+
onPermissionsReconciled?.({ sessionId: interactionSessionId, requestIds: new Set(requests.map((permission) => permission.id)) });
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
void (async () => {
|
|
549
|
+
while (!controller.signal.aborted) {
|
|
550
|
+
try {
|
|
551
|
+
const url = serverUrl(baseUrl, "/event", workingDirectory);
|
|
552
|
+
const response = await fetchImpl(url, {
|
|
553
|
+
headers: { ...headers, accept: "text/event-stream" },
|
|
554
|
+
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(requestTimeoutMs)]),
|
|
555
|
+
});
|
|
556
|
+
if (!response.ok) throw new OpenCodeRequestError(response.status);
|
|
557
|
+
await reconcile();
|
|
558
|
+
if (!subscribed) {
|
|
559
|
+
subscribed = true;
|
|
560
|
+
resolveReady();
|
|
561
|
+
}
|
|
562
|
+
for await (const event of readServerSentEvents(response, controller.signal)) {
|
|
563
|
+
if (controller.signal.aborted) return;
|
|
564
|
+
const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
|
|
565
|
+
const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
|
|
566
|
+
if (event.type === "permission.replied" && (interactionSessionId === sessionId || await belongsToSession(interactionSessionId))) {
|
|
567
|
+
onPermissionReplied?.({ sessionId: interactionSessionId, requestId: properties?.requestID ?? properties?.requestId, reply: properties?.reply });
|
|
568
|
+
await reconcile();
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
await dispatch(event);
|
|
572
|
+
}
|
|
573
|
+
await reconcile();
|
|
574
|
+
await delay(250, controller.signal).catch(() => undefined);
|
|
575
|
+
} catch (error) {
|
|
576
|
+
if (controller.signal.aborted) return;
|
|
577
|
+
if (!subscribed) {
|
|
578
|
+
rejectReady(error);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
await delay(250, controller.signal).catch(() => undefined);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
})();
|
|
585
|
+
return { ready };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
async function settleInteraction({ type, requestId, sessionId, request: interactionRequest, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn }) {
|
|
589
|
+
try {
|
|
590
|
+
const decision = await abortable(Promise.resolve().then(() => onInteraction({
|
|
591
|
+
type,
|
|
592
|
+
sessionId,
|
|
593
|
+
request: interactionRequest,
|
|
594
|
+
signal: controller.signal,
|
|
595
|
+
})), controller.signal);
|
|
596
|
+
if (decision?.type === "cancelled" || decision?.type === "stopped") return;
|
|
597
|
+
if (decision?.type === "stop") {
|
|
598
|
+
onDismiss?.();
|
|
599
|
+
if (type === "question") await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
|
|
600
|
+
else await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply: "reject" }) }, workingDirectory, controller, [200, 204, 404], false);
|
|
601
|
+
await requestTurn(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, workingDirectory, controller, [200, 204], false);
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
if (type === "question" && decision?.type === "answer") {
|
|
605
|
+
await requestTurn(`/question/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ answers: decision.answers }) }, workingDirectory, controller, [200, 204, 404], false);
|
|
606
|
+
} else if (type === "question" && decision?.type === "reject") {
|
|
607
|
+
await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
|
|
608
|
+
} else if (type === "permission" && (decision?.type === "reply" || decision?.type === "reject")) {
|
|
609
|
+
const reply = decision.type === "reject" ? "reject" : decision.reply;
|
|
610
|
+
if (!["once", "always", "reject"].includes(reply)) throw new Error("Invalid OpenCode permission decision.");
|
|
611
|
+
if (reply === "reject") onPermissionRejected?.();
|
|
612
|
+
await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply }) }, workingDirectory, controller, [200, 204, 404], false);
|
|
613
|
+
} else {
|
|
614
|
+
throw new Error(`Invalid OpenCode ${type} decision.`);
|
|
615
|
+
}
|
|
616
|
+
} catch (error) {
|
|
617
|
+
if (!controller.signal.aborted) process.stderr.write(`OpenCode interaction handler error: ${error.message}\n`);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
async function* readServerSentEvents(response, signal) {
|
|
622
|
+
const reader = response.body?.getReader();
|
|
623
|
+
if (!reader) return;
|
|
624
|
+
const abort = () => reader.cancel().catch(() => undefined);
|
|
625
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
626
|
+
const decoder = new TextDecoder();
|
|
627
|
+
let buffer = "";
|
|
628
|
+
try {
|
|
629
|
+
while (true) {
|
|
630
|
+
const { done, value } = await reader.read();
|
|
631
|
+
if (done) break;
|
|
632
|
+
buffer += decoder.decode(value, { stream: true });
|
|
633
|
+
let boundary = buffer.indexOf("\n\n");
|
|
634
|
+
while (boundary >= 0) {
|
|
635
|
+
const chunk = buffer.slice(0, boundary);
|
|
636
|
+
buffer = buffer.slice(boundary + 2);
|
|
637
|
+
const lines = chunk.split("\n");
|
|
638
|
+
const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
|
|
639
|
+
const id = lines.find((line) => line.startsWith("id:"))?.slice(3).trim();
|
|
640
|
+
const type = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
|
|
641
|
+
if (data) {
|
|
642
|
+
try {
|
|
643
|
+
const event = JSON.parse(data);
|
|
644
|
+
yield type ? { id, type, data: event } : event;
|
|
645
|
+
} catch { /* ponytail: skip non-JSON SSE frames */ }
|
|
646
|
+
}
|
|
647
|
+
boundary = buffer.indexOf("\n\n");
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
} finally {
|
|
651
|
+
signal?.removeEventListener("abort", abort);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function abortable(operation, signal) {
|
|
656
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
657
|
+
return new Promise((resolve, reject) => {
|
|
658
|
+
const settle = (callback, value) => {
|
|
659
|
+
signal.removeEventListener("abort", abort);
|
|
660
|
+
callback(value);
|
|
661
|
+
};
|
|
662
|
+
const abort = () => settle(reject, signal.reason);
|
|
663
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
664
|
+
Promise.resolve(operation).then((value) => settle(resolve, value), (error) => settle(reject, error));
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
|
|
456
668
|
function isNetworkError(error) {
|
|
457
669
|
return error instanceof TypeError || ["ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.cause?.code ?? error?.code);
|
|
458
670
|
}
|
package/src/state.mjs
CHANGED
|
@@ -76,6 +76,19 @@ export async function acquireInstanceLock(file = pipaPaths().lock) {
|
|
|
76
76
|
return () => rm(file, { force: true });
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
+
export async function stopInstance(file = pipaPaths().lock, kill = process.kill) {
|
|
80
|
+
const pid = Number.parseInt(await readFile(file, "utf8").catch(() => ""), 10);
|
|
81
|
+
if (!pid) return null;
|
|
82
|
+
try {
|
|
83
|
+
kill(pid, "SIGTERM");
|
|
84
|
+
return pid;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (error?.code === "ESRCH") await rm(file, { force: true });
|
|
87
|
+
else throw error;
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
79
92
|
export function createManifest(botName) {
|
|
80
93
|
const name = validateBotName(botName);
|
|
81
94
|
const manifest = structuredClone(MANIFEST);
|