@usepipa/pipa 0.3.0 → 0.3.2
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 +20 -3
- package/bin/pipa.mjs +22 -11
- package/package.json +7 -2
- package/src/app.mjs +48 -8
- package/src/opencode.mjs +347 -92
- package/src/state.mjs +6 -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 OpenCode in one of two profile modes: local Slack Socket Mode or a Managed OpenCode server. Local mode uses no hosted relay, database, public endpoint, or sandbox.
|
|
6
|
+
Pipa runs OpenCode in one of two profile modes: local Slack Socket Mode or a Managed OpenCode server. Local mode uses one persistent private OpenCode server and 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
|
|
|
@@ -41,9 +41,26 @@ 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 replies in a thread, and follow-up messages in that thread
|
|
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. 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
45
|
|
|
46
|
-
|
|
46
|
+
### Access control
|
|
47
|
+
|
|
48
|
+
By default Pipa answers anyone who mentions it in a channel it can see. In a shared workspace, restrict who can use it by listing the allowed Slack channel and user IDs. `pipa init` asks for these, and they are stored in the config:
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"botName": "Pipa",
|
|
53
|
+
"workingDirectory": "/work",
|
|
54
|
+
"slackAppToken": "xapp-...",
|
|
55
|
+
"slackBotToken": "xoxb-...",
|
|
56
|
+
"allowedSlackChannelIds": ["C0BSE2JTYPR"],
|
|
57
|
+
"allowedSlackUserIds": ["UFWBSCZ54"]
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
A mention is only handled when the channel ID is in `allowedSlackChannelIds` **and** the author's user ID is in `allowedSlackUserIds`. Leave a list empty to allow any channel or any user. You can also set them non-interactively during setup with `PIPA_ALLOWED_CHANNEL_IDS` and `PIPA_ALLOWED_USER_IDS` (comma-separated).
|
|
62
|
+
|
|
63
|
+
To use an existing OpenCode server instead, set its URL before starting Pipa. Pipa health-checks the server but does not start or stop it. If the server uses authentication, also set `OPENCODE_SERVER_USERNAME` and `OPENCODE_SERVER_PASSWORD`:
|
|
47
64
|
|
|
48
65
|
```sh
|
|
49
66
|
export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
|
package/bin/pipa.mjs
CHANGED
|
@@ -61,8 +61,12 @@ async function init(io) {
|
|
|
61
61
|
};
|
|
62
62
|
const slackAppToken = process.env.PIPA_SLACK_APP_TOKEN || await askSecret("Slack app token (xapp-, input hidden): ", "App token");
|
|
63
63
|
const slackBotToken = process.env.PIPA_SLACK_BOT_TOKEN || await askSecret("Slack bot token (xoxb-, input hidden): ", "Bot token");
|
|
64
|
+
const allowedSlackChannelIds = process.env.PIPA_ALLOWED_CHANNEL_IDS
|
|
65
|
+
?? (await prompt.question("Allowed Slack channel IDs (comma-separated, e.g. C0BSE2JTYPR; leave empty to allow any channel): ")).trim();
|
|
66
|
+
const allowedSlackUserIds = process.env.PIPA_ALLOWED_USER_IDS
|
|
67
|
+
?? (await prompt.question("Allowed Slack user IDs (comma-separated, e.g. UFWBSCZ54; leave empty to allow any user): ")).trim();
|
|
64
68
|
io.output.write("\nChecking OpenCode and Slack credentials...\n");
|
|
65
|
-
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken });
|
|
69
|
+
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds });
|
|
66
70
|
io.output.write(`✓ Credentials validated.\n\nSaved config to ${result.paths.config}. Run \`pipa start\`.\n`);
|
|
67
71
|
} finally {
|
|
68
72
|
prompt.close();
|
|
@@ -117,17 +121,24 @@ async function start(io) {
|
|
|
117
121
|
}
|
|
118
122
|
|
|
119
123
|
const app = await startPipa({ config });
|
|
124
|
+
io.output.write(app.server.owned
|
|
125
|
+
? `Pipa started a private OpenCode server at ${app.server.baseUrl}.\n`
|
|
126
|
+
: `Pipa is using the configured OpenCode server at ${app.server.baseUrl}.\n`);
|
|
120
127
|
io.output.write("Pipa is connected through Slack Socket Mode.\n");
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
128
|
+
let stop;
|
|
129
|
+
const signal = new Promise((resolve) => stop = resolve);
|
|
130
|
+
process.once("SIGINT", stop);
|
|
131
|
+
process.once("SIGTERM", stop);
|
|
132
|
+
try {
|
|
133
|
+
await Promise.race([signal, app.wait()]);
|
|
134
|
+
} finally {
|
|
135
|
+
try {
|
|
136
|
+
await app.shutdown();
|
|
137
|
+
} finally {
|
|
138
|
+
process.off("SIGINT", stop);
|
|
139
|
+
process.off("SIGTERM", stop);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
131
142
|
} finally {
|
|
132
143
|
await releaseLock();
|
|
133
144
|
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usepipa/pipa",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Run Pipa through Slack Socket Mode or as a managed OpenCode server",
|
|
5
|
-
"keywords": [
|
|
5
|
+
"keywords": [
|
|
6
|
+
"slack",
|
|
7
|
+
"opencode",
|
|
8
|
+
"ai-agent",
|
|
9
|
+
"cli"
|
|
10
|
+
],
|
|
6
11
|
"type": "module",
|
|
7
12
|
"bin": {
|
|
8
13
|
"pipa": "bin/pipa.mjs"
|
package/src/app.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { Chat } from "chat";
|
|
|
2
2
|
import { createSlackAdapter } from "@chat-adapter/slack";
|
|
3
3
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
4
4
|
import { canonicalWorkingDirectory, createManifest, createSessionStore, loadConfig, pipaPaths, saveConfig } from "./state.mjs";
|
|
5
|
-
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, runOpenCodeVersion } from "./opencode.mjs";
|
|
5
|
+
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
6
6
|
|
|
7
7
|
export async function initializePipa(input, options = {}) {
|
|
8
8
|
const paths = options.paths ?? pipaPaths();
|
|
@@ -12,6 +12,8 @@ export async function initializePipa(input, options = {}) {
|
|
|
12
12
|
slackAppToken: requireToken(input.slackAppToken, "Slack app token", "xapp-"),
|
|
13
13
|
slackBotToken: requireToken(input.slackBotToken, "Slack bot token", "xoxb-"),
|
|
14
14
|
workingDirectory: await canonicalWorkingDirectory(input.workingDirectory),
|
|
15
|
+
allowedSlackChannelIds: normalizeIdList(input.allowedSlackChannelIds),
|
|
16
|
+
allowedSlackUserIds: normalizeIdList(input.allowedSlackUserIds),
|
|
15
17
|
};
|
|
16
18
|
const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
|
|
17
19
|
if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
|
|
@@ -27,8 +29,6 @@ export async function startPipa(options = {}) {
|
|
|
27
29
|
const config = options.config ?? await loadConfig(paths.config);
|
|
28
30
|
await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
29
31
|
const sessionStore = options.sessionStore ?? await createSessionStore(paths.sessions);
|
|
30
|
-
const executor = options.executor ?? createOpenCodeExecutor();
|
|
31
|
-
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
32
32
|
const state = options.state ?? createMemoryState();
|
|
33
33
|
const chat = options.chat ?? new Chat({
|
|
34
34
|
adapters: {
|
|
@@ -44,10 +44,25 @@ export async function startPipa(options = {}) {
|
|
|
44
44
|
state,
|
|
45
45
|
userName: config.botName,
|
|
46
46
|
});
|
|
47
|
+
const server = options.server ?? (options.executor ? null : await (options.startServer ?? startSocketOpenCodeServer)(config, {
|
|
48
|
+
startupTimeoutMs: options.startupTimeoutMs,
|
|
49
|
+
}));
|
|
50
|
+
let executor;
|
|
51
|
+
try {
|
|
52
|
+
executor = options.executor ?? (options.createExecutor ?? createOpenCodeExecutor)({
|
|
53
|
+
baseUrl: server.baseUrl,
|
|
54
|
+
onFatal: server.fail,
|
|
55
|
+
});
|
|
56
|
+
} catch (error) {
|
|
57
|
+
server?.stop();
|
|
58
|
+
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
47
62
|
let accepting = true;
|
|
48
63
|
|
|
49
64
|
const handle = async (thread, message, subscribe) => {
|
|
50
|
-
if (!accepting || shouldIgnore(thread, message)) return;
|
|
65
|
+
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
|
|
51
66
|
const prompt = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
52
67
|
if (!prompt) return;
|
|
53
68
|
const attachments = message.attachments ?? [];
|
|
@@ -86,18 +101,28 @@ export async function startPipa(options = {}) {
|
|
|
86
101
|
} catch (error) {
|
|
87
102
|
executor.stopAll();
|
|
88
103
|
await withTimeout(chat.shutdown(), options.shutdownTimeoutMs ?? 15_000, "Slack shutdown timed out.").catch(() => undefined);
|
|
104
|
+
server?.stop();
|
|
105
|
+
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
89
106
|
throw error;
|
|
90
107
|
}
|
|
91
108
|
|
|
92
109
|
return {
|
|
110
|
+
server: server ? { baseUrl: server.baseUrl, owned: server.owned } : null,
|
|
111
|
+
wait: () => server?.wait() ?? new Promise(() => undefined),
|
|
93
112
|
async shutdown() {
|
|
94
113
|
accepting = false;
|
|
95
114
|
runner.close();
|
|
96
115
|
executor.stopAll();
|
|
97
|
-
|
|
98
|
-
await
|
|
99
|
-
|
|
100
|
-
|
|
116
|
+
try {
|
|
117
|
+
await withTimeout((async () => {
|
|
118
|
+
await runner.drain();
|
|
119
|
+
await chat.shutdown();
|
|
120
|
+
server?.stop();
|
|
121
|
+
await server?.wait();
|
|
122
|
+
})(), options.shutdownTimeoutMs ?? 15_000, "Pipa shutdown timed out.");
|
|
123
|
+
} finally {
|
|
124
|
+
server?.stop();
|
|
125
|
+
}
|
|
101
126
|
},
|
|
102
127
|
};
|
|
103
128
|
}
|
|
@@ -178,6 +203,20 @@ function shouldIgnore(thread, message) {
|
|
|
178
203
|
|| !message.text?.trim();
|
|
179
204
|
}
|
|
180
205
|
|
|
206
|
+
function isAuthorized(thread, message, config) {
|
|
207
|
+
const channelId = thread.id.split(":")[1];
|
|
208
|
+
const userId = message.author?.userId ?? message.author?.id;
|
|
209
|
+
if (config.allowedSlackChannelIds?.length && !config.allowedSlackChannelIds.includes(channelId)) return false;
|
|
210
|
+
if (config.allowedSlackUserIds?.length && !config.allowedSlackUserIds.includes(userId)) return false;
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function normalizeIdList(value) {
|
|
215
|
+
if (value === undefined || value === null) return [];
|
|
216
|
+
const list = Array.isArray(value) ? value : String(value).split(/[\s,]+/u);
|
|
217
|
+
return list.map((item) => String(item).trim()).filter(Boolean);
|
|
218
|
+
}
|
|
219
|
+
|
|
181
220
|
function stripMention(text = "") {
|
|
182
221
|
return text.replace(/(?:<@|@)[UW][A-Z0-9]+>?/u, "").trim();
|
|
183
222
|
}
|
|
@@ -221,6 +260,7 @@ async function finishReaction(thread, message, emoji) {
|
|
|
221
260
|
}
|
|
222
261
|
|
|
223
262
|
async function withTimeout(promise, timeoutMs, message) {
|
|
263
|
+
if (!promise) return;
|
|
224
264
|
let timer;
|
|
225
265
|
try {
|
|
226
266
|
return await Promise.race([
|
package/src/opencode.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import crossSpawn from "cross-spawn";
|
|
|
2
2
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
5
6
|
|
|
6
7
|
const SECRET_ENV_KEYS = new Set([
|
|
7
8
|
"PIPA_SLACK_APP_TOKEN",
|
|
@@ -9,6 +10,7 @@ const SECRET_ENV_KEYS = new Set([
|
|
|
9
10
|
"SLACK_APP_TOKEN",
|
|
10
11
|
"SLACK_BOT_TOKEN",
|
|
11
12
|
]);
|
|
13
|
+
const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
|
|
12
14
|
|
|
13
15
|
export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
|
|
14
16
|
|
|
@@ -16,24 +18,100 @@ export function cleanChildEnvironment(environment = process.env) {
|
|
|
16
18
|
return Object.fromEntries(Object.entries(environment).filter(([key]) => !SECRET_ENV_KEYS.has(key.toUpperCase())));
|
|
17
19
|
}
|
|
18
20
|
|
|
19
|
-
export function
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
21
|
+
export async function startSocketOpenCodeServer(config, options = {}) {
|
|
22
|
+
const environment = options.environment ?? process.env;
|
|
23
|
+
const attachUrl = options.attachUrl ?? environment.PIPA_OPENCODE_ATTACH_URL?.trim();
|
|
24
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
25
|
+
const startupTimeoutMs = options.startupTimeoutMs ?? 30_000;
|
|
26
|
+
const headers = authenticationHeaders(environment);
|
|
27
|
+
|
|
28
|
+
if (attachUrl) {
|
|
29
|
+
const baseUrl = normalizeBaseUrl(attachUrl);
|
|
30
|
+
await waitForHealth(baseUrl, fetchImpl, headers, startupTimeoutMs);
|
|
31
|
+
return externalServer(baseUrl);
|
|
32
|
+
}
|
|
27
33
|
|
|
28
|
-
export function createOpenCodeExecutor(options = {}) {
|
|
29
34
|
const spawn = options.spawn ?? crossSpawn;
|
|
30
35
|
const platform = options.platform ?? process.platform;
|
|
36
|
+
const child = spawn("opencode", [
|
|
37
|
+
"serve",
|
|
38
|
+
"--hostname", "127.0.0.1",
|
|
39
|
+
"--port", "0",
|
|
40
|
+
"--log-level", "ERROR",
|
|
41
|
+
], {
|
|
42
|
+
cwd: config.workingDirectory,
|
|
43
|
+
env: cleanChildEnvironment(environment),
|
|
44
|
+
shell: false,
|
|
45
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
46
|
+
});
|
|
47
|
+
const exit = waitForExit(child);
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const baseUrl = await Promise.race([
|
|
51
|
+
readListeningUrl(child, startupTimeoutMs),
|
|
52
|
+
exit.then((code) => { throw new Error(`OpenCode server exited before startup with code ${code}.`); }),
|
|
53
|
+
]);
|
|
54
|
+
child.stdout?.resume();
|
|
55
|
+
child.stderr?.resume();
|
|
56
|
+
await Promise.race([
|
|
57
|
+
waitForHealth(baseUrl, fetchImpl, headers, startupTimeoutMs),
|
|
58
|
+
exit.then((code) => { throw new Error(`OpenCode server exited before startup with code ${code}.`); }),
|
|
59
|
+
]);
|
|
60
|
+
return ownedServer(baseUrl, child, exit, platform);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
terminateChild(child, platform);
|
|
63
|
+
await Promise.race([exit.catch(() => undefined), delay(5_000)]);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function createOpenCodeExecutor(options = {}) {
|
|
69
|
+
const baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
70
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
31
71
|
const environment = options.environment ?? process.env;
|
|
32
|
-
const
|
|
72
|
+
const headers = authenticationHeaders(environment);
|
|
33
73
|
const timeoutMs = options.timeoutMs ?? 2.5 * 60 * 60 * 1000;
|
|
34
|
-
const
|
|
74
|
+
const requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
|
|
75
|
+
const pollIntervalMs = options.pollIntervalMs ?? 1_000;
|
|
76
|
+
const useDataUrls = !isLoopbackUrl(baseUrl);
|
|
77
|
+
const active = new Set();
|
|
35
78
|
let stopped = false;
|
|
36
79
|
|
|
80
|
+
async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200]) {
|
|
81
|
+
const url = serverUrl(baseUrl, pathname, workingDirectory);
|
|
82
|
+
let response;
|
|
83
|
+
try {
|
|
84
|
+
response = await fetchImpl(url, {
|
|
85
|
+
...init,
|
|
86
|
+
headers: {
|
|
87
|
+
...headers,
|
|
88
|
+
...(init.body ? { "content-type": "application/json" } : {}),
|
|
89
|
+
...init.headers,
|
|
90
|
+
},
|
|
91
|
+
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(requestTimeoutMs)]),
|
|
92
|
+
});
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
95
|
+
if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
let text;
|
|
99
|
+
try {
|
|
100
|
+
text = await response.text();
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
103
|
+
if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
if (!acceptedStatuses.includes(response.status)) throw new OpenCodeRequestError(response.status);
|
|
107
|
+
if (!text) return undefined;
|
|
108
|
+
try {
|
|
109
|
+
return JSON.parse(text);
|
|
110
|
+
} catch {
|
|
111
|
+
throw new Error("OpenCode returned an invalid response.");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
37
115
|
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [] }) {
|
|
38
116
|
if (!prompt?.trim()) throw new Error("A prompt is required.");
|
|
39
117
|
if (stopped) throw new Error("Pipa is shutting down.");
|
|
@@ -41,66 +119,63 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
41
119
|
let turnError;
|
|
42
120
|
|
|
43
121
|
try {
|
|
44
|
-
const files =
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
+
try {
|
|
129
|
+
let selectedSessionId = sessionId;
|
|
130
|
+
let messages;
|
|
131
|
+
if (selectedSessionId) {
|
|
132
|
+
try {
|
|
133
|
+
while (true) {
|
|
134
|
+
const status = (await request("/session/status", { method: "GET" }, workingDirectory, controller))?.[selectedSessionId]?.type;
|
|
135
|
+
if (status !== "busy" && status !== "retry") break;
|
|
136
|
+
await delay(pollIntervalMs, controller.signal);
|
|
137
|
+
}
|
|
138
|
+
messages = await request(`/session/${encodeURIComponent(selectedSessionId)}/message?limit=1`, { method: "GET" }, workingDirectory, controller);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (!(error instanceof OpenCodeRequestError) || error.status !== 404) throw error;
|
|
141
|
+
selectedSessionId = null;
|
|
142
|
+
}
|
|
51
143
|
}
|
|
52
|
-
if (
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const name = Array.from(sanitizedName).reduce(
|
|
58
|
-
(result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result,
|
|
59
|
-
"",
|
|
60
|
-
) || "attachment";
|
|
61
|
-
const file = path.join(temporaryDirectory, `${index + 1}-${name}`);
|
|
62
|
-
await writeFile(file, data);
|
|
63
|
-
files.push(file);
|
|
64
|
-
} catch {
|
|
65
|
-
throw new Error("Could not read one of the attached files. Please try uploading it again.");
|
|
144
|
+
if (!selectedSessionId) {
|
|
145
|
+
const session = await request("/session", { method: "POST", body: "{}" }, workingDirectory, controller);
|
|
146
|
+
if (!session?.id) throw new Error("OpenCode did not create a session.");
|
|
147
|
+
selectedSessionId = session.id;
|
|
148
|
+
messages = [];
|
|
66
149
|
}
|
|
67
|
-
}
|
|
68
150
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
75
|
-
});
|
|
76
|
-
children.add(child);
|
|
77
|
-
const exit = waitForExit(child);
|
|
78
|
-
void exit.finally(() => children.delete(child)).catch(() => undefined);
|
|
79
|
-
let timer;
|
|
151
|
+
const baseline = new Set(messages.map((message) => message?.info?.id).filter(Boolean));
|
|
152
|
+
await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
|
|
153
|
+
method: "POST",
|
|
154
|
+
body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment)),
|
|
155
|
+
}, workingDirectory, controller, [204]);
|
|
80
156
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
} catch (error) {
|
|
96
|
-
terminateChild(child, platform);
|
|
97
|
-
await exit.catch(() => undefined);
|
|
98
|
-
throw error;
|
|
157
|
+
while (true) {
|
|
158
|
+
const [currentMessages, statuses] = await Promise.all([
|
|
159
|
+
request(`/session/${encodeURIComponent(selectedSessionId)}/message?limit=1`, { method: "GET" }, workingDirectory, controller),
|
|
160
|
+
request("/session/status", { method: "GET" }, workingDirectory, controller),
|
|
161
|
+
]);
|
|
162
|
+
const finalMessage = latestAssistantMessage(currentMessages, baseline);
|
|
163
|
+
const status = statuses?.[selectedSessionId]?.type;
|
|
164
|
+
if (["error", "failed", "cancelled"].includes(status) || finalMessage?.error) throw new Error("OpenCode failed to complete the turn.");
|
|
165
|
+
if (finalMessage && (status === "idle" || (!status && finalMessage.completed))) {
|
|
166
|
+
if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
|
|
167
|
+
return { text: finalMessage.text, sessionId: selectedSessionId };
|
|
168
|
+
}
|
|
169
|
+
await delay(pollIntervalMs, controller.signal);
|
|
170
|
+
}
|
|
99
171
|
} finally {
|
|
100
172
|
clearTimeout(timer);
|
|
173
|
+
controller.abort(new Error("OpenCode turn completed."));
|
|
174
|
+
active.delete(controller);
|
|
101
175
|
}
|
|
102
176
|
} catch (error) {
|
|
103
177
|
turnError = error;
|
|
178
|
+
if (stopped) throw new Error("Pipa is shutting down.");
|
|
104
179
|
throw error;
|
|
105
180
|
} finally {
|
|
106
181
|
if (temporaryDirectory) {
|
|
@@ -118,7 +193,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
118
193
|
runTurn,
|
|
119
194
|
stopAll() {
|
|
120
195
|
stopped = true;
|
|
121
|
-
for (const
|
|
196
|
+
for (const controller of active) controller.abort(new Error("Pipa is shutting down."));
|
|
122
197
|
},
|
|
123
198
|
};
|
|
124
199
|
}
|
|
@@ -152,16 +227,6 @@ export function startOpenCodeServer(config, options = {}) {
|
|
|
152
227
|
};
|
|
153
228
|
}
|
|
154
229
|
|
|
155
|
-
function fetchAttachment(attachment, timeoutMs) {
|
|
156
|
-
let timer;
|
|
157
|
-
return Promise.race([
|
|
158
|
-
attachment.fetchData(),
|
|
159
|
-
new Promise((_, reject) => {
|
|
160
|
-
timer = setTimeout(() => reject(new Error(`Attachment download timed out after ${timeoutMs}ms.`)), timeoutMs);
|
|
161
|
-
}),
|
|
162
|
-
]).finally(() => clearTimeout(timer));
|
|
163
|
-
}
|
|
164
|
-
|
|
165
230
|
export async function runOpenCodeVersion(options = {}) {
|
|
166
231
|
const spawn = options.spawn ?? crossSpawn;
|
|
167
232
|
const platform = options.platform ?? process.platform;
|
|
@@ -184,35 +249,219 @@ export async function runOpenCodeVersion(options = {}) {
|
|
|
184
249
|
if (code !== 0) throw new Error(stderr.trim() || "OpenCode version check failed.");
|
|
185
250
|
return stdout.trim();
|
|
186
251
|
} catch (error) {
|
|
187
|
-
if (error?.code === "ENOENT")
|
|
188
|
-
throw new Error("OpenCode is unavailable. Install it and make sure `opencode --version` succeeds.");
|
|
189
|
-
}
|
|
252
|
+
if (error?.code === "ENOENT") throw new Error("OpenCode is unavailable. Install it and make sure `opencode --version` succeeds.");
|
|
190
253
|
throw error;
|
|
191
254
|
} finally {
|
|
192
255
|
clearTimeout(timer);
|
|
193
256
|
}
|
|
194
257
|
}
|
|
195
258
|
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
259
|
+
async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls) {
|
|
260
|
+
const files = [];
|
|
261
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
262
|
+
let data;
|
|
263
|
+
try {
|
|
264
|
+
data = await fetchAttachment(attachment, timeoutMs);
|
|
265
|
+
} catch {
|
|
266
|
+
throw new Error("Could not read one of the attached files. Please try uploading it again.");
|
|
267
|
+
}
|
|
268
|
+
if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 100 MB or smaller.");
|
|
269
|
+
try {
|
|
270
|
+
const sanitizedName = path.basename(attachment.name || "attachment")
|
|
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";
|
|
277
|
+
const file = path.join(temporaryDirectory, `${index + 1}-${filename}`);
|
|
278
|
+
await writeFile(file, data);
|
|
279
|
+
const mime = attachment.mimeType || "application/octet-stream";
|
|
280
|
+
files.push({
|
|
281
|
+
filename,
|
|
282
|
+
mime,
|
|
283
|
+
url: useDataUrls ? `data:${mime};base64,${Buffer.from(data).toString("base64")}` : pathToFileURL(file).href,
|
|
284
|
+
});
|
|
285
|
+
} catch {
|
|
286
|
+
throw new Error("Could not read one of the attached files. Please try uploading it again.");
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return files;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function promptBody(prompt, files, contextEnvironment) {
|
|
293
|
+
const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
|
|
294
|
+
const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
|
|
295
|
+
return {
|
|
296
|
+
parts,
|
|
297
|
+
...(context.length ? { system: `Runtime context for this turn:\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}` } : {}),
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function latestAssistantMessage(messages, baseline) {
|
|
302
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
303
|
+
const message = messages[index];
|
|
304
|
+
if (!message?.info?.id || baseline.has(message.info.id) || message.info.role !== "assistant") continue;
|
|
305
|
+
return {
|
|
306
|
+
completed: typeof message.info.time?.completed === "number",
|
|
307
|
+
error: message.info.error,
|
|
308
|
+
text: message.parts
|
|
309
|
+
.filter((part) => part.type === "text" && typeof part.text === "string" && part.text)
|
|
310
|
+
.map((part) => part.text)
|
|
311
|
+
.join("\n")
|
|
312
|
+
.trim(),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function ownedServer(baseUrl, child, exit, platform) {
|
|
319
|
+
let stopping = false;
|
|
320
|
+
let rejectFailure;
|
|
321
|
+
const failure = new Promise((_, reject) => rejectFailure = reject);
|
|
322
|
+
const wait = Promise.race([exit.then((code) => {
|
|
323
|
+
if (!stopping) throw new Error(`OpenCode server exited unexpectedly with code ${code}.`);
|
|
324
|
+
}), failure]);
|
|
325
|
+
void wait.catch(() => undefined);
|
|
326
|
+
return {
|
|
327
|
+
baseUrl,
|
|
328
|
+
owned: true,
|
|
329
|
+
wait: () => wait,
|
|
330
|
+
fail(error) {
|
|
331
|
+
if (!stopping) rejectFailure(error);
|
|
332
|
+
},
|
|
333
|
+
stop(signal = "SIGTERM") {
|
|
334
|
+
if (stopping) return;
|
|
335
|
+
stopping = true;
|
|
336
|
+
terminateChild(child, platform, signal);
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function externalServer(baseUrl) {
|
|
342
|
+
let resolveWait;
|
|
343
|
+
let rejectWait;
|
|
344
|
+
let stopped = false;
|
|
345
|
+
const wait = new Promise((resolve, reject) => {
|
|
346
|
+
resolveWait = resolve;
|
|
347
|
+
rejectWait = reject;
|
|
348
|
+
});
|
|
349
|
+
void wait.catch(() => undefined);
|
|
350
|
+
return {
|
|
351
|
+
baseUrl,
|
|
352
|
+
owned: false,
|
|
353
|
+
wait: () => wait,
|
|
354
|
+
fail(error) {
|
|
355
|
+
if (!stopped) rejectWait(error);
|
|
356
|
+
},
|
|
357
|
+
stop() {
|
|
358
|
+
if (stopped) return;
|
|
359
|
+
stopped = true;
|
|
360
|
+
resolveWait();
|
|
361
|
+
},
|
|
362
|
+
};
|
|
363
|
+
}
|
|
200
364
|
|
|
201
|
-
|
|
202
|
-
|
|
365
|
+
async function waitForHealth(baseUrl, fetchImpl, headers, timeoutMs) {
|
|
366
|
+
const deadline = Date.now() + timeoutMs;
|
|
367
|
+
while (Date.now() < deadline) {
|
|
203
368
|
try {
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
if (
|
|
209
|
-
const eventError = event.error?.data?.message ?? event.error?.message;
|
|
210
|
-
if (typeof eventError === "string" && eventError.trim()) error = eventError.trim();
|
|
369
|
+
const response = await fetchImpl(`${baseUrl}/global/health`, {
|
|
370
|
+
headers,
|
|
371
|
+
signal: AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))),
|
|
372
|
+
});
|
|
373
|
+
if (response.ok && (await response.json())?.healthy === true) return;
|
|
211
374
|
} catch {
|
|
212
|
-
//
|
|
375
|
+
// The server can accept its socket shortly before the health route is ready.
|
|
213
376
|
}
|
|
377
|
+
await delay(Math.min(250, Math.max(0, deadline - Date.now())));
|
|
378
|
+
}
|
|
379
|
+
throw new Error("OpenCode server health check timed out.");
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function readListeningUrl(child, timeoutMs) {
|
|
383
|
+
return new Promise((resolve, reject) => {
|
|
384
|
+
let output = "";
|
|
385
|
+
const cleanup = () => {
|
|
386
|
+
child.stdout?.off("data", inspect);
|
|
387
|
+
child.stderr?.off("data", inspect);
|
|
388
|
+
};
|
|
389
|
+
const finish = (callback, value) => {
|
|
390
|
+
clearTimeout(timer);
|
|
391
|
+
cleanup();
|
|
392
|
+
callback(value);
|
|
393
|
+
};
|
|
394
|
+
const inspect = (chunk) => {
|
|
395
|
+
output = (output + chunk).slice(-16_384);
|
|
396
|
+
const match = output.match(LISTENING_URL);
|
|
397
|
+
if (!match) return;
|
|
398
|
+
finish(resolve, normalizeBaseUrl(match[0]));
|
|
399
|
+
};
|
|
400
|
+
const timer = setTimeout(() => finish(reject, new Error("OpenCode server did not report its listening URL.")), timeoutMs);
|
|
401
|
+
timer.unref?.();
|
|
402
|
+
child.stdout?.on("data", inspect);
|
|
403
|
+
child.stderr?.on("data", inspect);
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function authenticationHeaders(environment) {
|
|
408
|
+
const password = environment.OPENCODE_SERVER_PASSWORD;
|
|
409
|
+
if (!password) return {};
|
|
410
|
+
const username = environment.OPENCODE_SERVER_USERNAME?.trim() || "opencode";
|
|
411
|
+
return { authorization: `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}` };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function normalizeBaseUrl(value) {
|
|
415
|
+
const url = new URL(value);
|
|
416
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("OpenCode server URL must use http or https.");
|
|
417
|
+
return url.href.replace(/\/+$/u, "");
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function isLoopbackUrl(value) {
|
|
421
|
+
const hostname = new URL(value).hostname;
|
|
422
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function serverUrl(baseUrl, pathname, workingDirectory) {
|
|
426
|
+
const url = new URL(`${baseUrl}${pathname}`);
|
|
427
|
+
if (workingDirectory) url.searchParams.set("directory", workingDirectory);
|
|
428
|
+
return url;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function fetchAttachment(attachment, timeoutMs) {
|
|
432
|
+
let timer;
|
|
433
|
+
return Promise.race([
|
|
434
|
+
attachment.fetchData(),
|
|
435
|
+
new Promise((_, reject) => timer = setTimeout(() => reject(new Error(`Attachment download timed out after ${timeoutMs}ms.`)), timeoutMs)),
|
|
436
|
+
]).finally(() => clearTimeout(timer));
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function delay(delayMs, signal) {
|
|
440
|
+
return new Promise((resolve, reject) => {
|
|
441
|
+
if (signal?.aborted) {
|
|
442
|
+
reject(signal.reason);
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const settle = (callback, value) => {
|
|
446
|
+
clearTimeout(timer);
|
|
447
|
+
signal?.removeEventListener("abort", abort);
|
|
448
|
+
callback(value);
|
|
449
|
+
};
|
|
450
|
+
const abort = () => settle(reject, signal.reason);
|
|
451
|
+
const timer = setTimeout(() => settle(resolve), delayMs);
|
|
452
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function isNetworkError(error) {
|
|
457
|
+
return error instanceof TypeError || ["ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.cause?.code ?? error?.code);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
class OpenCodeRequestError extends Error {
|
|
461
|
+
constructor(status) {
|
|
462
|
+
super(`OpenCode request failed with status ${status}.`);
|
|
463
|
+
this.status = status;
|
|
214
464
|
}
|
|
215
|
-
return { text, sessionId, error };
|
|
216
465
|
}
|
|
217
466
|
|
|
218
467
|
function collect(stream, limit = 10 * 1024 * 1024) {
|
|
@@ -236,7 +485,13 @@ function waitForExit(child) {
|
|
|
236
485
|
|
|
237
486
|
function terminateChild(child, platform, signal) {
|
|
238
487
|
if (platform === "win32" && child.pid) {
|
|
239
|
-
crossSpawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore" });
|
|
488
|
+
const taskkill = crossSpawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], { stdio: "ignore" });
|
|
489
|
+
const fallback = () => child.kill("SIGKILL");
|
|
490
|
+
taskkill.once("error", fallback);
|
|
491
|
+
taskkill.once("close", (code) => { if (code !== 0) fallback(); });
|
|
492
|
+
const force = setTimeout(fallback, 5_000);
|
|
493
|
+
force.unref?.();
|
|
494
|
+
child.once("close", () => clearTimeout(force));
|
|
240
495
|
return;
|
|
241
496
|
}
|
|
242
497
|
child.kill(signal);
|
package/src/state.mjs
CHANGED
|
@@ -114,6 +114,12 @@ export async function loadConfig(file = pipaPaths().config) {
|
|
|
114
114
|
if (slackMode === "managed" && (!Number.isInteger(config.openCodePort) || config.openCodePort < 1 || config.openCodePort > 65535)) {
|
|
115
115
|
throw new Error("Invalid Pipa config: openCodePort must be an integer from 1 to 65535.");
|
|
116
116
|
}
|
|
117
|
+
for (const key of ["allowedSlackChannelIds", "allowedSlackUserIds"]) {
|
|
118
|
+
const value = config[key];
|
|
119
|
+
if (value !== undefined && (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim()))) {
|
|
120
|
+
throw new Error(`Invalid Pipa config: ${key} must be a list of non-empty Slack IDs.`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
117
123
|
return { ...config, slackMode };
|
|
118
124
|
}
|
|
119
125
|
|