@usepipa/pipa 0.2.0 → 0.2.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 +1 -3
- package/package.json +1 -1
- package/src/app.mjs +9 -3
- package/src/opencode.mjs +89 -26
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ pipa init
|
|
|
37
37
|
pipa start
|
|
38
38
|
```
|
|
39
39
|
|
|
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 do not need another mention.
|
|
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 do not need 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
41
|
|
|
42
42
|
To use an existing OpenCode server instead of starting standalone OpenCode runs, set its URL before starting Pipa:
|
|
43
43
|
|
|
@@ -54,8 +54,6 @@ pipa start Connect Slack Socket Mode to local OpenCode
|
|
|
54
54
|
pipa --version Print the installed version
|
|
55
55
|
```
|
|
56
56
|
|
|
57
|
-
Pipa v0.1 is text-only. File handling, DMs, interactive questions, schedulers, and hosted fallback are not included.
|
|
58
|
-
|
|
59
57
|
## Development
|
|
60
58
|
|
|
61
59
|
```sh
|
package/package.json
CHANGED
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, runOpenCodeVersion } from "./opencode.mjs";
|
|
5
|
+
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, runOpenCodeVersion } from "./opencode.mjs";
|
|
6
6
|
|
|
7
7
|
export async function initializePipa(input, options = {}) {
|
|
8
8
|
const paths = options.paths ?? pipaPaths();
|
|
@@ -50,13 +50,19 @@ export async function startPipa(options = {}) {
|
|
|
50
50
|
if (!accepting || shouldIgnore(thread, message)) return;
|
|
51
51
|
const prompt = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
52
52
|
if (!prompt) return;
|
|
53
|
+
const attachments = message.attachments ?? [];
|
|
53
54
|
if (subscribe) await thread.subscribe();
|
|
55
|
+
if (attachments.some(({ size }) => size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_ATTACHMENT_BYTES))) {
|
|
56
|
+
await thread.post("Pipa can read files up to 100 MB each.");
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
54
59
|
if (!accepting) return;
|
|
55
60
|
|
|
56
61
|
await react(thread, message, "eyes");
|
|
57
62
|
try {
|
|
58
63
|
const result = await runner.enqueue(thread.id, {
|
|
59
64
|
prompt,
|
|
65
|
+
attachments,
|
|
60
66
|
workingDirectory: config.workingDirectory,
|
|
61
67
|
contextEnvironment: slackContext(thread, message),
|
|
62
68
|
deliver: (text) => postInChunks(thread, text),
|
|
@@ -168,7 +174,7 @@ function shouldIgnore(thread, message) {
|
|
|
168
174
|
|| message.author?.isBot
|
|
169
175
|
|| thread.channel?.isDM
|
|
170
176
|
|| thread.channel?.channelVisibility === "external"
|
|
171
|
-
|| Boolean(message.raw?.subtype)
|
|
177
|
+
|| Boolean(message.raw?.subtype && message.raw.subtype !== "file_share")
|
|
172
178
|
|| !message.text?.trim();
|
|
173
179
|
}
|
|
174
180
|
|
|
@@ -199,7 +205,7 @@ function slackContext(thread, message) {
|
|
|
199
205
|
|
|
200
206
|
async function postInChunks(thread, text) {
|
|
201
207
|
for (let index = 0; index < text.length; index += 3500) {
|
|
202
|
-
await thread.post(text.slice(index, index + 3500));
|
|
208
|
+
await thread.post({ markdown: text.slice(index, index + 3500) });
|
|
203
209
|
}
|
|
204
210
|
}
|
|
205
211
|
|
package/src/opencode.mjs
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import crossSpawn from "cross-spawn";
|
|
2
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
2
5
|
|
|
3
6
|
const SECRET_ENV_KEYS = new Set([
|
|
4
7
|
"PIPA_SLACK_APP_TOKEN",
|
|
@@ -7,14 +10,17 @@ const SECRET_ENV_KEYS = new Set([
|
|
|
7
10
|
"SLACK_BOT_TOKEN",
|
|
8
11
|
]);
|
|
9
12
|
|
|
13
|
+
export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
|
|
14
|
+
|
|
10
15
|
export function cleanChildEnvironment(environment = process.env) {
|
|
11
16
|
return Object.fromEntries(Object.entries(environment).filter(([key]) => !SECRET_ENV_KEYS.has(key.toUpperCase())));
|
|
12
17
|
}
|
|
13
18
|
|
|
14
|
-
export function buildRunArguments({ prompt, sessionId, workingDirectory, attachUrl }) {
|
|
19
|
+
export function buildRunArguments({ prompt, sessionId, workingDirectory, attachUrl, files = [] }) {
|
|
15
20
|
const args = ["run", "--format", "json", "--dir", workingDirectory];
|
|
16
21
|
if (attachUrl) args.push("--attach", attachUrl);
|
|
17
22
|
if (sessionId) args.push("--session", sessionId);
|
|
23
|
+
for (const file of files) args.push("--file", file);
|
|
18
24
|
args.push("--", prompt);
|
|
19
25
|
return args;
|
|
20
26
|
}
|
|
@@ -26,50 +32,107 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
26
32
|
const attachUrl = options.attachUrl ?? environment.PIPA_OPENCODE_ATTACH_URL?.trim();
|
|
27
33
|
const timeoutMs = options.timeoutMs ?? 2.5 * 60 * 60 * 1000;
|
|
28
34
|
const children = new Set();
|
|
35
|
+
let stopped = false;
|
|
29
36
|
|
|
30
|
-
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {} }) {
|
|
37
|
+
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [] }) {
|
|
31
38
|
if (!prompt?.trim()) throw new Error("A prompt is required.");
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
shell: false,
|
|
36
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
37
|
-
});
|
|
38
|
-
children.add(child);
|
|
39
|
-
const exit = waitForExit(child);
|
|
40
|
-
void exit.finally(() => children.delete(child)).catch(() => undefined);
|
|
41
|
-
let timer;
|
|
39
|
+
if (stopped) throw new Error("Pipa is shutting down.");
|
|
40
|
+
const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
|
|
41
|
+
let turnError;
|
|
42
42
|
|
|
43
43
|
try {
|
|
44
|
-
const
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
44
|
+
const files = [];
|
|
45
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
46
|
+
let data;
|
|
47
|
+
try {
|
|
48
|
+
data = await fetchAttachment(attachment, timeoutMs);
|
|
49
|
+
} catch {
|
|
50
|
+
throw new Error("Could not read one of the attached files. Please try uploading it again.");
|
|
51
|
+
}
|
|
52
|
+
if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 100 MB or smaller.");
|
|
53
|
+
try {
|
|
54
|
+
const sanitizedName = path.basename(attachment.name || "attachment")
|
|
55
|
+
.replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "_")
|
|
56
|
+
.replace(/[. ]+$/u, "");
|
|
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.");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (stopped) throw new Error("Pipa is shutting down.");
|
|
70
|
+
const child = spawn("opencode", buildRunArguments({ prompt, sessionId, workingDirectory, attachUrl, files }), {
|
|
71
|
+
cwd: workingDirectory,
|
|
72
|
+
env: { ...cleanChildEnvironment(environment), ...contextEnvironment },
|
|
73
|
+
shell: false,
|
|
74
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
50
75
|
});
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
76
|
+
children.add(child);
|
|
77
|
+
const exit = waitForExit(child);
|
|
78
|
+
void exit.finally(() => children.delete(child)).catch(() => undefined);
|
|
79
|
+
let timer;
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const operation = Promise.all([collect(child.stdout), collect(child.stderr), exit]);
|
|
83
|
+
const timeout = new Promise((_, reject) => {
|
|
84
|
+
timer = setTimeout(() => {
|
|
85
|
+
terminateChild(child, platform);
|
|
86
|
+
reject(new Error(`OpenCode timed out after ${timeoutMs}ms.`));
|
|
87
|
+
}, timeoutMs);
|
|
88
|
+
});
|
|
89
|
+
const [stdout, stderr, code] = await Promise.race([operation, timeout]);
|
|
90
|
+
const output = parseOpenCodeOutput(stdout);
|
|
91
|
+
if (output.error) throw new Error(output.error);
|
|
92
|
+
if (code !== 0) throw new Error(output.error || stderr.trim() || `OpenCode exited with code ${code}.`);
|
|
93
|
+
if (!output.text) throw new Error("OpenCode completed without assistant text.");
|
|
94
|
+
return { text: output.text, sessionId: output.sessionId ?? sessionId ?? null };
|
|
95
|
+
} catch (error) {
|
|
96
|
+
terminateChild(child, platform);
|
|
97
|
+
await exit.catch(() => undefined);
|
|
98
|
+
throw error;
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
}
|
|
57
102
|
} catch (error) {
|
|
58
|
-
|
|
103
|
+
turnError = error;
|
|
59
104
|
throw error;
|
|
60
105
|
} finally {
|
|
61
|
-
|
|
106
|
+
if (temporaryDirectory) {
|
|
107
|
+
try {
|
|
108
|
+
await rm(temporaryDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (!turnError) throw error;
|
|
111
|
+
process.stderr.write("Pipa could not remove temporary attachment files.\n");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
62
114
|
}
|
|
63
115
|
}
|
|
64
116
|
|
|
65
117
|
return {
|
|
66
118
|
runTurn,
|
|
67
119
|
stopAll() {
|
|
120
|
+
stopped = true;
|
|
68
121
|
for (const child of children) terminateChild(child, platform);
|
|
69
122
|
},
|
|
70
123
|
};
|
|
71
124
|
}
|
|
72
125
|
|
|
126
|
+
function fetchAttachment(attachment, timeoutMs) {
|
|
127
|
+
let timer;
|
|
128
|
+
return Promise.race([
|
|
129
|
+
attachment.fetchData(),
|
|
130
|
+
new Promise((_, reject) => {
|
|
131
|
+
timer = setTimeout(() => reject(new Error(`Attachment download timed out after ${timeoutMs}ms.`)), timeoutMs);
|
|
132
|
+
}),
|
|
133
|
+
]).finally(() => clearTimeout(timer));
|
|
134
|
+
}
|
|
135
|
+
|
|
73
136
|
export async function runOpenCodeVersion(options = {}) {
|
|
74
137
|
const spawn = options.spawn ?? crossSpawn;
|
|
75
138
|
const platform = options.platform ?? process.platform;
|