@usepipa/pipa 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -20
- package/bin/pipa.mjs +30 -19
- package/package.json +2 -2
- package/src/app.mjs +402 -23
- package/src/opencode.mjs +350 -39
- package/src/state.mjs +14 -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
|
|
|
@@ -33,7 +33,7 @@ npm install --global @usepipa/pipa
|
|
|
33
33
|
pipa init
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
`pipa init` guides you through creating and installing the Slack app and saving its local configuration.
|
|
36
|
+
`pipa init` guides you through creating and installing the Slack app and saving its local configuration. The generated manifest includes `channels:read` and `assistant:write`. If an existing installation has not granted a recommended scope, `pipa init` and `pipa start` print reauthorization guidance but continue running.
|
|
37
37
|
|
|
38
38
|
3. Start Pipa:
|
|
39
39
|
|
|
@@ -41,7 +41,11 @@ pipa init
|
|
|
41
41
|
pipa start
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
-
Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. Pipa starts one OpenCode server bound to `127.0.0.1` on an operating-system-assigned port and reuses it for every Slack turn. Port `0` asks the operating system for an available port; no port configuration is required. Pipa replies in a thread, and follow-up messages in that thread reuse the same OpenCode session without another mention.
|
|
44
|
+
Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. Pipa starts one OpenCode server bound to `127.0.0.1` on an operating-system-assigned port and reuses it for every Slack turn. Port `0` asks the operating system for an available port; no port configuration is required. Pipa replies in a thread, and follow-up messages in that thread reuse the same OpenCode session without another mention. While a queued turn is active, Pipa shows a typing status in its Slack thread.
|
|
45
|
+
|
|
46
|
+
Pipa keeps naturally short answers inline. For deeper work, OpenCode can return a concise summary with suitable generated files, such as documents, spreadsheets, PDFs, or images. Files are read only from a private per-turn directory under `.pipa/artifacts` in the configured working directory, validated, limited to 10 files and 100 MB per file or response, and deleted locally after delivery. If file delivery fails, Pipa retries the declaration-free summary without the files. Attached OpenCode servers on non-loopback hosts use inline text fallback instead of local artifact delivery.
|
|
47
|
+
|
|
48
|
+
Incoming messages can include up to Slack's 10-file limit, with a maximum size of 100 MB per file. Attachments require a text prompt and are copied to a temporary directory only for the duration of the turn.
|
|
45
49
|
|
|
46
50
|
### Access control
|
|
47
51
|
|
|
@@ -67,27 +71,11 @@ export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
|
|
|
67
71
|
pipa start
|
|
68
72
|
```
|
|
69
73
|
|
|
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
74
|
## Commands
|
|
87
75
|
|
|
88
76
|
```text
|
|
89
77
|
pipa init Configure Slack and the local working directory
|
|
90
|
-
pipa start Start the configured
|
|
78
|
+
pipa start Start the configured Slack runtime
|
|
91
79
|
pipa --version Print the installed version
|
|
92
80
|
```
|
|
93
81
|
|
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.1",
|
|
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,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Chat, Modal, TextInput } from "chat";
|
|
2
4
|
import { createSlackAdapter } from "@chat-adapter/slack";
|
|
3
5
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
4
6
|
import { canonicalWorkingDirectory, createManifest, createSessionStore, loadConfig, pipaPaths, saveConfig } from "./state.mjs";
|
|
5
|
-
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
7
|
+
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
6
8
|
|
|
7
9
|
export async function initializePipa(input, options = {}) {
|
|
8
10
|
const paths = options.paths ?? pipaPaths();
|
|
@@ -18,7 +20,8 @@ export async function initializePipa(input, options = {}) {
|
|
|
18
20
|
const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
|
|
19
21
|
if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
|
|
20
22
|
await (options.checkSlackAppToken ?? checkSlackAppToken)(config.slackAppToken);
|
|
21
|
-
await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
23
|
+
const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
24
|
+
warnMissingSlackScopes(slackAuth, options.warn);
|
|
22
25
|
|
|
23
26
|
await saveConfig(config, paths, manifest);
|
|
24
27
|
return { config, manifest, paths };
|
|
@@ -27,7 +30,8 @@ export async function initializePipa(input, options = {}) {
|
|
|
27
30
|
export async function startPipa(options = {}) {
|
|
28
31
|
const paths = options.paths ?? pipaPaths();
|
|
29
32
|
const config = options.config ?? await loadConfig(paths.config);
|
|
30
|
-
await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
33
|
+
const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
34
|
+
warnMissingSlackScopes(slackAuth, options.warn);
|
|
31
35
|
const sessionStore = options.sessionStore ?? await createSessionStore(paths.sessions);
|
|
32
36
|
const state = options.state ?? createMemoryState();
|
|
33
37
|
const chat = options.chat ?? new Chat({
|
|
@@ -50,6 +54,7 @@ export async function startPipa(options = {}) {
|
|
|
50
54
|
let executor;
|
|
51
55
|
try {
|
|
52
56
|
executor = options.executor ?? (options.createExecutor ?? createOpenCodeExecutor)({
|
|
57
|
+
artifactRoot: path.join(config.workingDirectory, ".pipa", "artifacts"),
|
|
53
58
|
baseUrl: server.baseUrl,
|
|
54
59
|
onFatal: server.fail,
|
|
55
60
|
});
|
|
@@ -60,6 +65,9 @@ export async function startPipa(options = {}) {
|
|
|
60
65
|
}
|
|
61
66
|
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
62
67
|
let accepting = true;
|
|
68
|
+
const interactions = createPendingInteractions();
|
|
69
|
+
chat.onAction?.(interactions.onAction);
|
|
70
|
+
chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
|
|
63
71
|
|
|
64
72
|
const handle = async (thread, message, subscribe) => {
|
|
65
73
|
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
|
|
@@ -75,23 +83,31 @@ export async function startPipa(options = {}) {
|
|
|
75
83
|
|
|
76
84
|
await react(thread, message, "eyes");
|
|
77
85
|
try {
|
|
86
|
+
const interactionContext = { thread };
|
|
78
87
|
const result = await runner.enqueue(thread.id, {
|
|
79
88
|
prompt,
|
|
80
89
|
attachments,
|
|
81
90
|
workingDirectory: config.workingDirectory,
|
|
82
91
|
contextEnvironment: slackContext(thread, message),
|
|
83
|
-
|
|
84
|
-
|
|
92
|
+
onSession: () => undefined,
|
|
93
|
+
onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
|
|
94
|
+
onPermissionReplied: interactions.onPermissionReplied,
|
|
95
|
+
onPermissionsReconciled: interactions.onPermissionsReconciled,
|
|
96
|
+
startTyping: () => thread.startTyping("Working on it..."),
|
|
97
|
+
deliver: (result) => postResult(thread, result),
|
|
98
|
+
deliverFailure: (error) => thread.post(error instanceof PipaStoppedError
|
|
99
|
+
? `${config.botName} stopped before finishing this request.`
|
|
100
|
+
: `${config.botName} failed: ${safeError(error)}`),
|
|
85
101
|
});
|
|
86
|
-
await finishReaction(thread, message, result.error ? "warning" : "white_check_mark");
|
|
102
|
+
await finishReaction(thread, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
|
|
87
103
|
} catch (error) {
|
|
88
104
|
await finishReaction(thread, message, "warning");
|
|
89
105
|
process.stderr.write("Pipa could not complete or deliver a Slack turn.\n");
|
|
90
106
|
}
|
|
91
107
|
};
|
|
92
108
|
|
|
93
|
-
chat.onNewMention((thread, message) => handle(thread, message, true));
|
|
94
|
-
chat.onSubscribedMessage((thread, message) => handle(thread, message, false));
|
|
109
|
+
chat.onNewMention((thread, message) => { void handle(thread, message, true); });
|
|
110
|
+
chat.onSubscribedMessage((thread, message) => { void handle(thread, message, false); });
|
|
95
111
|
try {
|
|
96
112
|
await state.connect();
|
|
97
113
|
for (const conversationKey of sessionStore.keys()) {
|
|
@@ -99,6 +115,7 @@ export async function startPipa(options = {}) {
|
|
|
99
115
|
}
|
|
100
116
|
await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
|
|
101
117
|
} catch (error) {
|
|
118
|
+
await interactions.close();
|
|
102
119
|
executor.stopAll();
|
|
103
120
|
await withTimeout(chat.shutdown(), options.shutdownTimeoutMs ?? 15_000, "Slack shutdown timed out.").catch(() => undefined);
|
|
104
121
|
server?.stop();
|
|
@@ -106,13 +123,27 @@ export async function startPipa(options = {}) {
|
|
|
106
123
|
throw error;
|
|
107
124
|
}
|
|
108
125
|
|
|
126
|
+
const stop = (reason = new PipaStoppedError()) => {
|
|
127
|
+
if (!accepting) return;
|
|
128
|
+
accepting = false;
|
|
129
|
+
runner.close(reason);
|
|
130
|
+
executor.stopAll(reason);
|
|
131
|
+
};
|
|
132
|
+
|
|
109
133
|
return {
|
|
110
134
|
server: server ? { baseUrl: server.baseUrl, owned: server.owned } : null,
|
|
111
|
-
|
|
135
|
+
async wait() {
|
|
136
|
+
try {
|
|
137
|
+
return await (server?.wait() ?? new Promise(() => undefined));
|
|
138
|
+
} catch (error) {
|
|
139
|
+
stop(error);
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
stop: () => stop(),
|
|
112
144
|
async shutdown() {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
executor.stopAll();
|
|
145
|
+
stop();
|
|
146
|
+
await interactions.close();
|
|
116
147
|
try {
|
|
117
148
|
await withTimeout((async () => {
|
|
118
149
|
await runner.drain();
|
|
@@ -127,18 +158,298 @@ export async function startPipa(options = {}) {
|
|
|
127
158
|
};
|
|
128
159
|
}
|
|
129
160
|
|
|
161
|
+
function createPendingInteractions() {
|
|
162
|
+
const pending = new Map();
|
|
163
|
+
const permissionRequests = new Map();
|
|
164
|
+
const tails = new Map();
|
|
165
|
+
|
|
166
|
+
async function onInteraction(context, interaction) {
|
|
167
|
+
const token = randomUUID().replaceAll("-", "");
|
|
168
|
+
const entry = {
|
|
169
|
+
token,
|
|
170
|
+
type: interaction.type,
|
|
171
|
+
request: interaction.request,
|
|
172
|
+
sessionId: interaction.sessionId,
|
|
173
|
+
requestId: interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id,
|
|
174
|
+
questionIndex: 0,
|
|
175
|
+
answers: [],
|
|
176
|
+
resolve: null,
|
|
177
|
+
};
|
|
178
|
+
const decision = new Promise((resolve, reject) => {
|
|
179
|
+
const abort = () => reject(interaction.signal.reason);
|
|
180
|
+
entry.resolve = (value) => {
|
|
181
|
+
if (entry.decision !== undefined) return;
|
|
182
|
+
entry.decision = value;
|
|
183
|
+
interaction.signal.removeEventListener("abort", abort);
|
|
184
|
+
resolve(value);
|
|
185
|
+
};
|
|
186
|
+
if (interaction.signal.aborted) abort();
|
|
187
|
+
else interaction.signal.addEventListener("abort", abort, { once: true });
|
|
188
|
+
});
|
|
189
|
+
pending.set(token, entry);
|
|
190
|
+
const requestId = interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id;
|
|
191
|
+
const permissionKey = interaction.type === "permission" && requestId ? `${interaction.sessionId}:${requestId}` : null;
|
|
192
|
+
if (permissionKey) permissionRequests.set(permissionKey, entry);
|
|
193
|
+
const conversationKey = context.thread.id;
|
|
194
|
+
const previous = tails.get(conversationKey) ?? Promise.resolve();
|
|
195
|
+
let release;
|
|
196
|
+
const tail = new Promise((resolve) => { release = resolve; });
|
|
197
|
+
tails.set(conversationKey, tail);
|
|
198
|
+
try {
|
|
199
|
+
await previous;
|
|
200
|
+
if (entry.decision === undefined) {
|
|
201
|
+
entry.message = await postInteraction(context.thread, entry);
|
|
202
|
+
if (interaction.signal.aborted) throw interaction.signal.reason;
|
|
203
|
+
}
|
|
204
|
+
const result = await decision;
|
|
205
|
+
await submit(entry, result);
|
|
206
|
+
return result;
|
|
207
|
+
} finally {
|
|
208
|
+
pending.delete(token);
|
|
209
|
+
if (permissionKey) permissionRequests.delete(permissionKey);
|
|
210
|
+
release();
|
|
211
|
+
if (tails.get(conversationKey) === tail) tails.delete(conversationKey);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function onPermissionReplied({ sessionId, requestId, reply }) {
|
|
216
|
+
const entry = permissionRequests.get(`${sessionId}:${requestId}`);
|
|
217
|
+
entry?.resolve?.(reply === "reject" ? { type: "reject" } : { type: "reply", reply });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function onPermissionsReconciled({ sessionId, requestIds }) {
|
|
221
|
+
for (const entry of permissionRequests.values()) {
|
|
222
|
+
if (entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function close() {
|
|
227
|
+
const entries = [...pending.values()];
|
|
228
|
+
for (const entry of entries) entry.resolve?.({ type: "stopped" });
|
|
229
|
+
await Promise.all(entries.map((entry) => submit(entry, { type: "stopped" })));
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function onAction(event) {
|
|
233
|
+
const token = interactionToken(event);
|
|
234
|
+
const entry = pending.get(token);
|
|
235
|
+
if (!entry) return;
|
|
236
|
+
if (event.actionId?.startsWith("pipa_dismiss_")) {
|
|
237
|
+
entry.resolve?.({ type: "stop" });
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (entry.type === "permission") {
|
|
241
|
+
const reply = String(event.value ?? "").split(".")[1];
|
|
242
|
+
if (!["once", "always", "reject"].includes(reply)) return;
|
|
243
|
+
const selectedBy = displayName(event.user?.fullName ?? event.user?.userName);
|
|
244
|
+
entry.resolve?.(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (event.actionId?.startsWith("pipa_custom_")) {
|
|
248
|
+
await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: token, title: "Custom answer", submitLabel: "Submit", children: [TextInput({ id: "answer", label: "Answer" })] }));
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (entry.type !== "question") return;
|
|
252
|
+
if (event.actionId?.startsWith("pipa_select_")) {
|
|
253
|
+
const answers = selectedAnswers(event);
|
|
254
|
+
if (!answers.length) return;
|
|
255
|
+
entry.answers[entry.questionIndex] = answers;
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (event.actionId?.startsWith("pipa_submit_")) {
|
|
259
|
+
if (!entry.answers[entry.questionIndex]?.length) return;
|
|
260
|
+
advance(entry, event.user);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function onCustomAnswer(event) {
|
|
266
|
+
const entry = pending.get(event.privateMetadata);
|
|
267
|
+
if (!entry) return;
|
|
268
|
+
const answer = event.values?.answer?.trim();
|
|
269
|
+
if (!answer) return { action: "errors", errors: { answer: "Enter an answer." } };
|
|
270
|
+
entry.answers[entry.questionIndex] = [answer];
|
|
271
|
+
advance(entry, event.user);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function advance(entry, user) {
|
|
275
|
+
if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
|
|
276
|
+
const selectedBy = displayName(user?.fullName ?? user?.userName);
|
|
277
|
+
entry.resolve?.({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
|
|
278
|
+
}
|
|
279
|
+
else entry.message?.edit();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
return { onInteraction, onPermissionReplied, onPermissionsReconciled, onAction, onCustomAnswer, close };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function submit(entry, decision) {
|
|
286
|
+
if (entry.submitted) return;
|
|
287
|
+
entry.submitted = true;
|
|
288
|
+
if (decision?.type === "cancelled" || decision?.type === "stopped") {
|
|
289
|
+
await entry.message?.delete?.();
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
await entry.message?.edit(decision);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function renderSubmitted(entry, decision) {
|
|
296
|
+
let content = "Answered.";
|
|
297
|
+
let title = entry.type === "permission" ? "Permission requested" : (entry.request.questions?.[0]?.header || "Question");
|
|
298
|
+
if (decision?.type === "stop") content = "Dismissed.";
|
|
299
|
+
else if (entry.type === "permission") ({ title, content } = permissionOutcome(entry.request, decision));
|
|
300
|
+
else {
|
|
301
|
+
const answers = decision?.answers?.flat().filter(Boolean) ?? [];
|
|
302
|
+
content = `${decision?.selectedBy ? `${decision.selectedBy} selected` : "Selected"}: ${answers.map((answer) => `“${answer}”`).join(", ")}.`;
|
|
303
|
+
}
|
|
304
|
+
return { title, content };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async function postInteraction(thread, entry) {
|
|
308
|
+
const [, channel, threadTs] = thread.id.split(":");
|
|
309
|
+
const client = thread.adapter?.webClient;
|
|
310
|
+
if (!client || !channel || !threadTs) throw new Error("Slack interaction context is unavailable.");
|
|
311
|
+
const message = await client.chat.postMessage({
|
|
312
|
+
channel,
|
|
313
|
+
thread_ts: threadTs,
|
|
314
|
+
text: interactionFallback(entry),
|
|
315
|
+
blocks: renderSlackInteraction(entry),
|
|
316
|
+
});
|
|
317
|
+
return {
|
|
318
|
+
edit: (decision) => client.chat.update({
|
|
319
|
+
channel,
|
|
320
|
+
ts: message.ts,
|
|
321
|
+
text: decision ? submittedText(entry, decision) : interactionFallback(entry),
|
|
322
|
+
blocks: decision ? renderSlackSubmitted(entry, decision) : renderSlackInteraction(entry),
|
|
323
|
+
}),
|
|
324
|
+
delete: () => client.chat.delete({ channel, ts: message.ts }),
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function renderSlackInteraction(entry) {
|
|
329
|
+
if (entry.type === "permission") {
|
|
330
|
+
const resources = entry.request.patterns ?? entry.request.resources ?? [];
|
|
331
|
+
return [
|
|
332
|
+
slackHeader("Permission requested"),
|
|
333
|
+
slackText(permissionDetail(entry.request, resources)),
|
|
334
|
+
slackActions([
|
|
335
|
+
slackButton(`pipa_permission_once_${entry.token}`, "Allow once", `${entry.token}.once`, "primary"),
|
|
336
|
+
slackButton(`pipa_permission_always_${entry.token}`, "Always allow", `${entry.token}.always`),
|
|
337
|
+
slackButton(`pipa_permission_reject_${entry.token}`, "Reject", `${entry.token}.reject`, "danger"),
|
|
338
|
+
]),
|
|
339
|
+
];
|
|
340
|
+
}
|
|
341
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
342
|
+
const options = (question.options ?? []).map((option) => ({
|
|
343
|
+
text: { type: "plain_text", text: option.label ?? option },
|
|
344
|
+
value: `${entry.token}.${option.label ?? option}`,
|
|
345
|
+
}));
|
|
346
|
+
const selector = options.length && (question.multiple
|
|
347
|
+
? { type: "checkboxes", action_id: `pipa_select_${entry.token}`, options }
|
|
348
|
+
: { type: "radio_buttons", action_id: `pipa_select_${entry.token}`, options });
|
|
349
|
+
const actions = [
|
|
350
|
+
...(question.custom || !options.length ? [slackButton(`pipa_custom_${entry.token}`, "Custom answer", entry.token)] : []),
|
|
351
|
+
...(options.length ? [slackButton(`pipa_submit_${entry.token}`, "Submit", entry.token, "primary")] : []),
|
|
352
|
+
slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
|
|
353
|
+
];
|
|
354
|
+
return [slackHeader(question.header || "Question"), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [slackActions([selector])] : []), slackActions(actions)];
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function renderSlackSubmitted(entry, decision) {
|
|
358
|
+
const submitted = renderSubmitted(entry, decision);
|
|
359
|
+
return [slackHeader(submitted.title), slackText(submitted.content)];
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function submittedText(entry, decision) {
|
|
363
|
+
return renderSubmitted(entry, decision).content;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function permissionDetail(request, resources) {
|
|
367
|
+
const input = request.tool?.input;
|
|
368
|
+
const tool = request.tool?.name ? [`Tool: ${request.tool.name}`] : [];
|
|
369
|
+
if (request.tool?.name === "read" && input?.filePath) tool.push(`File: ${input.filePath}`);
|
|
370
|
+
if (request.tool?.name === "glob" && input?.pattern) tool.push(`Pattern: ${input.pattern}`);
|
|
371
|
+
return [`Action: ${request.permission ?? request.action ?? "Unknown"}`, ...tool, ...(resources.length ? ["Resources:", ...resources.map((resource) => `- ${resource}`)] : [])].join("\n");
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function permissionOutcome(request, decision) {
|
|
375
|
+
const action = permissionAction(request);
|
|
376
|
+
const detail = permissionDetail(request, request.patterns ?? request.resources ?? []);
|
|
377
|
+
const actor = decision?.selectedBy ? ` by ${decision.selectedBy}` : "";
|
|
378
|
+
if (decision?.type === "reject") return {
|
|
379
|
+
title: "Permission rejected",
|
|
380
|
+
content: `Rejected${actor}. Blocked ${action}. OpenCode may cancel related requests from the same batch.\n\n${detail}`,
|
|
381
|
+
};
|
|
382
|
+
if (decision?.reply === "always") return {
|
|
383
|
+
title: "Permission allowed",
|
|
384
|
+
content: `Allowed${actor} in this workspace. Pipa will not ask again for matching access.\n\n${detail}`,
|
|
385
|
+
};
|
|
386
|
+
return {
|
|
387
|
+
title: "Permission allowed once",
|
|
388
|
+
content: `Allowed${actor} for this request. Pipa will ask again for later protected access.\n\n${detail}`,
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function permissionAction(request) {
|
|
393
|
+
const input = request.tool?.input;
|
|
394
|
+
if (request.tool?.name === "read" && input?.filePath) return `\`read ${input.filePath}\``;
|
|
395
|
+
if (request.tool?.name === "glob" && input?.pattern) return `\`glob ${input.pattern}\``;
|
|
396
|
+
return `the ${request.permission ?? request.action ?? "requested"} action`;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function interactionFallback(entry) {
|
|
400
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
401
|
+
return question.question ?? question.header ?? "Action required";
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function slackHeader(text) {
|
|
405
|
+
return { type: "header", text: { type: "plain_text", text } };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function slackText(text) {
|
|
409
|
+
return { type: "section", text: { type: "mrkdwn", text } };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function slackActions(elements) {
|
|
413
|
+
return { type: "actions", elements };
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function slackButton(actionId, text, value, style) {
|
|
417
|
+
return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function selectedAnswers(event) {
|
|
421
|
+
const action = event.raw?.actions?.find((item) => item.action_id === event.actionId);
|
|
422
|
+
const values = action?.selected_options?.map((option) => option.value) ?? [event.value];
|
|
423
|
+
return values.filter(Boolean).map((value) => String(value).split(".").slice(1).join(".")).filter(Boolean);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function interactionToken(event) {
|
|
427
|
+
const value = String(event.value ?? "").split(".")[0];
|
|
428
|
+
return value || event.actionId?.split("_").at(-1) || "";
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function displayName(value) {
|
|
432
|
+
const name = String(value ?? "").trim();
|
|
433
|
+
return name ? name[0].toUpperCase() + name.slice(1) : "";
|
|
434
|
+
}
|
|
435
|
+
|
|
130
436
|
export function createConversationRunner({ sessionStore, runTurn }) {
|
|
131
437
|
const tails = new Map();
|
|
132
438
|
let closed = false;
|
|
439
|
+
let closeReason;
|
|
133
440
|
|
|
134
441
|
function enqueue(conversationKey, input) {
|
|
135
|
-
if (closed) return Promise.
|
|
442
|
+
if (closed && input.deliverFailure) return Promise.resolve(input.deliverFailure(closeReason)).then(() => ({ error: closeReason }));
|
|
443
|
+
if (closed) return Promise.reject(closeReason);
|
|
136
444
|
const previous = tails.get(conversationKey) ?? Promise.resolve();
|
|
137
445
|
const current = previous.catch(() => undefined).then(async () => {
|
|
138
|
-
|
|
139
|
-
const { deliver, deliverFailure, ...turn } = input;
|
|
446
|
+
const { deliver, deliverFailure, startTyping, ...turn } = input;
|
|
140
447
|
let result;
|
|
141
448
|
try {
|
|
449
|
+
if (closed) throw closeReason;
|
|
450
|
+
try {
|
|
451
|
+
Promise.resolve(startTyping?.()).catch(() => undefined);
|
|
452
|
+
} catch {}
|
|
142
453
|
result = await runTurn({ ...turn, sessionId: sessionStore.get(conversationKey) });
|
|
143
454
|
if (result.sessionId) await sessionStore.set(conversationKey, result.sessionId);
|
|
144
455
|
} catch (error) {
|
|
@@ -148,7 +459,7 @@ export function createConversationRunner({ sessionStore, runTurn }) {
|
|
|
148
459
|
}
|
|
149
460
|
throw error;
|
|
150
461
|
}
|
|
151
|
-
if (deliver) await deliver(result
|
|
462
|
+
if (deliver) await deliver(result);
|
|
152
463
|
return result;
|
|
153
464
|
});
|
|
154
465
|
const tail = current.then(() => undefined, () => undefined);
|
|
@@ -161,7 +472,7 @@ export function createConversationRunner({ sessionStore, runTurn }) {
|
|
|
161
472
|
|
|
162
473
|
return {
|
|
163
474
|
enqueue,
|
|
164
|
-
close() { closed = true; },
|
|
475
|
+
close(reason = new PipaStoppedError()) { closed = true; closeReason ??= reason; },
|
|
165
476
|
drain: () => Promise.all([...tails.values()]),
|
|
166
477
|
};
|
|
167
478
|
}
|
|
@@ -175,7 +486,10 @@ export async function checkSlackToken(token, fetchImpl = fetch) {
|
|
|
175
486
|
});
|
|
176
487
|
const result = await response.json();
|
|
177
488
|
if (!response.ok || !result.ok) throw new Error("Slack rejected the bot token.");
|
|
178
|
-
|
|
489
|
+
const headerScopes = response.headers?.get?.("x-oauth-scopes");
|
|
490
|
+
const grantedScopes = normalizeGrantedScopes(typeof headerScopes === "string" ? headerScopes.split(",") : undefined)
|
|
491
|
+
?? normalizeGrantedScopes(result.response_metadata?.scopes);
|
|
492
|
+
return grantedScopes === undefined ? result : { ...result, grantedScopes };
|
|
179
493
|
}
|
|
180
494
|
|
|
181
495
|
export async function checkSlackAppToken(token, fetchImpl = fetch) {
|
|
@@ -227,6 +541,22 @@ function requireToken(value, label, prefix) {
|
|
|
227
541
|
return token;
|
|
228
542
|
}
|
|
229
543
|
|
|
544
|
+
function normalizeGrantedScopes(value) {
|
|
545
|
+
if (Array.isArray(value) && value.every((scope) => typeof scope === "string" && scope.trim())) {
|
|
546
|
+
return [...new Set(value.map((scope) => scope.trim()))];
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`${message}\n`)) {
|
|
551
|
+
if (!Array.isArray(auth?.grantedScopes)) return;
|
|
552
|
+
const missing = ["channels:read", "assistant:write"].filter((scope) => !auth.grantedScopes.includes(scope));
|
|
553
|
+
if (!missing.length) return;
|
|
554
|
+
const scopes = missing.join(", ");
|
|
555
|
+
try {
|
|
556
|
+
warn(`Pipa warning: Slack bot token is missing recommended ${missing.length === 1 ? "scope" : "scopes"} ${scopes}. Add ${missing.length === 1 ? "it" : "them"} and reinstall or reauthorize the Slack app.`);
|
|
557
|
+
} catch {}
|
|
558
|
+
}
|
|
559
|
+
|
|
230
560
|
function safeError(error) {
|
|
231
561
|
const message = error instanceof Error ? error.message : String(error);
|
|
232
562
|
return message.replace(/xox[baprs]-[^\s]+|xapp-[^\s]+/gu, "[redacted]");
|
|
@@ -242,10 +572,59 @@ function slackContext(thread, message) {
|
|
|
242
572
|
};
|
|
243
573
|
}
|
|
244
574
|
|
|
245
|
-
async function
|
|
246
|
-
|
|
247
|
-
|
|
575
|
+
async function postResult(thread, { text, files = [] }) {
|
|
576
|
+
if (files.length) {
|
|
577
|
+
try {
|
|
578
|
+
await thread.post({ markdown: text, files });
|
|
579
|
+
return;
|
|
580
|
+
} catch {
|
|
581
|
+
// A failed adapter call may still have uploaded files, so retry text only.
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
if (!text) return;
|
|
585
|
+
for (const markdown of splitSlackMarkdown(text)) await thread.post({ markdown });
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function splitSlackMarkdown(text, limit = 3500) {
|
|
589
|
+
if (text.length <= limit) return [text];
|
|
590
|
+
const chunks = [];
|
|
591
|
+
let chunk = "";
|
|
592
|
+
let fence = "";
|
|
593
|
+
const append = (line) => {
|
|
594
|
+
const separator = chunk ? "\n" : "";
|
|
595
|
+
const closing = fence ? `\n${fence}` : "";
|
|
596
|
+
if (chunk && chunk.length + separator.length + line.length + closing.length > limit) {
|
|
597
|
+
chunks.push(chunk + closing);
|
|
598
|
+
chunk = fence ? `${fence}\n${line}` : line;
|
|
599
|
+
} else {
|
|
600
|
+
chunk += separator + line;
|
|
601
|
+
}
|
|
602
|
+
const marker = line.match(/^ {0,3}(```+|~~~+)/u)?.[0];
|
|
603
|
+
if (marker) fence = fence ? "" : marker;
|
|
604
|
+
};
|
|
605
|
+
for (const inputLine of text.split("\n")) {
|
|
606
|
+
let line = inputLine;
|
|
607
|
+
const emptyChunkLimit = limit - (fence ? (2 * fence.length) + 2 : 0);
|
|
608
|
+
if (line.length <= emptyChunkLimit) {
|
|
609
|
+
append(line);
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
if (chunk) {
|
|
613
|
+
chunks.push(chunk + (fence ? `\n${fence}` : ""));
|
|
614
|
+
chunk = fence ? `${fence}\n` : "";
|
|
615
|
+
}
|
|
616
|
+
const room = Math.max(1, limit - chunk.length - (fence ? fence.length + 1 : 0));
|
|
617
|
+
while (line.length > room) {
|
|
618
|
+
const boundary = line.slice(0, room + 1).search(/\s+\S*$/u);
|
|
619
|
+
const splitAt = boundary > 0 ? boundary : room;
|
|
620
|
+
chunks.push(chunk + line.slice(0, splitAt) + (fence ? `\n${fence}` : ""));
|
|
621
|
+
line = line.slice(splitAt).replace(/^\s+/u, "");
|
|
622
|
+
chunk = fence ? `${fence}\n` : "";
|
|
623
|
+
}
|
|
624
|
+
chunk += line;
|
|
248
625
|
}
|
|
626
|
+
if (chunk) chunks.push(chunk + (fence ? `\n${fence}` : ""));
|
|
627
|
+
return chunks;
|
|
249
628
|
}
|
|
250
629
|
|
|
251
630
|
async function react(thread, message, emoji) {
|
|
@@ -256,7 +635,7 @@ async function react(thread, message, emoji) {
|
|
|
256
635
|
async function finishReaction(thread, message, emoji) {
|
|
257
636
|
if (!message.id) return;
|
|
258
637
|
await thread.adapter.removeReaction(thread.id, message.id, "eyes").catch(() => undefined);
|
|
259
|
-
await react(thread, message, emoji);
|
|
638
|
+
if (emoji) await react(thread, message, emoji);
|
|
260
639
|
}
|
|
261
640
|
|
|
262
641
|
async function withTimeout(promise, timeoutMs, message) {
|
package/src/opencode.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import crossSpawn from "cross-spawn";
|
|
2
|
-
import {
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { chmod, lstat, mkdir, mkdtemp, open, realpath, rm, writeFile } from "node:fs/promises";
|
|
3
4
|
import os from "node:os";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import { pathToFileURL } from "node:url";
|
|
@@ -13,6 +14,16 @@ const SECRET_ENV_KEYS = new Set([
|
|
|
13
14
|
const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
|
|
14
15
|
|
|
15
16
|
export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
|
|
17
|
+
const ARTIFACT_MARKER = "PIPA_ARTIFACTS:";
|
|
18
|
+
const MAX_ARTIFACT_DECLARATION_BYTES = 8 * 1024;
|
|
19
|
+
const MAX_ARTIFACT_PATH_BYTES = 1024;
|
|
20
|
+
const MAX_ARTIFACT_FILES = 10;
|
|
21
|
+
|
|
22
|
+
export class PipaStoppedError extends Error {
|
|
23
|
+
constructor(message = "Pipa is shutting down.") {
|
|
24
|
+
super(message);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
16
27
|
|
|
17
28
|
export function cleanChildEnvironment(environment = process.env) {
|
|
18
29
|
return Object.fromEntries(Object.entries(environment).filter(([key]) => !SECRET_ENV_KEYS.has(key.toUpperCase())));
|
|
@@ -74,10 +85,12 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
74
85
|
const requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
|
|
75
86
|
const pollIntervalMs = options.pollIntervalMs ?? 1_000;
|
|
76
87
|
const useDataUrls = !isLoopbackUrl(baseUrl);
|
|
88
|
+
const remove = options.rm ?? rm;
|
|
89
|
+
const artifactRoot = options.artifactRoot;
|
|
77
90
|
const active = new Set();
|
|
78
|
-
let
|
|
91
|
+
let stopReason;
|
|
79
92
|
|
|
80
|
-
async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200]) {
|
|
93
|
+
async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
|
|
81
94
|
const url = serverUrl(baseUrl, pathname, workingDirectory);
|
|
82
95
|
let response;
|
|
83
96
|
try {
|
|
@@ -92,7 +105,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
92
105
|
});
|
|
93
106
|
} catch (error) {
|
|
94
107
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
95
|
-
if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
108
|
+
if (reportFatal && isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
96
109
|
throw error;
|
|
97
110
|
}
|
|
98
111
|
let text;
|
|
@@ -100,7 +113,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
100
113
|
text = await response.text();
|
|
101
114
|
} catch (error) {
|
|
102
115
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
103
|
-
if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
116
|
+
if (reportFatal && isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
104
117
|
throw error;
|
|
105
118
|
}
|
|
106
119
|
if (!acceptedStatuses.includes(response.status)) throw new OpenCodeRequestError(response.status);
|
|
@@ -112,20 +125,27 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
112
125
|
}
|
|
113
126
|
}
|
|
114
127
|
|
|
115
|
-
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [] }) {
|
|
128
|
+
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [], onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
|
|
116
129
|
if (!prompt?.trim()) throw new Error("A prompt is required.");
|
|
117
|
-
if (
|
|
130
|
+
if (stopReason) throw stopReason;
|
|
118
131
|
const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
|
|
119
|
-
|
|
132
|
+
const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
|
|
133
|
+
const controller = new AbortController();
|
|
134
|
+
const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
|
|
135
|
+
active.add(controller);
|
|
136
|
+
let artifactDirectory;
|
|
120
137
|
|
|
121
138
|
try {
|
|
122
|
-
const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls);
|
|
123
|
-
if (stopped) throw new Error("Pipa is shutting down.");
|
|
124
|
-
const controller = new AbortController();
|
|
125
|
-
const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
|
|
126
|
-
active.add(controller);
|
|
127
|
-
|
|
128
139
|
try {
|
|
140
|
+
if (slackTurn && !useDataUrls && artifactRoot) {
|
|
141
|
+
try {
|
|
142
|
+
await mkdir(artifactRoot, { recursive: true, mode: 0o700 });
|
|
143
|
+
artifactDirectory = await mkdtemp(path.join(artifactRoot, "turn-"));
|
|
144
|
+
} catch {}
|
|
145
|
+
}
|
|
146
|
+
if (artifactDirectory) await chmod(artifactDirectory, 0o700);
|
|
147
|
+
const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls, controller.signal);
|
|
148
|
+
if (stopReason) throw stopReason;
|
|
129
149
|
let selectedSessionId = sessionId;
|
|
130
150
|
let messages;
|
|
131
151
|
if (selectedSessionId) {
|
|
@@ -148,10 +168,32 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
148
168
|
messages = [];
|
|
149
169
|
}
|
|
150
170
|
|
|
171
|
+
await onSession?.(selectedSessionId);
|
|
172
|
+
|
|
151
173
|
const baseline = new Set(messages.map((message) => message?.info?.id).filter(Boolean));
|
|
174
|
+
let dismissed = false;
|
|
175
|
+
let permissionRejected = false;
|
|
176
|
+
if (onInteraction) {
|
|
177
|
+
const watcher = watchInteractions({
|
|
178
|
+
baseUrl,
|
|
179
|
+
fetchImpl,
|
|
180
|
+
headers,
|
|
181
|
+
requestTimeoutMs,
|
|
182
|
+
sessionId: selectedSessionId,
|
|
183
|
+
workingDirectory,
|
|
184
|
+
controller,
|
|
185
|
+
onInteraction,
|
|
186
|
+
onPermissionReplied,
|
|
187
|
+
onPermissionsReconciled,
|
|
188
|
+
onPermissionRejected: () => { permissionRejected = true; },
|
|
189
|
+
onDismiss: () => { dismissed = true; },
|
|
190
|
+
requestTurn: request,
|
|
191
|
+
});
|
|
192
|
+
await watcher.ready;
|
|
193
|
+
}
|
|
152
194
|
await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
|
|
153
195
|
method: "POST",
|
|
154
|
-
body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment)),
|
|
196
|
+
body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment, artifactDirectory)),
|
|
155
197
|
}, workingDirectory, controller, [204]);
|
|
156
198
|
|
|
157
199
|
while (true) {
|
|
@@ -161,10 +203,18 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
161
203
|
]);
|
|
162
204
|
const finalMessage = latestAssistantMessage(currentMessages, baseline);
|
|
163
205
|
const status = statuses?.[selectedSessionId]?.type;
|
|
206
|
+
if (dismissed && status !== "busy" && status !== "retry") return { text: "", sessionId: selectedSessionId };
|
|
164
207
|
if (["error", "failed", "cancelled"].includes(status) || finalMessage?.error) throw new Error("OpenCode failed to complete the turn.");
|
|
165
208
|
if (finalMessage && (status === "idle" || (!status && finalMessage.completed))) {
|
|
209
|
+
if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
|
|
166
210
|
if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
|
|
167
|
-
|
|
211
|
+
const parsed = slackTurn ? parseArtifactDeclaration(finalMessage.text) : { text: finalMessage.text };
|
|
212
|
+
const artifacts = artifactDirectory && parsed.paths ? await readArtifacts(artifactDirectory, parsed.paths, options.onArtifactOpened) : [];
|
|
213
|
+
return {
|
|
214
|
+
text: parsed.text,
|
|
215
|
+
sessionId: selectedSessionId,
|
|
216
|
+
...(artifacts.length ? { files: artifacts } : {}),
|
|
217
|
+
};
|
|
168
218
|
}
|
|
169
219
|
await delay(pollIntervalMs, controller.signal);
|
|
170
220
|
}
|
|
@@ -174,26 +224,31 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
174
224
|
active.delete(controller);
|
|
175
225
|
}
|
|
176
226
|
} catch (error) {
|
|
177
|
-
|
|
178
|
-
if (stopped) throw new Error("Pipa is shutting down.");
|
|
227
|
+
if (stopReason) throw stopReason;
|
|
179
228
|
throw error;
|
|
180
229
|
} finally {
|
|
181
230
|
if (temporaryDirectory) {
|
|
182
231
|
try {
|
|
183
|
-
await
|
|
184
|
-
} catch
|
|
185
|
-
if (!turnError) throw error;
|
|
232
|
+
await remove(temporaryDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
233
|
+
} catch {
|
|
186
234
|
process.stderr.write("Pipa could not remove temporary attachment files.\n");
|
|
187
235
|
}
|
|
188
236
|
}
|
|
237
|
+
if (artifactDirectory) {
|
|
238
|
+
try {
|
|
239
|
+
await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
240
|
+
} catch {
|
|
241
|
+
process.stderr.write("Pipa could not remove temporary artifact files.\n");
|
|
242
|
+
}
|
|
243
|
+
}
|
|
189
244
|
}
|
|
190
245
|
}
|
|
191
246
|
|
|
192
247
|
return {
|
|
193
248
|
runTurn,
|
|
194
|
-
stopAll() {
|
|
195
|
-
|
|
196
|
-
for (const controller of active) controller.abort(
|
|
249
|
+
stopAll(reason = new PipaStoppedError()) {
|
|
250
|
+
stopReason ??= reason;
|
|
251
|
+
for (const controller of active) controller.abort(stopReason);
|
|
197
252
|
},
|
|
198
253
|
};
|
|
199
254
|
}
|
|
@@ -256,24 +311,18 @@ export async function runOpenCodeVersion(options = {}) {
|
|
|
256
311
|
}
|
|
257
312
|
}
|
|
258
313
|
|
|
259
|
-
async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls) {
|
|
314
|
+
async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls, signal) {
|
|
260
315
|
const files = [];
|
|
261
316
|
for (const [index, attachment] of attachments.entries()) {
|
|
262
317
|
let data;
|
|
263
318
|
try {
|
|
264
|
-
data = await fetchAttachment(attachment, timeoutMs);
|
|
319
|
+
data = await fetchAttachment(attachment, timeoutMs, signal);
|
|
265
320
|
} catch {
|
|
266
321
|
throw new Error("Could not read one of the attached files. Please try uploading it again.");
|
|
267
322
|
}
|
|
268
323
|
if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 100 MB or smaller.");
|
|
269
324
|
try {
|
|
270
|
-
const
|
|
271
|
-
.replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "_")
|
|
272
|
-
.replace(/[. ]+$/u, "");
|
|
273
|
-
const filename = Array.from(sanitizedName).reduce(
|
|
274
|
-
(result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result,
|
|
275
|
-
"",
|
|
276
|
-
) || "attachment";
|
|
325
|
+
const filename = sanitizeFilename(path.basename(attachment.name || "attachment"), "attachment");
|
|
277
326
|
const file = path.join(temporaryDirectory, `${index + 1}-${filename}`);
|
|
278
327
|
await writeFile(file, data);
|
|
279
328
|
const mime = attachment.mimeType || "application/octet-stream";
|
|
@@ -289,15 +338,96 @@ async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useD
|
|
|
289
338
|
return files;
|
|
290
339
|
}
|
|
291
340
|
|
|
292
|
-
function promptBody(prompt, files, contextEnvironment) {
|
|
341
|
+
function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
|
|
293
342
|
const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
|
|
294
343
|
const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
|
|
344
|
+
const instructions = [];
|
|
345
|
+
if (context.length) instructions.push(`Slack context for this turn (provided here, not as shell environment variables):\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}`);
|
|
346
|
+
if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
|
|
347
|
+
instructions.push("Keep naturally short answers inline. For deeper work or larger deliverables, keep the Slack response concise and use the most suitable artifact format.");
|
|
348
|
+
if (artifactDirectory) instructions.push(`To attach files, copy up to 10 top-level files (100 MB total) to this private artifact directory: ${artifactDirectory}\nEnd with exactly one final line: ${ARTIFACT_MARKER} [\"report.csv\",\"brief.pdf\"]`);
|
|
349
|
+
}
|
|
295
350
|
return {
|
|
296
351
|
parts,
|
|
297
|
-
...(
|
|
352
|
+
...(instructions.length ? { system: instructions.join("\n\n") } : {}),
|
|
298
353
|
};
|
|
299
354
|
}
|
|
300
355
|
|
|
356
|
+
function parseArtifactDeclaration(text) {
|
|
357
|
+
const lines = text.split(/\r?\n/u);
|
|
358
|
+
const declarations = lines.map((line, index) => line.startsWith(ARTIFACT_MARKER) ? { line, index } : null).filter(Boolean);
|
|
359
|
+
const cleanText = lines.filter((line) => !line.startsWith(ARTIFACT_MARKER)).join("\n").trim();
|
|
360
|
+
const lastNonblank = lines.findLastIndex((line) => line.trim());
|
|
361
|
+
if (declarations.length !== 1 || declarations[0].index !== lastNonblank) return { text: cleanText };
|
|
362
|
+
const declaration = declarations[0].line;
|
|
363
|
+
if (!declaration.startsWith(`${ARTIFACT_MARKER} `) || Buffer.byteLength(declaration) > MAX_ARTIFACT_DECLARATION_BYTES) return { text: cleanText };
|
|
364
|
+
let paths;
|
|
365
|
+
try {
|
|
366
|
+
paths = JSON.parse(declaration.slice(ARTIFACT_MARKER.length + 1));
|
|
367
|
+
} catch {
|
|
368
|
+
return { text: cleanText };
|
|
369
|
+
}
|
|
370
|
+
if (!Array.isArray(paths) || !paths.length || paths.length > MAX_ARTIFACT_FILES || paths.some((item) => typeof item !== "string")) return { text: cleanText };
|
|
371
|
+
if (new Set(paths).size !== paths.length || paths.some((item) => !validArtifactPath(item))) return { text: cleanText };
|
|
372
|
+
return { text: cleanText, paths };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function validArtifactPath(value) {
|
|
376
|
+
if (!value || Buffer.byteLength(value) > MAX_ARTIFACT_PATH_BYTES || value.includes("\0") || value.includes("\\") || path.isAbsolute(value)) return false;
|
|
377
|
+
const parts = value.split("/");
|
|
378
|
+
return parts.length === 1 && parts[0] !== "." && parts[0] !== "..";
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async function readArtifacts(directory, paths, onOpened) {
|
|
382
|
+
const files = [];
|
|
383
|
+
let total = 0;
|
|
384
|
+
try {
|
|
385
|
+
const root = await realpath(directory);
|
|
386
|
+
for (const relativePath of paths) {
|
|
387
|
+
const filename = path.resolve(root, relativePath);
|
|
388
|
+
if (!filename.startsWith(`${root}${path.sep}`)) throw new Error("Artifact path escaped its directory.");
|
|
389
|
+
let current = root;
|
|
390
|
+
for (const part of relativePath.split("/")) {
|
|
391
|
+
current = path.join(current, part);
|
|
392
|
+
if ((await lstat(current)).isSymbolicLink()) throw new Error("Artifact path contains a symbolic link.");
|
|
393
|
+
}
|
|
394
|
+
const handle = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
395
|
+
try {
|
|
396
|
+
const before = await handle.stat({ bigint: true });
|
|
397
|
+
await onOpened?.(filename);
|
|
398
|
+
const size = Number(before.size);
|
|
399
|
+
if (!before.isFile() || size > MAX_ATTACHMENT_BYTES || total + size > MAX_ATTACHMENT_BYTES) throw new Error("Artifact exceeds delivery limits.");
|
|
400
|
+
const data = Buffer.alloc(size + 1);
|
|
401
|
+
let bytesRead = 0;
|
|
402
|
+
while (bytesRead < data.length) {
|
|
403
|
+
const read = await handle.read(data, bytesRead, data.length - bytesRead, bytesRead);
|
|
404
|
+
if (!read.bytesRead) break;
|
|
405
|
+
bytesRead += read.bytesRead;
|
|
406
|
+
}
|
|
407
|
+
const after = await handle.stat({ bigint: true });
|
|
408
|
+
const current = await lstat(filename, { bigint: true });
|
|
409
|
+
if (bytesRead !== size || changedFile(before, after) || current.isSymbolicLink() || current.dev !== before.dev || current.ino !== before.ino) throw new Error("Artifact changed while being read.");
|
|
410
|
+
total += size;
|
|
411
|
+
files.push({ data: data.subarray(0, size), filename: sanitizeFilename(path.basename(relativePath)) });
|
|
412
|
+
} finally {
|
|
413
|
+
await handle.close();
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return files;
|
|
417
|
+
} catch {
|
|
418
|
+
return [];
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function changedFile(before, after) {
|
|
423
|
+
return before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function sanitizeFilename(value, fallback = "artifact") {
|
|
427
|
+
const sanitized = value.replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "_").replace(/[. ]+$/u, "");
|
|
428
|
+
return Array.from(sanitized).reduce((result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result, "") || fallback;
|
|
429
|
+
}
|
|
430
|
+
|
|
301
431
|
function latestAssistantMessage(messages, baseline) {
|
|
302
432
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
303
433
|
const message = messages[index];
|
|
@@ -428,12 +558,11 @@ function serverUrl(baseUrl, pathname, workingDirectory) {
|
|
|
428
558
|
return url;
|
|
429
559
|
}
|
|
430
560
|
|
|
431
|
-
function fetchAttachment(attachment, timeoutMs) {
|
|
432
|
-
let timer;
|
|
561
|
+
function fetchAttachment(attachment, timeoutMs, signal) {
|
|
433
562
|
return Promise.race([
|
|
434
563
|
attachment.fetchData(),
|
|
435
|
-
|
|
436
|
-
])
|
|
564
|
+
delay(timeoutMs, signal).then(() => { throw new Error(`Attachment download timed out after ${timeoutMs}ms.`); }),
|
|
565
|
+
]);
|
|
437
566
|
}
|
|
438
567
|
|
|
439
568
|
function delay(delayMs, signal) {
|
|
@@ -453,6 +582,188 @@ function delay(delayMs, signal) {
|
|
|
453
582
|
});
|
|
454
583
|
}
|
|
455
584
|
|
|
585
|
+
function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sessionId, workingDirectory, controller, onInteraction, onPermissionReplied, onPermissionsReconciled, onPermissionRejected, onDismiss, requestTurn }) {
|
|
586
|
+
const seenIds = new Set();
|
|
587
|
+
const messages = new Map();
|
|
588
|
+
const parents = new Map();
|
|
589
|
+
const interactionSessionIds = new Set([sessionId]);
|
|
590
|
+
let resolveReady;
|
|
591
|
+
let rejectReady;
|
|
592
|
+
let subscribed = false;
|
|
593
|
+
const ready = new Promise((resolve, reject) => {
|
|
594
|
+
resolveReady = resolve;
|
|
595
|
+
rejectReady = reject;
|
|
596
|
+
});
|
|
597
|
+
const dispatch = async (event) => {
|
|
598
|
+
const type = event.type === "question.asked" ? "question" : event.type === "permission.asked" ? "permission" : null;
|
|
599
|
+
const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
|
|
600
|
+
const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
|
|
601
|
+
const requestId = properties?.requestID ?? properties?.requestId ?? properties?.id;
|
|
602
|
+
if (!type || (interactionSessionId !== sessionId && !await belongsToSession(interactionSessionId)) || !requestId || seenIds.has(`${type}:${requestId}`)) return;
|
|
603
|
+
seenIds.add(`${type}:${requestId}`);
|
|
604
|
+
const request = type === "permission" ? await hydratePermission(properties, interactionSessionId) : properties;
|
|
605
|
+
void settleInteraction({ type, requestId, sessionId: interactionSessionId, request, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn });
|
|
606
|
+
};
|
|
607
|
+
|
|
608
|
+
const belongsToSession = async (candidate) => {
|
|
609
|
+
const original = candidate;
|
|
610
|
+
const visited = new Set();
|
|
611
|
+
while (candidate && !visited.has(candidate)) {
|
|
612
|
+
if (candidate === sessionId) {
|
|
613
|
+
interactionSessionIds.add(original);
|
|
614
|
+
return true;
|
|
615
|
+
}
|
|
616
|
+
visited.add(candidate);
|
|
617
|
+
if (!parents.has(candidate)) parents.set(candidate, requestTurn(`/session/${encodeURIComponent(candidate)}`, { method: "GET" }, workingDirectory, controller)
|
|
618
|
+
.then((session) => session?.parentID));
|
|
619
|
+
candidate = await parents.get(candidate);
|
|
620
|
+
}
|
|
621
|
+
return false;
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
const hydratePermission = async (permission, interactionSessionId) => {
|
|
625
|
+
const tool = permission.tool;
|
|
626
|
+
if (!tool?.messageID || !tool.callID) return permission;
|
|
627
|
+
if (!messages.has(tool.messageID)) {
|
|
628
|
+
messages.set(tool.messageID, requestTurn(`/session/${encodeURIComponent(interactionSessionId)}/message?limit=100`, { method: "GET" }, workingDirectory, controller)
|
|
629
|
+
.then((items) => items.flatMap((message) => message.info?.id === tool.messageID ? message.parts ?? [] : [])));
|
|
630
|
+
}
|
|
631
|
+
const part = (await messages.get(tool.messageID)).find((item) => item.callID === tool.callID);
|
|
632
|
+
return part ? { ...permission, tool: { ...tool, name: part.tool, input: part.state?.input } } : permission;
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
const reconcile = async () => {
|
|
636
|
+
const permissions = await requestTurn("/permission", { method: "GET" }, workingDirectory, controller);
|
|
637
|
+
const pending = (await Promise.all((permissions ?? []).map(async (permission) => {
|
|
638
|
+
return await belongsToSession(permission?.sessionID) ? permission : null;
|
|
639
|
+
}))).filter(Boolean);
|
|
640
|
+
await Promise.all(pending.map((permission) => dispatch({ type: "permission.asked", properties: permission })));
|
|
641
|
+
for (const interactionSessionId of interactionSessionIds) {
|
|
642
|
+
const requests = pending.filter((permission) => permission.sessionID === interactionSessionId);
|
|
643
|
+
onPermissionsReconciled?.({ sessionId: interactionSessionId, requestIds: new Set(requests.map((permission) => permission.id)) });
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
void (async () => {
|
|
648
|
+
while (!controller.signal.aborted) {
|
|
649
|
+
try {
|
|
650
|
+
const url = serverUrl(baseUrl, "/event", workingDirectory);
|
|
651
|
+
const response = await fetchImpl(url, {
|
|
652
|
+
headers: { ...headers, accept: "text/event-stream" },
|
|
653
|
+
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(requestTimeoutMs)]),
|
|
654
|
+
});
|
|
655
|
+
if (!response.ok) throw new OpenCodeRequestError(response.status);
|
|
656
|
+
await reconcile();
|
|
657
|
+
if (!subscribed) {
|
|
658
|
+
subscribed = true;
|
|
659
|
+
resolveReady();
|
|
660
|
+
}
|
|
661
|
+
for await (const event of readServerSentEvents(response, controller.signal)) {
|
|
662
|
+
if (controller.signal.aborted) return;
|
|
663
|
+
const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
|
|
664
|
+
const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
|
|
665
|
+
if (event.type === "permission.replied" && (interactionSessionId === sessionId || await belongsToSession(interactionSessionId))) {
|
|
666
|
+
onPermissionReplied?.({ sessionId: interactionSessionId, requestId: properties?.requestID ?? properties?.requestId, reply: properties?.reply });
|
|
667
|
+
await reconcile();
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
await dispatch(event);
|
|
671
|
+
}
|
|
672
|
+
await reconcile();
|
|
673
|
+
await delay(250, controller.signal).catch(() => undefined);
|
|
674
|
+
} catch (error) {
|
|
675
|
+
if (controller.signal.aborted) return;
|
|
676
|
+
if (!subscribed) {
|
|
677
|
+
rejectReady(error);
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
await delay(250, controller.signal).catch(() => undefined);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
})();
|
|
684
|
+
return { ready };
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
async function settleInteraction({ type, requestId, sessionId, request: interactionRequest, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn }) {
|
|
688
|
+
try {
|
|
689
|
+
const decision = await abortable(Promise.resolve().then(() => onInteraction({
|
|
690
|
+
type,
|
|
691
|
+
sessionId,
|
|
692
|
+
request: interactionRequest,
|
|
693
|
+
signal: controller.signal,
|
|
694
|
+
})), controller.signal);
|
|
695
|
+
if (decision?.type === "cancelled" || decision?.type === "stopped") return;
|
|
696
|
+
if (decision?.type === "stop") {
|
|
697
|
+
onDismiss?.();
|
|
698
|
+
if (type === "question") await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
|
|
699
|
+
else await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply: "reject" }) }, workingDirectory, controller, [200, 204, 404], false);
|
|
700
|
+
await requestTurn(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, workingDirectory, controller, [200, 204], false);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
if (type === "question" && decision?.type === "answer") {
|
|
704
|
+
await requestTurn(`/question/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ answers: decision.answers }) }, workingDirectory, controller, [200, 204, 404], false);
|
|
705
|
+
} else if (type === "question" && decision?.type === "reject") {
|
|
706
|
+
await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
|
|
707
|
+
} else if (type === "permission" && (decision?.type === "reply" || decision?.type === "reject")) {
|
|
708
|
+
const reply = decision.type === "reject" ? "reject" : decision.reply;
|
|
709
|
+
if (!["once", "always", "reject"].includes(reply)) throw new Error("Invalid OpenCode permission decision.");
|
|
710
|
+
if (reply === "reject") onPermissionRejected?.();
|
|
711
|
+
await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply }) }, workingDirectory, controller, [200, 204, 404], false);
|
|
712
|
+
} else {
|
|
713
|
+
throw new Error(`Invalid OpenCode ${type} decision.`);
|
|
714
|
+
}
|
|
715
|
+
} catch (error) {
|
|
716
|
+
if (!controller.signal.aborted) process.stderr.write(`OpenCode interaction handler error: ${error.message}\n`);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
async function* readServerSentEvents(response, signal) {
|
|
721
|
+
const reader = response.body?.getReader();
|
|
722
|
+
if (!reader) return;
|
|
723
|
+
const abort = () => reader.cancel().catch(() => undefined);
|
|
724
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
725
|
+
const decoder = new TextDecoder();
|
|
726
|
+
let buffer = "";
|
|
727
|
+
try {
|
|
728
|
+
while (true) {
|
|
729
|
+
const { done, value } = await reader.read();
|
|
730
|
+
if (done) break;
|
|
731
|
+
buffer += decoder.decode(value, { stream: true });
|
|
732
|
+
let boundary = buffer.indexOf("\n\n");
|
|
733
|
+
while (boundary >= 0) {
|
|
734
|
+
const chunk = buffer.slice(0, boundary);
|
|
735
|
+
buffer = buffer.slice(boundary + 2);
|
|
736
|
+
const lines = chunk.split("\n");
|
|
737
|
+
const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
|
|
738
|
+
const id = lines.find((line) => line.startsWith("id:"))?.slice(3).trim();
|
|
739
|
+
const type = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
|
|
740
|
+
if (data) {
|
|
741
|
+
try {
|
|
742
|
+
const event = JSON.parse(data);
|
|
743
|
+
yield type ? { id, type, data: event } : event;
|
|
744
|
+
} catch { /* ponytail: skip non-JSON SSE frames */ }
|
|
745
|
+
}
|
|
746
|
+
boundary = buffer.indexOf("\n\n");
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
} finally {
|
|
750
|
+
signal?.removeEventListener("abort", abort);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
function abortable(operation, signal) {
|
|
755
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
756
|
+
return new Promise((resolve, reject) => {
|
|
757
|
+
const settle = (callback, value) => {
|
|
758
|
+
signal.removeEventListener("abort", abort);
|
|
759
|
+
callback(value);
|
|
760
|
+
};
|
|
761
|
+
const abort = () => settle(reject, signal.reason);
|
|
762
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
763
|
+
Promise.resolve(operation).then((value) => settle(resolve, value), (error) => settle(reject, error));
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
|
|
456
767
|
function isNetworkError(error) {
|
|
457
768
|
return error instanceof TypeError || ["ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.cause?.code ?? error?.code);
|
|
458
769
|
}
|
package/src/state.mjs
CHANGED
|
@@ -23,6 +23,7 @@ const MANIFEST = {
|
|
|
23
23
|
bot: [
|
|
24
24
|
"files:read",
|
|
25
25
|
"app_mentions:read",
|
|
26
|
+
"assistant:write",
|
|
26
27
|
"channels:history",
|
|
27
28
|
"channels:read",
|
|
28
29
|
"chat:write",
|
|
@@ -76,6 +77,19 @@ export async function acquireInstanceLock(file = pipaPaths().lock) {
|
|
|
76
77
|
return () => rm(file, { force: true });
|
|
77
78
|
}
|
|
78
79
|
|
|
80
|
+
export async function stopInstance(file = pipaPaths().lock, kill = process.kill) {
|
|
81
|
+
const pid = Number.parseInt(await readFile(file, "utf8").catch(() => ""), 10);
|
|
82
|
+
if (!pid) return null;
|
|
83
|
+
try {
|
|
84
|
+
kill(pid, "SIGTERM");
|
|
85
|
+
return pid;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error?.code === "ESRCH") await rm(file, { force: true });
|
|
88
|
+
else throw error;
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
79
93
|
export function createManifest(botName) {
|
|
80
94
|
const name = validateBotName(botName);
|
|
81
95
|
const manifest = structuredClone(MANIFEST);
|