@usepipa/pipa 0.4.1 → 0.4.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 +8 -2
- package/package.json +1 -1
- package/src/app.mjs +105 -37
- package/src/opencode.mjs +44 -8
package/README.md
CHANGED
|
@@ -5,8 +5,14 @@
|
|
|
5
5
|
|
|
6
6
|
Pipa runs Slack through one persistent private OpenCode server with no hosted relay, database, public endpoint, or sandbox.
|
|
7
7
|
|
|
8
|
+
[View Pipa on GitHub](https://github.com/lunchpaillola/pipa). If it is useful, star the repo so more people can find it.
|
|
9
|
+
|
|
8
10
|
**Pipa is in early preview. Features may break unintentionally, and CLI commands, configuration, and Slack behavior may continue to change.**
|
|
9
11
|
|
|
12
|
+
## Pipa Managed
|
|
13
|
+
|
|
14
|
+
Want someone to configure, run, and manage agent workflows for your company? Check out [Pipa Managed](https://usepipa.com/managed). We set up a Slack-native operations agent around how your team works, then keep its workflows running and improving over time.
|
|
15
|
+
|
|
10
16
|
## Local Socket Mode
|
|
11
17
|
|
|
12
18
|
Profiles created by `pipa init` use Socket Mode. Profiles written before mode support continue to load as Socket Mode.
|
|
@@ -41,9 +47,9 @@ pipa init
|
|
|
41
47
|
pipa start
|
|
42
48
|
```
|
|
43
49
|
|
|
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
|
|
50
|
+
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. A newer follow-up interrupts an active turn in the same thread, while other threads continue independently. While a turn is active, Pipa shows a typing status in its Slack thread.
|
|
45
51
|
|
|
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
|
|
52
|
+
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 session directory under `.pipa/artifacts` in the configured working directory. The directory is cleared before each turn, files are validated and limited to 10 files and 100 MB per file or response, and the directory is 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
53
|
|
|
48
54
|
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.
|
|
49
55
|
|
package/package.json
CHANGED
package/src/app.mjs
CHANGED
|
@@ -63,12 +63,20 @@ export async function startPipa(options = {}) {
|
|
|
63
63
|
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
64
64
|
throw error;
|
|
65
65
|
}
|
|
66
|
-
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
|
|
66
|
+
const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn, abortTurn: executor.abortTurn });
|
|
67
67
|
let accepting = true;
|
|
68
68
|
const interactions = createPendingInteractions();
|
|
69
|
+
const pendingReactions = new Map();
|
|
69
70
|
chat.onAction?.(interactions.onAction);
|
|
70
71
|
chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
|
|
71
72
|
|
|
73
|
+
const finishPendingReactions = async (conversationKey, currentMessage, emoji) => {
|
|
74
|
+
const pending = pendingReactions.get(conversationKey) ?? [];
|
|
75
|
+
if (pending.at(-1)?.message !== currentMessage) return;
|
|
76
|
+
pendingReactions.delete(conversationKey);
|
|
77
|
+
for (const entry of pending) await finishReaction(entry.thread, entry.message, entry.message === currentMessage ? emoji : "white_check_mark");
|
|
78
|
+
};
|
|
79
|
+
|
|
72
80
|
const handle = async (thread, message, subscribe) => {
|
|
73
81
|
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
|
|
74
82
|
const prompt = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
@@ -82,6 +90,9 @@ export async function startPipa(options = {}) {
|
|
|
82
90
|
if (!accepting) return;
|
|
83
91
|
|
|
84
92
|
await react(thread, message, "eyes");
|
|
93
|
+
const pending = pendingReactions.get(thread.id) ?? [];
|
|
94
|
+
pending.push({ thread, message });
|
|
95
|
+
pendingReactions.set(thread.id, pending);
|
|
85
96
|
try {
|
|
86
97
|
const interactionContext = { thread };
|
|
87
98
|
const result = await runner.enqueue(thread.id, {
|
|
@@ -94,14 +105,15 @@ export async function startPipa(options = {}) {
|
|
|
94
105
|
onPermissionReplied: interactions.onPermissionReplied,
|
|
95
106
|
onPermissionsReconciled: interactions.onPermissionsReconciled,
|
|
96
107
|
startTyping: () => thread.startTyping("Working on it..."),
|
|
97
|
-
deliver: (result) => postResult(thread, result),
|
|
108
|
+
deliver: (result, signal) => postResult(thread, result, signal),
|
|
98
109
|
deliverFailure: (error) => thread.post(error instanceof PipaStoppedError
|
|
99
110
|
? `${config.botName} stopped before finishing this request.`
|
|
100
111
|
: `${config.botName} failed: ${safeError(error)}`),
|
|
101
112
|
});
|
|
102
|
-
|
|
113
|
+
if (result.superseded) return;
|
|
114
|
+
await finishPendingReactions(thread.id, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
|
|
103
115
|
} catch (error) {
|
|
104
|
-
await
|
|
116
|
+
await finishPendingReactions(thread.id, message, "warning");
|
|
105
117
|
process.stderr.write("Pipa could not complete or deliver a Slack turn.\n");
|
|
106
118
|
}
|
|
107
119
|
};
|
|
@@ -433,47 +445,99 @@ function displayName(value) {
|
|
|
433
445
|
return name ? name[0].toUpperCase() + name.slice(1) : "";
|
|
434
446
|
}
|
|
435
447
|
|
|
436
|
-
export function createConversationRunner({ sessionStore, runTurn }) {
|
|
437
|
-
const
|
|
448
|
+
export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined }) {
|
|
449
|
+
const latest = new Map();
|
|
438
450
|
let closed = false;
|
|
439
451
|
let closeReason;
|
|
452
|
+
let closing = Promise.resolve();
|
|
440
453
|
|
|
441
454
|
function enqueue(conversationKey, input) {
|
|
442
455
|
if (closed && input.deliverFailure) return Promise.resolve(input.deliverFailure(closeReason)).then(() => ({ error: closeReason }));
|
|
443
456
|
if (closed) return Promise.reject(closeReason);
|
|
444
|
-
const previous =
|
|
445
|
-
const
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
457
|
+
const previous = latest.get(conversationKey);
|
|
458
|
+
const reason = new Error("Pipa replaced this turn with a newer message.");
|
|
459
|
+
previous?.controller.abort(reason);
|
|
460
|
+
const turn = {
|
|
461
|
+
controller: new AbortController(),
|
|
462
|
+
generation: (previous?.generation ?? 0) + 1,
|
|
463
|
+
sessionId: previous?.sessionId ?? sessionStore.get(conversationKey),
|
|
464
|
+
};
|
|
465
|
+
latest.set(conversationKey, turn);
|
|
466
|
+
turn.done = execute(conversationKey, turn, previous, input, reason);
|
|
467
|
+
void turn.done.then(
|
|
468
|
+
() => { if (latest.get(conversationKey) === turn) latest.delete(conversationKey); },
|
|
469
|
+
() => { if (latest.get(conversationKey) === turn) latest.delete(conversationKey); },
|
|
470
|
+
);
|
|
471
|
+
return turn.done;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async function execute(conversationKey, current, previous, input, abortReason) {
|
|
475
|
+
const { deliver, deliverFailure, startTyping, onSession, ...turn } = input;
|
|
476
|
+
const isLatest = () => latest.get(conversationKey)?.generation === current.generation;
|
|
477
|
+
const stopped = async () => {
|
|
478
|
+
const error = closeReason ?? current.controller.signal.reason;
|
|
479
|
+
if (!deliverFailure) throw error;
|
|
480
|
+
await deliverFailure(error);
|
|
481
|
+
return { error };
|
|
482
|
+
};
|
|
483
|
+
let result;
|
|
484
|
+
try {
|
|
485
|
+
if (previous) {
|
|
486
|
+
if (previous.sessionId) await Promise.resolve(abortTurn(previous.sessionId, abortReason)).catch(() => undefined);
|
|
487
|
+
await previous.done.catch(() => undefined);
|
|
488
|
+
current.sessionId = previous.sessionId ?? current.sessionId;
|
|
461
489
|
}
|
|
462
|
-
if (
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
490
|
+
if (!isLatest()) return { superseded: true };
|
|
491
|
+
if (closed) throw closeReason;
|
|
492
|
+
try {
|
|
493
|
+
Promise.resolve(startTyping?.()).catch(() => undefined);
|
|
494
|
+
} catch {}
|
|
495
|
+
result = await runTurn({
|
|
496
|
+
...turn,
|
|
497
|
+
signal: current.controller.signal,
|
|
498
|
+
sessionId: current.sessionId,
|
|
499
|
+
onSession: async (sessionId) => {
|
|
500
|
+
current.sessionId = sessionId;
|
|
501
|
+
await onSession?.(sessionId);
|
|
502
|
+
},
|
|
503
|
+
});
|
|
504
|
+
} catch (error) {
|
|
505
|
+
if (!isLatest()) return { superseded: true };
|
|
506
|
+
error = closed ? closeReason : error;
|
|
507
|
+
if (!deliverFailure) throw error;
|
|
508
|
+
await deliverFailure(error);
|
|
509
|
+
return { error };
|
|
510
|
+
}
|
|
511
|
+
if (!isLatest()) return { superseded: true };
|
|
512
|
+
if (current.controller.signal.aborted) return stopped();
|
|
513
|
+
if (result.sessionId) {
|
|
514
|
+
current.sessionId = result.sessionId;
|
|
515
|
+
await sessionStore.set(conversationKey, result.sessionId);
|
|
516
|
+
}
|
|
517
|
+
if (!isLatest()) return { superseded: true };
|
|
518
|
+
if (current.controller.signal.aborted) return stopped();
|
|
519
|
+
if (deliver) await deliver(result, current.controller.signal);
|
|
520
|
+
if (!isLatest()) return { superseded: true };
|
|
521
|
+
if (current.controller.signal.aborted) return stopped();
|
|
522
|
+
return result;
|
|
471
523
|
}
|
|
472
524
|
|
|
473
525
|
return {
|
|
474
526
|
enqueue,
|
|
475
|
-
close(reason = new PipaStoppedError()) {
|
|
476
|
-
|
|
527
|
+
close(reason = new PipaStoppedError()) {
|
|
528
|
+
closed = true;
|
|
529
|
+
closeReason ??= reason;
|
|
530
|
+
const aborts = [];
|
|
531
|
+
for (const turn of latest.values()) {
|
|
532
|
+
turn.controller.abort(closeReason);
|
|
533
|
+
if (turn.sessionId) aborts.push(Promise.resolve(abortTurn(turn.sessionId, closeReason)).catch(() => undefined));
|
|
534
|
+
}
|
|
535
|
+
closing = Promise.allSettled(aborts);
|
|
536
|
+
},
|
|
537
|
+
async drain() {
|
|
538
|
+
await closing;
|
|
539
|
+
while (latest.size) await Promise.allSettled([...latest.values()].map((turn) => turn.done));
|
|
540
|
+
},
|
|
477
541
|
};
|
|
478
542
|
}
|
|
479
543
|
|
|
@@ -572,7 +636,8 @@ function slackContext(thread, message) {
|
|
|
572
636
|
};
|
|
573
637
|
}
|
|
574
638
|
|
|
575
|
-
async function postResult(thread, { text, files = [] }) {
|
|
639
|
+
async function postResult(thread, { text, files = [] }, signal) {
|
|
640
|
+
if (signal?.aborted) return;
|
|
576
641
|
if (files.length) {
|
|
577
642
|
try {
|
|
578
643
|
await thread.post({ markdown: text, files });
|
|
@@ -581,8 +646,11 @@ async function postResult(thread, { text, files = [] }) {
|
|
|
581
646
|
// A failed adapter call may still have uploaded files, so retry text only.
|
|
582
647
|
}
|
|
583
648
|
}
|
|
584
|
-
if (!text) return;
|
|
585
|
-
for (const markdown of splitSlackMarkdown(text))
|
|
649
|
+
if (!text || signal?.aborted) return;
|
|
650
|
+
for (const markdown of splitSlackMarkdown(text)) {
|
|
651
|
+
if (signal?.aborted) return;
|
|
652
|
+
await thread.post({ markdown });
|
|
653
|
+
}
|
|
586
654
|
}
|
|
587
655
|
|
|
588
656
|
function splitSlackMarkdown(text, limit = 3500) {
|
package/src/opencode.mjs
CHANGED
|
@@ -88,6 +88,7 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
88
88
|
const remove = options.rm ?? rm;
|
|
89
89
|
const artifactRoot = options.artifactRoot;
|
|
90
90
|
const active = new Set();
|
|
91
|
+
const activeSessions = new Map();
|
|
91
92
|
let stopReason;
|
|
92
93
|
|
|
93
94
|
async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
|
|
@@ -125,25 +126,21 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
125
126
|
}
|
|
126
127
|
}
|
|
127
128
|
|
|
128
|
-
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [], onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
|
|
129
|
+
async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
|
|
129
130
|
if (!prompt?.trim()) throw new Error("A prompt is required.");
|
|
130
131
|
if (stopReason) throw stopReason;
|
|
131
132
|
const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
|
|
132
133
|
const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
|
|
133
134
|
const controller = new AbortController();
|
|
135
|
+
const abort = () => controller.abort(signal.reason);
|
|
136
|
+
if (signal?.aborted) abort();
|
|
137
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
134
138
|
const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
|
|
135
139
|
active.add(controller);
|
|
136
140
|
let artifactDirectory;
|
|
137
141
|
|
|
138
142
|
try {
|
|
139
143
|
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
144
|
const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls, controller.signal);
|
|
148
145
|
if (stopReason) throw stopReason;
|
|
149
146
|
let selectedSessionId = sessionId;
|
|
@@ -168,7 +165,19 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
168
165
|
messages = [];
|
|
169
166
|
}
|
|
170
167
|
|
|
168
|
+
activeSessions.set(selectedSessionId, { controller, workingDirectory });
|
|
171
169
|
await onSession?.(selectedSessionId);
|
|
170
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
171
|
+
|
|
172
|
+
if (slackTurn && !useDataUrls && artifactRoot) {
|
|
173
|
+
try {
|
|
174
|
+
await mkdir(artifactRoot, { recursive: true, mode: 0o700 });
|
|
175
|
+
artifactDirectory = await sessionArtifactDirectory(artifactRoot, selectedSessionId, workingDirectory);
|
|
176
|
+
await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
177
|
+
await mkdir(artifactDirectory, { mode: 0o700 });
|
|
178
|
+
await chmod(artifactDirectory, 0o700);
|
|
179
|
+
} catch {}
|
|
180
|
+
}
|
|
172
181
|
|
|
173
182
|
const baseline = new Set(messages.map((message) => message?.info?.id).filter(Boolean));
|
|
174
183
|
let dismissed = false;
|
|
@@ -222,6 +231,9 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
222
231
|
clearTimeout(timer);
|
|
223
232
|
controller.abort(new Error("OpenCode turn completed."));
|
|
224
233
|
active.delete(controller);
|
|
234
|
+
for (const [sessionId, turn] of activeSessions) {
|
|
235
|
+
if (turn.controller === controller) activeSessions.delete(sessionId);
|
|
236
|
+
}
|
|
225
237
|
}
|
|
226
238
|
} catch (error) {
|
|
227
239
|
if (stopReason) throw stopReason;
|
|
@@ -241,11 +253,25 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
241
253
|
process.stderr.write("Pipa could not remove temporary artifact files.\n");
|
|
242
254
|
}
|
|
243
255
|
}
|
|
256
|
+
signal?.removeEventListener("abort", abort);
|
|
244
257
|
}
|
|
245
258
|
}
|
|
246
259
|
|
|
247
260
|
return {
|
|
248
261
|
runTurn,
|
|
262
|
+
async abortTurn(sessionId, reason = new Error("OpenCode turn aborted.")) {
|
|
263
|
+
const turn = activeSessions.get(sessionId);
|
|
264
|
+
if (!turn) return;
|
|
265
|
+
const abortController = new AbortController();
|
|
266
|
+
try {
|
|
267
|
+
await request(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, turn.workingDirectory, abortController, [200, 204, 404], false);
|
|
268
|
+
} catch {
|
|
269
|
+
// Local cancellation still supersedes the turn if OpenCode's abort request fails.
|
|
270
|
+
} finally {
|
|
271
|
+
abortController.abort(reason);
|
|
272
|
+
turn.controller.abort(reason);
|
|
273
|
+
}
|
|
274
|
+
},
|
|
249
275
|
stopAll(reason = new PipaStoppedError()) {
|
|
250
276
|
stopReason ??= reason;
|
|
251
277
|
for (const controller of active) controller.abort(stopReason);
|
|
@@ -253,6 +279,16 @@ export function createOpenCodeExecutor(options = {}) {
|
|
|
253
279
|
};
|
|
254
280
|
}
|
|
255
281
|
|
|
282
|
+
async function sessionArtifactDirectory(root, sessionId, workingDirectory) {
|
|
283
|
+
if (!/^[A-Za-z0-9_-]{1,200}$/u.test(sessionId)) throw new Error("OpenCode returned an invalid session ID.");
|
|
284
|
+
const stats = await lstat(root);
|
|
285
|
+
if (!stats.isDirectory() || stats.isSymbolicLink()) throw new Error("Pipa's artifact root must be a directory, not a symlink.");
|
|
286
|
+
const [resolvedRoot, resolvedWorkingDirectory] = await Promise.all([realpath(root), realpath(workingDirectory)]);
|
|
287
|
+
const relative = path.relative(resolvedWorkingDirectory, resolvedRoot);
|
|
288
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error("Pipa's artifact root must be inside the working directory.");
|
|
289
|
+
return path.join(resolvedRoot, sessionId);
|
|
290
|
+
}
|
|
291
|
+
|
|
256
292
|
export function startOpenCodeServer(config, options = {}) {
|
|
257
293
|
const spawn = options.spawn ?? crossSpawn;
|
|
258
294
|
const platform = options.platform ?? process.platform;
|