@usepipa/pipa 0.2.3 → 0.3.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 +26 -6
- package/bin/pipa.mjs +37 -12
- package/package.json +8 -3
- package/src/app.mjs +31 -7
- package/src/opencode.mjs +377 -92
- package/src/state.mjs +12 -2
package/README.md
CHANGED
|
@@ -3,11 +3,15 @@
|
|
|
3
3
|
[](https://github.com/lunchpaillola/pipa/actions/workflows/ci.yml)
|
|
4
4
|
[](LICENSE)
|
|
5
5
|
|
|
6
|
-
Pipa
|
|
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
|
|
|
10
|
-
##
|
|
10
|
+
## Local Socket Mode
|
|
11
|
+
|
|
12
|
+
Profiles created by `pipa init` use Socket Mode. Profiles written before mode support continue to load as Socket Mode.
|
|
13
|
+
|
|
14
|
+
### Requirements
|
|
11
15
|
|
|
12
16
|
- Node.js 22 or newer
|
|
13
17
|
- [OpenCode](https://opencode.ai) installed and authenticated
|
|
@@ -15,7 +19,7 @@ Pipa connects Slack to the OpenCode already installed on your computer. It runs
|
|
|
15
19
|
|
|
16
20
|
Invite the Slack app only to channels whose members may use OpenCode in the configured working directory.
|
|
17
21
|
|
|
18
|
-
|
|
22
|
+
### Install
|
|
19
23
|
|
|
20
24
|
1. Install Pipa:
|
|
21
25
|
|
|
@@ -37,20 +41,36 @@ pipa init
|
|
|
37
41
|
pipa start
|
|
38
42
|
```
|
|
39
43
|
|
|
40
|
-
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.
|
|
41
45
|
|
|
42
|
-
To use an existing OpenCode server instead
|
|
46
|
+
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`:
|
|
43
47
|
|
|
44
48
|
```sh
|
|
45
49
|
export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
|
|
46
50
|
pipa start
|
|
47
51
|
```
|
|
48
52
|
|
|
53
|
+
## Managed Mode
|
|
54
|
+
|
|
55
|
+
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:
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{
|
|
59
|
+
"botName": "Pipa",
|
|
60
|
+
"workingDirectory": "/workspace",
|
|
61
|
+
"slackMode": "managed",
|
|
62
|
+
"openCodeHostname": "127.0.0.1",
|
|
63
|
+
"openCodePort": 4096
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
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.
|
|
68
|
+
|
|
49
69
|
## Commands
|
|
50
70
|
|
|
51
71
|
```text
|
|
52
72
|
pipa init Configure Slack and the local working directory
|
|
53
|
-
pipa start
|
|
73
|
+
pipa start Start the configured Socket or Managed runtime
|
|
54
74
|
pipa --version Print the installed version
|
|
55
75
|
```
|
|
56
76
|
|
package/bin/pipa.mjs
CHANGED
|
@@ -5,8 +5,9 @@ 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 } from "../src/state.mjs";
|
|
8
|
+
import { acquireInstanceLock, createManifest, createManifestUrl, loadConfig } from "../src/state.mjs";
|
|
9
9
|
import { initializePipa, startPipa } from "../src/app.mjs";
|
|
10
|
+
import { startOpenCodeServer } from "../src/opencode.mjs";
|
|
10
11
|
|
|
11
12
|
const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
12
13
|
|
|
@@ -98,18 +99,42 @@ function openUrl(url) {
|
|
|
98
99
|
async function start(io) {
|
|
99
100
|
const releaseLock = await acquireInstanceLock();
|
|
100
101
|
try {
|
|
101
|
-
const
|
|
102
|
+
const config = await loadConfig();
|
|
103
|
+
if (config.slackMode === "managed") {
|
|
104
|
+
const server = startOpenCodeServer(config);
|
|
105
|
+
io.output.write(`Pipa is starting OpenCode on ${config.openCodeHostname}:${config.openCodePort}.\n`);
|
|
106
|
+
const stopWithSigint = () => server.stop("SIGINT");
|
|
107
|
+
const stopWithSigterm = () => server.stop("SIGTERM");
|
|
108
|
+
process.on("SIGINT", stopWithSigint);
|
|
109
|
+
process.on("SIGTERM", stopWithSigterm);
|
|
110
|
+
try {
|
|
111
|
+
await server.wait();
|
|
112
|
+
} finally {
|
|
113
|
+
process.off("SIGINT", stopWithSigint);
|
|
114
|
+
process.off("SIGTERM", stopWithSigterm);
|
|
115
|
+
}
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const app = await startPipa({ config });
|
|
120
|
+
io.output.write(app.server.owned
|
|
121
|
+
? `Pipa started a private OpenCode server at ${app.server.baseUrl}.\n`
|
|
122
|
+
: `Pipa is using the configured OpenCode server at ${app.server.baseUrl}.\n`);
|
|
102
123
|
io.output.write("Pipa is connected through Slack Socket Mode.\n");
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
124
|
+
let stop;
|
|
125
|
+
const signal = new Promise((resolve) => stop = resolve);
|
|
126
|
+
process.once("SIGINT", stop);
|
|
127
|
+
process.once("SIGTERM", stop);
|
|
128
|
+
try {
|
|
129
|
+
await Promise.race([signal, app.wait()]);
|
|
130
|
+
} finally {
|
|
131
|
+
try {
|
|
132
|
+
await app.shutdown();
|
|
133
|
+
} finally {
|
|
134
|
+
process.off("SIGINT", stop);
|
|
135
|
+
process.off("SIGTERM", stop);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
113
138
|
} finally {
|
|
114
139
|
await releaseLock();
|
|
115
140
|
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usepipa/pipa",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Run Pipa
|
|
5
|
-
"keywords": [
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"description": "Run Pipa through Slack Socket Mode or as a managed OpenCode server",
|
|
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();
|
|
@@ -27,8 +27,6 @@ export async function startPipa(options = {}) {
|
|
|
27
27
|
const config = options.config ?? await loadConfig(paths.config);
|
|
28
28
|
await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
29
29
|
const sessionStore = options.sessionStore ?? await createSessionStore(paths.sessions);
|
|
30
|
-
const executor = options.executor ?? createOpenCodeExecutor();
|
|
31
|
-
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
32
30
|
const state = options.state ?? createMemoryState();
|
|
33
31
|
const chat = options.chat ?? new Chat({
|
|
34
32
|
adapters: {
|
|
@@ -44,6 +42,21 @@ export async function startPipa(options = {}) {
|
|
|
44
42
|
state,
|
|
45
43
|
userName: config.botName,
|
|
46
44
|
});
|
|
45
|
+
const server = options.server ?? (options.executor ? null : await (options.startServer ?? startSocketOpenCodeServer)(config, {
|
|
46
|
+
startupTimeoutMs: options.startupTimeoutMs,
|
|
47
|
+
}));
|
|
48
|
+
let executor;
|
|
49
|
+
try {
|
|
50
|
+
executor = options.executor ?? (options.createExecutor ?? createOpenCodeExecutor)({
|
|
51
|
+
baseUrl: server.baseUrl,
|
|
52
|
+
onFatal: server.fail,
|
|
53
|
+
});
|
|
54
|
+
} catch (error) {
|
|
55
|
+
server?.stop();
|
|
56
|
+
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
47
60
|
let accepting = true;
|
|
48
61
|
|
|
49
62
|
const handle = async (thread, message, subscribe) => {
|
|
@@ -86,18 +99,28 @@ export async function startPipa(options = {}) {
|
|
|
86
99
|
} catch (error) {
|
|
87
100
|
executor.stopAll();
|
|
88
101
|
await withTimeout(chat.shutdown(), options.shutdownTimeoutMs ?? 15_000, "Slack shutdown timed out.").catch(() => undefined);
|
|
102
|
+
server?.stop();
|
|
103
|
+
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
89
104
|
throw error;
|
|
90
105
|
}
|
|
91
106
|
|
|
92
107
|
return {
|
|
108
|
+
server: server ? { baseUrl: server.baseUrl, owned: server.owned } : null,
|
|
109
|
+
wait: () => server?.wait() ?? new Promise(() => undefined),
|
|
93
110
|
async shutdown() {
|
|
94
111
|
accepting = false;
|
|
95
112
|
runner.close();
|
|
96
113
|
executor.stopAll();
|
|
97
|
-
|
|
98
|
-
await
|
|
99
|
-
|
|
100
|
-
|
|
114
|
+
try {
|
|
115
|
+
await withTimeout((async () => {
|
|
116
|
+
await runner.drain();
|
|
117
|
+
await chat.shutdown();
|
|
118
|
+
server?.stop();
|
|
119
|
+
await server?.wait();
|
|
120
|
+
})(), options.shutdownTimeoutMs ?? 15_000, "Pipa shutdown timed out.");
|
|
121
|
+
} finally {
|
|
122
|
+
server?.stop();
|
|
123
|
+
}
|
|
101
124
|
},
|
|
102
125
|
};
|
|
103
126
|
}
|
|
@@ -221,6 +244,7 @@ async function finishReaction(thread, message, emoji) {
|
|
|
221
244
|
}
|
|
222
245
|
|
|
223
246
|
async function withTimeout(promise, timeoutMs, message) {
|
|
247
|
+
if (!promise) return;
|
|
224
248
|
let timer;
|
|
225
249
|
try {
|
|
226
250
|
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,19 +193,38 @@ 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
|
}
|
|
125
200
|
|
|
126
|
-
function
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
201
|
+
export function startOpenCodeServer(config, options = {}) {
|
|
202
|
+
const spawn = options.spawn ?? crossSpawn;
|
|
203
|
+
const platform = options.platform ?? process.platform;
|
|
204
|
+
const child = spawn("opencode", [
|
|
205
|
+
"serve",
|
|
206
|
+
"--hostname", config.openCodeHostname,
|
|
207
|
+
"--port", String(config.openCodePort),
|
|
208
|
+
"--log-level", "ERROR",
|
|
209
|
+
], {
|
|
210
|
+
cwd: config.workingDirectory,
|
|
211
|
+
env: cleanChildEnvironment(options.environment ?? process.env),
|
|
212
|
+
shell: false,
|
|
213
|
+
stdio: "inherit",
|
|
214
|
+
});
|
|
215
|
+
let stopping = false;
|
|
216
|
+
const exit = waitForExit(child).then((code) => {
|
|
217
|
+
if (!stopping) throw new Error(`OpenCode server exited unexpectedly with code ${code}.`);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
wait: () => exit,
|
|
222
|
+
stop(signal) {
|
|
223
|
+
if (stopping) return;
|
|
224
|
+
stopping = true;
|
|
225
|
+
terminateChild(child, platform, signal);
|
|
226
|
+
},
|
|
227
|
+
};
|
|
134
228
|
}
|
|
135
229
|
|
|
136
230
|
export async function runOpenCodeVersion(options = {}) {
|
|
@@ -155,35 +249,219 @@ export async function runOpenCodeVersion(options = {}) {
|
|
|
155
249
|
if (code !== 0) throw new Error(stderr.trim() || "OpenCode version check failed.");
|
|
156
250
|
return stdout.trim();
|
|
157
251
|
} catch (error) {
|
|
158
|
-
if (error?.code === "ENOENT")
|
|
159
|
-
throw new Error("OpenCode is unavailable. Install it and make sure `opencode --version` succeeds.");
|
|
160
|
-
}
|
|
252
|
+
if (error?.code === "ENOENT") throw new Error("OpenCode is unavailable. Install it and make sure `opencode --version` succeeds.");
|
|
161
253
|
throw error;
|
|
162
254
|
} finally {
|
|
163
255
|
clearTimeout(timer);
|
|
164
256
|
}
|
|
165
257
|
}
|
|
166
258
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
+
}
|
|
171
317
|
|
|
172
|
-
|
|
173
|
-
|
|
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
|
+
}
|
|
364
|
+
|
|
365
|
+
async function waitForHealth(baseUrl, fetchImpl, headers, timeoutMs) {
|
|
366
|
+
const deadline = Date.now() + timeoutMs;
|
|
367
|
+
while (Date.now() < deadline) {
|
|
174
368
|
try {
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
if (
|
|
180
|
-
const eventError = event.error?.data?.message ?? event.error?.message;
|
|
181
|
-
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;
|
|
182
374
|
} catch {
|
|
183
|
-
//
|
|
375
|
+
// The server can accept its socket shortly before the health route is ready.
|
|
184
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;
|
|
185
464
|
}
|
|
186
|
-
return { text, sessionId, error };
|
|
187
465
|
}
|
|
188
466
|
|
|
189
467
|
function collect(stream, limit = 10 * 1024 * 1024) {
|
|
@@ -205,12 +483,19 @@ function waitForExit(child) {
|
|
|
205
483
|
});
|
|
206
484
|
}
|
|
207
485
|
|
|
208
|
-
function terminateChild(child, platform) {
|
|
486
|
+
function terminateChild(child, platform, signal) {
|
|
209
487
|
if (platform === "win32" && child.pid) {
|
|
210
|
-
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));
|
|
211
495
|
return;
|
|
212
496
|
}
|
|
213
|
-
child.kill();
|
|
497
|
+
child.kill(signal);
|
|
214
498
|
const force = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
|
215
499
|
force.unref?.();
|
|
500
|
+
child.once("close", () => clearTimeout(force));
|
|
216
501
|
}
|
package/src/state.mjs
CHANGED
|
@@ -99,12 +99,22 @@ export async function canonicalWorkingDirectory(directory) {
|
|
|
99
99
|
|
|
100
100
|
export async function loadConfig(file = pipaPaths().config) {
|
|
101
101
|
const config = await readJson(file, "Run `pipa init` first.");
|
|
102
|
-
|
|
102
|
+
const slackMode = config.slackMode === undefined ? "socket" : config.slackMode;
|
|
103
|
+
if (slackMode !== "socket" && slackMode !== "managed") {
|
|
104
|
+
throw new Error("Invalid Pipa config: slackMode is unsupported.");
|
|
105
|
+
}
|
|
106
|
+
const requiredStrings = slackMode === "socket"
|
|
107
|
+
? ["botName", "workingDirectory", "slackAppToken", "slackBotToken"]
|
|
108
|
+
: ["botName", "workingDirectory", "openCodeHostname"];
|
|
109
|
+
for (const key of requiredStrings) {
|
|
103
110
|
if (typeof config[key] !== "string" || !config[key].trim()) {
|
|
104
111
|
throw new Error(`Invalid Pipa config: ${key} is missing.`);
|
|
105
112
|
}
|
|
106
113
|
}
|
|
107
|
-
|
|
114
|
+
if (slackMode === "managed" && (!Number.isInteger(config.openCodePort) || config.openCodePort < 1 || config.openCodePort > 65535)) {
|
|
115
|
+
throw new Error("Invalid Pipa config: openCodePort must be an integer from 1 to 65535.");
|
|
116
|
+
}
|
|
117
|
+
return { ...config, slackMode };
|
|
108
118
|
}
|
|
109
119
|
|
|
110
120
|
export async function saveConfig(config, paths = pipaPaths(), manifest = createManifest(config.botName)) {
|