@usepipa/pipa 0.4.0 → 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 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.
@@ -33,7 +39,7 @@ npm install --global @usepipa/pipa
33
39
  pipa init
34
40
  ```
35
41
 
36
- `pipa init` guides you through creating and installing the Slack app and saving its local configuration.
42
+ `pipa init` guides you through creating and installing the Slack app and saving its local configuration. The generated manifest includes `channels:read` and `assistant:write`. If an existing installation has not granted a recommended scope, `pipa init` and `pipa start` print reauthorization guidance but continue running.
37
43
 
38
44
  3. Start Pipa:
39
45
 
@@ -41,7 +47,11 @@ 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. 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.
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.
51
+
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.
53
+
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.
45
55
 
46
56
  ### Access control
47
57
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usepipa/pipa",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "Run Pipa through Slack Socket Mode with OpenCode",
5
5
  "keywords": [
6
6
  "slack",
package/src/app.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
2
3
  import { Chat, Modal, TextInput } from "chat";
3
4
  import { createSlackAdapter } from "@chat-adapter/slack";
4
5
  import { createMemoryState } from "@chat-adapter/state-memory";
@@ -19,7 +20,8 @@ export async function initializePipa(input, options = {}) {
19
20
  const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
20
21
  if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
21
22
  await (options.checkSlackAppToken ?? checkSlackAppToken)(config.slackAppToken);
22
- await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
23
+ const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
24
+ warnMissingSlackScopes(slackAuth, options.warn);
23
25
 
24
26
  await saveConfig(config, paths, manifest);
25
27
  return { config, manifest, paths };
@@ -28,7 +30,8 @@ export async function initializePipa(input, options = {}) {
28
30
  export async function startPipa(options = {}) {
29
31
  const paths = options.paths ?? pipaPaths();
30
32
  const config = options.config ?? await loadConfig(paths.config);
31
- await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
33
+ const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
34
+ warnMissingSlackScopes(slackAuth, options.warn);
32
35
  const sessionStore = options.sessionStore ?? await createSessionStore(paths.sessions);
33
36
  const state = options.state ?? createMemoryState();
34
37
  const chat = options.chat ?? new Chat({
@@ -51,6 +54,7 @@ export async function startPipa(options = {}) {
51
54
  let executor;
52
55
  try {
53
56
  executor = options.executor ?? (options.createExecutor ?? createOpenCodeExecutor)({
57
+ artifactRoot: path.join(config.workingDirectory, ".pipa", "artifacts"),
54
58
  baseUrl: server.baseUrl,
55
59
  onFatal: server.fail,
56
60
  });
@@ -59,12 +63,20 @@ export async function startPipa(options = {}) {
59
63
  await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
60
64
  throw error;
61
65
  }
62
- const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
66
+ const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn, abortTurn: executor.abortTurn });
63
67
  let accepting = true;
64
68
  const interactions = createPendingInteractions();
69
+ const pendingReactions = new Map();
65
70
  chat.onAction?.(interactions.onAction);
66
71
  chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
67
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
+
68
80
  const handle = async (thread, message, subscribe) => {
69
81
  if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
70
82
  const prompt = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
@@ -78,6 +90,9 @@ export async function startPipa(options = {}) {
78
90
  if (!accepting) return;
79
91
 
80
92
  await react(thread, message, "eyes");
93
+ const pending = pendingReactions.get(thread.id) ?? [];
94
+ pending.push({ thread, message });
95
+ pendingReactions.set(thread.id, pending);
81
96
  try {
82
97
  const interactionContext = { thread };
83
98
  const result = await runner.enqueue(thread.id, {
@@ -89,14 +104,16 @@ export async function startPipa(options = {}) {
89
104
  onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
90
105
  onPermissionReplied: interactions.onPermissionReplied,
91
106
  onPermissionsReconciled: interactions.onPermissionsReconciled,
92
- deliver: (text) => postInChunks(thread, text),
107
+ startTyping: () => thread.startTyping("Working on it..."),
108
+ deliver: (result, signal) => postResult(thread, result, signal),
93
109
  deliverFailure: (error) => thread.post(error instanceof PipaStoppedError
94
110
  ? `${config.botName} stopped before finishing this request.`
95
111
  : `${config.botName} failed: ${safeError(error)}`),
96
112
  });
97
- await finishReaction(thread, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
113
+ if (result.superseded) return;
114
+ await finishPendingReactions(thread.id, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
98
115
  } catch (error) {
99
- await finishReaction(thread, message, "warning");
116
+ await finishPendingReactions(thread.id, message, "warning");
100
117
  process.stderr.write("Pipa could not complete or deliver a Slack turn.\n");
101
118
  }
102
119
  };
@@ -428,44 +445,99 @@ function displayName(value) {
428
445
  return name ? name[0].toUpperCase() + name.slice(1) : "";
429
446
  }
430
447
 
431
- export function createConversationRunner({ sessionStore, runTurn }) {
432
- const tails = new Map();
448
+ export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined }) {
449
+ const latest = new Map();
433
450
  let closed = false;
434
451
  let closeReason;
452
+ let closing = Promise.resolve();
435
453
 
436
454
  function enqueue(conversationKey, input) {
437
455
  if (closed && input.deliverFailure) return Promise.resolve(input.deliverFailure(closeReason)).then(() => ({ error: closeReason }));
438
456
  if (closed) return Promise.reject(closeReason);
439
- const previous = tails.get(conversationKey) ?? Promise.resolve();
440
- const current = previous.catch(() => undefined).then(async () => {
441
- const { deliver, deliverFailure, ...turn } = input;
442
- let result;
443
- try {
444
- if (closed) throw closeReason;
445
- result = await runTurn({ ...turn, sessionId: sessionStore.get(conversationKey) });
446
- if (result.sessionId) await sessionStore.set(conversationKey, result.sessionId);
447
- } catch (error) {
448
- if (deliverFailure) {
449
- await deliverFailure(error);
450
- return { error };
451
- }
452
- throw error;
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;
453
489
  }
454
- if (deliver) await deliver(result.text);
455
- return result;
456
- });
457
- const tail = current.then(() => undefined, () => undefined);
458
- tails.set(conversationKey, tail);
459
- tail.finally(() => {
460
- if (tails.get(conversationKey) === tail) tails.delete(conversationKey);
461
- });
462
- return current;
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;
463
523
  }
464
524
 
465
525
  return {
466
526
  enqueue,
467
- close(reason = new PipaStoppedError()) { closed = true; closeReason ??= reason; },
468
- drain: () => Promise.all([...tails.values()]),
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
+ },
469
541
  };
470
542
  }
471
543
 
@@ -478,7 +550,10 @@ export async function checkSlackToken(token, fetchImpl = fetch) {
478
550
  });
479
551
  const result = await response.json();
480
552
  if (!response.ok || !result.ok) throw new Error("Slack rejected the bot token.");
481
- return result;
553
+ const headerScopes = response.headers?.get?.("x-oauth-scopes");
554
+ const grantedScopes = normalizeGrantedScopes(typeof headerScopes === "string" ? headerScopes.split(",") : undefined)
555
+ ?? normalizeGrantedScopes(result.response_metadata?.scopes);
556
+ return grantedScopes === undefined ? result : { ...result, grantedScopes };
482
557
  }
483
558
 
484
559
  export async function checkSlackAppToken(token, fetchImpl = fetch) {
@@ -530,6 +605,22 @@ function requireToken(value, label, prefix) {
530
605
  return token;
531
606
  }
532
607
 
608
+ function normalizeGrantedScopes(value) {
609
+ if (Array.isArray(value) && value.every((scope) => typeof scope === "string" && scope.trim())) {
610
+ return [...new Set(value.map((scope) => scope.trim()))];
611
+ }
612
+ }
613
+
614
+ function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`${message}\n`)) {
615
+ if (!Array.isArray(auth?.grantedScopes)) return;
616
+ const missing = ["channels:read", "assistant:write"].filter((scope) => !auth.grantedScopes.includes(scope));
617
+ if (!missing.length) return;
618
+ const scopes = missing.join(", ");
619
+ try {
620
+ warn(`Pipa warning: Slack bot token is missing recommended ${missing.length === 1 ? "scope" : "scopes"} ${scopes}. Add ${missing.length === 1 ? "it" : "them"} and reinstall or reauthorize the Slack app.`);
621
+ } catch {}
622
+ }
623
+
533
624
  function safeError(error) {
534
625
  const message = error instanceof Error ? error.message : String(error);
535
626
  return message.replace(/xox[baprs]-[^\s]+|xapp-[^\s]+/gu, "[redacted]");
@@ -545,10 +636,63 @@ function slackContext(thread, message) {
545
636
  };
546
637
  }
547
638
 
548
- async function postInChunks(thread, text) {
549
- for (let index = 0; index < text.length; index += 3500) {
550
- await thread.post({ markdown: text.slice(index, index + 3500) });
639
+ async function postResult(thread, { text, files = [] }, signal) {
640
+ if (signal?.aborted) return;
641
+ if (files.length) {
642
+ try {
643
+ await thread.post({ markdown: text, files });
644
+ return;
645
+ } catch {
646
+ // A failed adapter call may still have uploaded files, so retry text only.
647
+ }
648
+ }
649
+ if (!text || signal?.aborted) return;
650
+ for (const markdown of splitSlackMarkdown(text)) {
651
+ if (signal?.aborted) return;
652
+ await thread.post({ markdown });
653
+ }
654
+ }
655
+
656
+ function splitSlackMarkdown(text, limit = 3500) {
657
+ if (text.length <= limit) return [text];
658
+ const chunks = [];
659
+ let chunk = "";
660
+ let fence = "";
661
+ const append = (line) => {
662
+ const separator = chunk ? "\n" : "";
663
+ const closing = fence ? `\n${fence}` : "";
664
+ if (chunk && chunk.length + separator.length + line.length + closing.length > limit) {
665
+ chunks.push(chunk + closing);
666
+ chunk = fence ? `${fence}\n${line}` : line;
667
+ } else {
668
+ chunk += separator + line;
669
+ }
670
+ const marker = line.match(/^ {0,3}(```+|~~~+)/u)?.[0];
671
+ if (marker) fence = fence ? "" : marker;
672
+ };
673
+ for (const inputLine of text.split("\n")) {
674
+ let line = inputLine;
675
+ const emptyChunkLimit = limit - (fence ? (2 * fence.length) + 2 : 0);
676
+ if (line.length <= emptyChunkLimit) {
677
+ append(line);
678
+ continue;
679
+ }
680
+ if (chunk) {
681
+ chunks.push(chunk + (fence ? `\n${fence}` : ""));
682
+ chunk = fence ? `${fence}\n` : "";
683
+ }
684
+ const room = Math.max(1, limit - chunk.length - (fence ? fence.length + 1 : 0));
685
+ while (line.length > room) {
686
+ const boundary = line.slice(0, room + 1).search(/\s+\S*$/u);
687
+ const splitAt = boundary > 0 ? boundary : room;
688
+ chunks.push(chunk + line.slice(0, splitAt) + (fence ? `\n${fence}` : ""));
689
+ line = line.slice(splitAt).replace(/^\s+/u, "");
690
+ chunk = fence ? `${fence}\n` : "";
691
+ }
692
+ chunk += line;
551
693
  }
694
+ if (chunk) chunks.push(chunk + (fence ? `\n${fence}` : ""));
695
+ return chunks;
552
696
  }
553
697
 
554
698
  async function react(thread, message, emoji) {
package/src/opencode.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import crossSpawn from "cross-spawn";
2
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { chmod, lstat, mkdir, mkdtemp, open, realpath, rm, writeFile } from "node:fs/promises";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
5
6
  import { pathToFileURL } from "node:url";
@@ -13,6 +14,10 @@ const SECRET_ENV_KEYS = new Set([
13
14
  const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
14
15
 
15
16
  export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
17
+ const ARTIFACT_MARKER = "PIPA_ARTIFACTS:";
18
+ const MAX_ARTIFACT_DECLARATION_BYTES = 8 * 1024;
19
+ const MAX_ARTIFACT_PATH_BYTES = 1024;
20
+ const MAX_ARTIFACT_FILES = 10;
16
21
 
17
22
  export class PipaStoppedError extends Error {
18
23
  constructor(message = "Pipa is shutting down.") {
@@ -80,7 +85,10 @@ export function createOpenCodeExecutor(options = {}) {
80
85
  const requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
81
86
  const pollIntervalMs = options.pollIntervalMs ?? 1_000;
82
87
  const useDataUrls = !isLoopbackUrl(baseUrl);
88
+ const remove = options.rm ?? rm;
89
+ const artifactRoot = options.artifactRoot;
83
90
  const active = new Set();
91
+ const activeSessions = new Map();
84
92
  let stopReason;
85
93
 
86
94
  async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
@@ -118,20 +126,23 @@ export function createOpenCodeExecutor(options = {}) {
118
126
  }
119
127
  }
120
128
 
121
- 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 }) {
122
130
  if (!prompt?.trim()) throw new Error("A prompt is required.");
123
131
  if (stopReason) throw stopReason;
124
132
  const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
125
- let turnError;
133
+ const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
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 });
138
+ const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
139
+ active.add(controller);
140
+ let artifactDirectory;
126
141
 
127
142
  try {
128
- const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls);
129
- if (stopReason) throw stopReason;
130
- const controller = new AbortController();
131
- const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
132
- active.add(controller);
133
-
134
143
  try {
144
+ const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls, controller.signal);
145
+ if (stopReason) throw stopReason;
135
146
  let selectedSessionId = sessionId;
136
147
  let messages;
137
148
  if (selectedSessionId) {
@@ -154,7 +165,19 @@ export function createOpenCodeExecutor(options = {}) {
154
165
  messages = [];
155
166
  }
156
167
 
168
+ activeSessions.set(selectedSessionId, { controller, workingDirectory });
157
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
+ }
158
181
 
159
182
  const baseline = new Set(messages.map((message) => message?.info?.id).filter(Boolean));
160
183
  let dismissed = false;
@@ -179,7 +202,7 @@ export function createOpenCodeExecutor(options = {}) {
179
202
  }
180
203
  await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
181
204
  method: "POST",
182
- body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment)),
205
+ body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment, artifactDirectory)),
183
206
  }, workingDirectory, controller, [204]);
184
207
 
185
208
  while (true) {
@@ -194,7 +217,13 @@ export function createOpenCodeExecutor(options = {}) {
194
217
  if (finalMessage && (status === "idle" || (!status && finalMessage.completed))) {
195
218
  if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
196
219
  if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
197
- return { text: finalMessage.text, sessionId: selectedSessionId };
220
+ const parsed = slackTurn ? parseArtifactDeclaration(finalMessage.text) : { text: finalMessage.text };
221
+ const artifacts = artifactDirectory && parsed.paths ? await readArtifacts(artifactDirectory, parsed.paths, options.onArtifactOpened) : [];
222
+ return {
223
+ text: parsed.text,
224
+ sessionId: selectedSessionId,
225
+ ...(artifacts.length ? { files: artifacts } : {}),
226
+ };
198
227
  }
199
228
  await delay(pollIntervalMs, controller.signal);
200
229
  }
@@ -202,25 +231,47 @@ export function createOpenCodeExecutor(options = {}) {
202
231
  clearTimeout(timer);
203
232
  controller.abort(new Error("OpenCode turn completed."));
204
233
  active.delete(controller);
234
+ for (const [sessionId, turn] of activeSessions) {
235
+ if (turn.controller === controller) activeSessions.delete(sessionId);
236
+ }
205
237
  }
206
238
  } catch (error) {
207
- turnError = error;
208
239
  if (stopReason) throw stopReason;
209
240
  throw error;
210
241
  } finally {
211
242
  if (temporaryDirectory) {
212
243
  try {
213
- await rm(temporaryDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
214
- } catch (error) {
215
- if (!turnError) throw error;
244
+ await remove(temporaryDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
245
+ } catch {
216
246
  process.stderr.write("Pipa could not remove temporary attachment files.\n");
217
247
  }
218
248
  }
249
+ if (artifactDirectory) {
250
+ try {
251
+ await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
252
+ } catch {
253
+ process.stderr.write("Pipa could not remove temporary artifact files.\n");
254
+ }
255
+ }
256
+ signal?.removeEventListener("abort", abort);
219
257
  }
220
258
  }
221
259
 
222
260
  return {
223
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
+ },
224
275
  stopAll(reason = new PipaStoppedError()) {
225
276
  stopReason ??= reason;
226
277
  for (const controller of active) controller.abort(stopReason);
@@ -228,6 +279,16 @@ export function createOpenCodeExecutor(options = {}) {
228
279
  };
229
280
  }
230
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
+
231
292
  export function startOpenCodeServer(config, options = {}) {
232
293
  const spawn = options.spawn ?? crossSpawn;
233
294
  const platform = options.platform ?? process.platform;
@@ -286,24 +347,18 @@ export async function runOpenCodeVersion(options = {}) {
286
347
  }
287
348
  }
288
349
 
289
- async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls) {
350
+ async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls, signal) {
290
351
  const files = [];
291
352
  for (const [index, attachment] of attachments.entries()) {
292
353
  let data;
293
354
  try {
294
- data = await fetchAttachment(attachment, timeoutMs);
355
+ data = await fetchAttachment(attachment, timeoutMs, signal);
295
356
  } catch {
296
357
  throw new Error("Could not read one of the attached files. Please try uploading it again.");
297
358
  }
298
359
  if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 100 MB or smaller.");
299
360
  try {
300
- const sanitizedName = path.basename(attachment.name || "attachment")
301
- .replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "_")
302
- .replace(/[. ]+$/u, "");
303
- const filename = Array.from(sanitizedName).reduce(
304
- (result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result,
305
- "",
306
- ) || "attachment";
361
+ const filename = sanitizeFilename(path.basename(attachment.name || "attachment"), "attachment");
307
362
  const file = path.join(temporaryDirectory, `${index + 1}-${filename}`);
308
363
  await writeFile(file, data);
309
364
  const mime = attachment.mimeType || "application/octet-stream";
@@ -319,15 +374,96 @@ async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useD
319
374
  return files;
320
375
  }
321
376
 
322
- function promptBody(prompt, files, contextEnvironment) {
377
+ function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
323
378
  const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
324
379
  const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
380
+ const instructions = [];
381
+ if (context.length) instructions.push(`Slack context for this turn (provided here, not as shell environment variables):\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}`);
382
+ if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
383
+ instructions.push("Keep naturally short answers inline. For deeper work or larger deliverables, keep the Slack response concise and use the most suitable artifact format.");
384
+ if (artifactDirectory) instructions.push(`To attach files, copy up to 10 top-level files (100 MB total) to this private artifact directory: ${artifactDirectory}\nEnd with exactly one final line: ${ARTIFACT_MARKER} [\"report.csv\",\"brief.pdf\"]`);
385
+ }
325
386
  return {
326
387
  parts,
327
- ...(context.length ? { system: `Slack context for this turn (provided here, not as shell environment variables):\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}` } : {}),
388
+ ...(instructions.length ? { system: instructions.join("\n\n") } : {}),
328
389
  };
329
390
  }
330
391
 
392
+ function parseArtifactDeclaration(text) {
393
+ const lines = text.split(/\r?\n/u);
394
+ const declarations = lines.map((line, index) => line.startsWith(ARTIFACT_MARKER) ? { line, index } : null).filter(Boolean);
395
+ const cleanText = lines.filter((line) => !line.startsWith(ARTIFACT_MARKER)).join("\n").trim();
396
+ const lastNonblank = lines.findLastIndex((line) => line.trim());
397
+ if (declarations.length !== 1 || declarations[0].index !== lastNonblank) return { text: cleanText };
398
+ const declaration = declarations[0].line;
399
+ if (!declaration.startsWith(`${ARTIFACT_MARKER} `) || Buffer.byteLength(declaration) > MAX_ARTIFACT_DECLARATION_BYTES) return { text: cleanText };
400
+ let paths;
401
+ try {
402
+ paths = JSON.parse(declaration.slice(ARTIFACT_MARKER.length + 1));
403
+ } catch {
404
+ return { text: cleanText };
405
+ }
406
+ if (!Array.isArray(paths) || !paths.length || paths.length > MAX_ARTIFACT_FILES || paths.some((item) => typeof item !== "string")) return { text: cleanText };
407
+ if (new Set(paths).size !== paths.length || paths.some((item) => !validArtifactPath(item))) return { text: cleanText };
408
+ return { text: cleanText, paths };
409
+ }
410
+
411
+ function validArtifactPath(value) {
412
+ if (!value || Buffer.byteLength(value) > MAX_ARTIFACT_PATH_BYTES || value.includes("\0") || value.includes("\\") || path.isAbsolute(value)) return false;
413
+ const parts = value.split("/");
414
+ return parts.length === 1 && parts[0] !== "." && parts[0] !== "..";
415
+ }
416
+
417
+ async function readArtifacts(directory, paths, onOpened) {
418
+ const files = [];
419
+ let total = 0;
420
+ try {
421
+ const root = await realpath(directory);
422
+ for (const relativePath of paths) {
423
+ const filename = path.resolve(root, relativePath);
424
+ if (!filename.startsWith(`${root}${path.sep}`)) throw new Error("Artifact path escaped its directory.");
425
+ let current = root;
426
+ for (const part of relativePath.split("/")) {
427
+ current = path.join(current, part);
428
+ if ((await lstat(current)).isSymbolicLink()) throw new Error("Artifact path contains a symbolic link.");
429
+ }
430
+ const handle = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
431
+ try {
432
+ const before = await handle.stat({ bigint: true });
433
+ await onOpened?.(filename);
434
+ const size = Number(before.size);
435
+ if (!before.isFile() || size > MAX_ATTACHMENT_BYTES || total + size > MAX_ATTACHMENT_BYTES) throw new Error("Artifact exceeds delivery limits.");
436
+ const data = Buffer.alloc(size + 1);
437
+ let bytesRead = 0;
438
+ while (bytesRead < data.length) {
439
+ const read = await handle.read(data, bytesRead, data.length - bytesRead, bytesRead);
440
+ if (!read.bytesRead) break;
441
+ bytesRead += read.bytesRead;
442
+ }
443
+ const after = await handle.stat({ bigint: true });
444
+ const current = await lstat(filename, { bigint: true });
445
+ if (bytesRead !== size || changedFile(before, after) || current.isSymbolicLink() || current.dev !== before.dev || current.ino !== before.ino) throw new Error("Artifact changed while being read.");
446
+ total += size;
447
+ files.push({ data: data.subarray(0, size), filename: sanitizeFilename(path.basename(relativePath)) });
448
+ } finally {
449
+ await handle.close();
450
+ }
451
+ }
452
+ return files;
453
+ } catch {
454
+ return [];
455
+ }
456
+ }
457
+
458
+ function changedFile(before, after) {
459
+ return before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs;
460
+ }
461
+
462
+ function sanitizeFilename(value, fallback = "artifact") {
463
+ const sanitized = value.replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "_").replace(/[. ]+$/u, "");
464
+ return Array.from(sanitized).reduce((result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result, "") || fallback;
465
+ }
466
+
331
467
  function latestAssistantMessage(messages, baseline) {
332
468
  for (let index = messages.length - 1; index >= 0; index -= 1) {
333
469
  const message = messages[index];
@@ -458,12 +594,11 @@ function serverUrl(baseUrl, pathname, workingDirectory) {
458
594
  return url;
459
595
  }
460
596
 
461
- function fetchAttachment(attachment, timeoutMs) {
462
- let timer;
597
+ function fetchAttachment(attachment, timeoutMs, signal) {
463
598
  return Promise.race([
464
599
  attachment.fetchData(),
465
- new Promise((_, reject) => timer = setTimeout(() => reject(new Error(`Attachment download timed out after ${timeoutMs}ms.`)), timeoutMs)),
466
- ]).finally(() => clearTimeout(timer));
600
+ delay(timeoutMs, signal).then(() => { throw new Error(`Attachment download timed out after ${timeoutMs}ms.`); }),
601
+ ]);
467
602
  }
468
603
 
469
604
  function delay(delayMs, signal) {
package/src/state.mjs CHANGED
@@ -23,6 +23,7 @@ const MANIFEST = {
23
23
  bot: [
24
24
  "files:read",
25
25
  "app_mentions:read",
26
+ "assistant:write",
26
27
  "channels:history",
27
28
  "channels:read",
28
29
  "chat:write",