@usepipa/pipa 0.4.0 → 0.4.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 CHANGED
@@ -33,7 +33,7 @@ npm install --global @usepipa/pipa
33
33
  pipa init
34
34
  ```
35
35
 
36
- `pipa init` guides you through creating and installing the Slack app and saving its local configuration.
36
+ `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
37
 
38
38
  3. Start Pipa:
39
39
 
@@ -41,7 +41,11 @@ pipa init
41
41
  pipa start
42
42
  ```
43
43
 
44
- Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. Pipa 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.
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 queued turn is active, Pipa shows a typing status in its Slack thread.
45
+
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 per-turn directory under `.pipa/artifacts` in the configured working directory, validated, limited to 10 files and 100 MB per file or response, and 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
+
48
+ 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
49
 
46
50
  ### Access control
47
51
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usepipa/pipa",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
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
  });
@@ -89,7 +93,8 @@ export async function startPipa(options = {}) {
89
93
  onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
90
94
  onPermissionReplied: interactions.onPermissionReplied,
91
95
  onPermissionsReconciled: interactions.onPermissionsReconciled,
92
- deliver: (text) => postInChunks(thread, text),
96
+ startTyping: () => thread.startTyping("Working on it..."),
97
+ deliver: (result) => postResult(thread, result),
93
98
  deliverFailure: (error) => thread.post(error instanceof PipaStoppedError
94
99
  ? `${config.botName} stopped before finishing this request.`
95
100
  : `${config.botName} failed: ${safeError(error)}`),
@@ -438,10 +443,13 @@ export function createConversationRunner({ sessionStore, runTurn }) {
438
443
  if (closed) return Promise.reject(closeReason);
439
444
  const previous = tails.get(conversationKey) ?? Promise.resolve();
440
445
  const current = previous.catch(() => undefined).then(async () => {
441
- const { deliver, deliverFailure, ...turn } = input;
446
+ const { deliver, deliverFailure, startTyping, ...turn } = input;
442
447
  let result;
443
448
  try {
444
449
  if (closed) throw closeReason;
450
+ try {
451
+ Promise.resolve(startTyping?.()).catch(() => undefined);
452
+ } catch {}
445
453
  result = await runTurn({ ...turn, sessionId: sessionStore.get(conversationKey) });
446
454
  if (result.sessionId) await sessionStore.set(conversationKey, result.sessionId);
447
455
  } catch (error) {
@@ -451,7 +459,7 @@ export function createConversationRunner({ sessionStore, runTurn }) {
451
459
  }
452
460
  throw error;
453
461
  }
454
- if (deliver) await deliver(result.text);
462
+ if (deliver) await deliver(result);
455
463
  return result;
456
464
  });
457
465
  const tail = current.then(() => undefined, () => undefined);
@@ -478,7 +486,10 @@ export async function checkSlackToken(token, fetchImpl = fetch) {
478
486
  });
479
487
  const result = await response.json();
480
488
  if (!response.ok || !result.ok) throw new Error("Slack rejected the bot token.");
481
- return result;
489
+ const headerScopes = response.headers?.get?.("x-oauth-scopes");
490
+ const grantedScopes = normalizeGrantedScopes(typeof headerScopes === "string" ? headerScopes.split(",") : undefined)
491
+ ?? normalizeGrantedScopes(result.response_metadata?.scopes);
492
+ return grantedScopes === undefined ? result : { ...result, grantedScopes };
482
493
  }
483
494
 
484
495
  export async function checkSlackAppToken(token, fetchImpl = fetch) {
@@ -530,6 +541,22 @@ function requireToken(value, label, prefix) {
530
541
  return token;
531
542
  }
532
543
 
544
+ function normalizeGrantedScopes(value) {
545
+ if (Array.isArray(value) && value.every((scope) => typeof scope === "string" && scope.trim())) {
546
+ return [...new Set(value.map((scope) => scope.trim()))];
547
+ }
548
+ }
549
+
550
+ function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`${message}\n`)) {
551
+ if (!Array.isArray(auth?.grantedScopes)) return;
552
+ const missing = ["channels:read", "assistant:write"].filter((scope) => !auth.grantedScopes.includes(scope));
553
+ if (!missing.length) return;
554
+ const scopes = missing.join(", ");
555
+ try {
556
+ 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.`);
557
+ } catch {}
558
+ }
559
+
533
560
  function safeError(error) {
534
561
  const message = error instanceof Error ? error.message : String(error);
535
562
  return message.replace(/xox[baprs]-[^\s]+|xapp-[^\s]+/gu, "[redacted]");
@@ -545,10 +572,59 @@ function slackContext(thread, message) {
545
572
  };
546
573
  }
547
574
 
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) });
575
+ async function postResult(thread, { text, files = [] }) {
576
+ if (files.length) {
577
+ try {
578
+ await thread.post({ markdown: text, files });
579
+ return;
580
+ } catch {
581
+ // A failed adapter call may still have uploaded files, so retry text only.
582
+ }
583
+ }
584
+ if (!text) return;
585
+ for (const markdown of splitSlackMarkdown(text)) await thread.post({ markdown });
586
+ }
587
+
588
+ function splitSlackMarkdown(text, limit = 3500) {
589
+ if (text.length <= limit) return [text];
590
+ const chunks = [];
591
+ let chunk = "";
592
+ let fence = "";
593
+ const append = (line) => {
594
+ const separator = chunk ? "\n" : "";
595
+ const closing = fence ? `\n${fence}` : "";
596
+ if (chunk && chunk.length + separator.length + line.length + closing.length > limit) {
597
+ chunks.push(chunk + closing);
598
+ chunk = fence ? `${fence}\n${line}` : line;
599
+ } else {
600
+ chunk += separator + line;
601
+ }
602
+ const marker = line.match(/^ {0,3}(```+|~~~+)/u)?.[0];
603
+ if (marker) fence = fence ? "" : marker;
604
+ };
605
+ for (const inputLine of text.split("\n")) {
606
+ let line = inputLine;
607
+ const emptyChunkLimit = limit - (fence ? (2 * fence.length) + 2 : 0);
608
+ if (line.length <= emptyChunkLimit) {
609
+ append(line);
610
+ continue;
611
+ }
612
+ if (chunk) {
613
+ chunks.push(chunk + (fence ? `\n${fence}` : ""));
614
+ chunk = fence ? `${fence}\n` : "";
615
+ }
616
+ const room = Math.max(1, limit - chunk.length - (fence ? fence.length + 1 : 0));
617
+ while (line.length > room) {
618
+ const boundary = line.slice(0, room + 1).search(/\s+\S*$/u);
619
+ const splitAt = boundary > 0 ? boundary : room;
620
+ chunks.push(chunk + line.slice(0, splitAt) + (fence ? `\n${fence}` : ""));
621
+ line = line.slice(splitAt).replace(/^\s+/u, "");
622
+ chunk = fence ? `${fence}\n` : "";
623
+ }
624
+ chunk += line;
551
625
  }
626
+ if (chunk) chunks.push(chunk + (fence ? `\n${fence}` : ""));
627
+ return chunks;
552
628
  }
553
629
 
554
630
  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,6 +85,8 @@ 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();
84
91
  let stopReason;
85
92
 
@@ -122,16 +129,23 @@ export function createOpenCodeExecutor(options = {}) {
122
129
  if (!prompt?.trim()) throw new Error("A prompt is required.");
123
130
  if (stopReason) throw stopReason;
124
131
  const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
125
- let turnError;
132
+ const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
133
+ const controller = new AbortController();
134
+ const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
135
+ active.add(controller);
136
+ let artifactDirectory;
126
137
 
127
138
  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
139
  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
+ const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls, controller.signal);
148
+ if (stopReason) throw stopReason;
135
149
  let selectedSessionId = sessionId;
136
150
  let messages;
137
151
  if (selectedSessionId) {
@@ -179,7 +193,7 @@ export function createOpenCodeExecutor(options = {}) {
179
193
  }
180
194
  await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
181
195
  method: "POST",
182
- body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment)),
196
+ body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment, artifactDirectory)),
183
197
  }, workingDirectory, controller, [204]);
184
198
 
185
199
  while (true) {
@@ -194,7 +208,13 @@ export function createOpenCodeExecutor(options = {}) {
194
208
  if (finalMessage && (status === "idle" || (!status && finalMessage.completed))) {
195
209
  if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
196
210
  if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
197
- return { text: finalMessage.text, sessionId: selectedSessionId };
211
+ const parsed = slackTurn ? parseArtifactDeclaration(finalMessage.text) : { text: finalMessage.text };
212
+ const artifacts = artifactDirectory && parsed.paths ? await readArtifacts(artifactDirectory, parsed.paths, options.onArtifactOpened) : [];
213
+ return {
214
+ text: parsed.text,
215
+ sessionId: selectedSessionId,
216
+ ...(artifacts.length ? { files: artifacts } : {}),
217
+ };
198
218
  }
199
219
  await delay(pollIntervalMs, controller.signal);
200
220
  }
@@ -204,18 +224,23 @@ export function createOpenCodeExecutor(options = {}) {
204
224
  active.delete(controller);
205
225
  }
206
226
  } catch (error) {
207
- turnError = error;
208
227
  if (stopReason) throw stopReason;
209
228
  throw error;
210
229
  } finally {
211
230
  if (temporaryDirectory) {
212
231
  try {
213
- await rm(temporaryDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
214
- } catch (error) {
215
- if (!turnError) throw error;
232
+ await remove(temporaryDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
233
+ } catch {
216
234
  process.stderr.write("Pipa could not remove temporary attachment files.\n");
217
235
  }
218
236
  }
237
+ if (artifactDirectory) {
238
+ try {
239
+ await remove(artifactDirectory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
240
+ } catch {
241
+ process.stderr.write("Pipa could not remove temporary artifact files.\n");
242
+ }
243
+ }
219
244
  }
220
245
  }
221
246
 
@@ -286,24 +311,18 @@ export async function runOpenCodeVersion(options = {}) {
286
311
  }
287
312
  }
288
313
 
289
- async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls) {
314
+ async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls, signal) {
290
315
  const files = [];
291
316
  for (const [index, attachment] of attachments.entries()) {
292
317
  let data;
293
318
  try {
294
- data = await fetchAttachment(attachment, timeoutMs);
319
+ data = await fetchAttachment(attachment, timeoutMs, signal);
295
320
  } catch {
296
321
  throw new Error("Could not read one of the attached files. Please try uploading it again.");
297
322
  }
298
323
  if (data.byteLength > MAX_ATTACHMENT_BYTES) throw new Error("Attached files must be 100 MB or smaller.");
299
324
  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";
325
+ const filename = sanitizeFilename(path.basename(attachment.name || "attachment"), "attachment");
307
326
  const file = path.join(temporaryDirectory, `${index + 1}-${filename}`);
308
327
  await writeFile(file, data);
309
328
  const mime = attachment.mimeType || "application/octet-stream";
@@ -319,15 +338,96 @@ async function stageAttachments(attachments, temporaryDirectory, timeoutMs, useD
319
338
  return files;
320
339
  }
321
340
 
322
- function promptBody(prompt, files, contextEnvironment) {
341
+ function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
323
342
  const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
324
343
  const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
344
+ const instructions = [];
345
+ 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")}`);
346
+ if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
347
+ 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.");
348
+ 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\"]`);
349
+ }
325
350
  return {
326
351
  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")}` } : {}),
352
+ ...(instructions.length ? { system: instructions.join("\n\n") } : {}),
328
353
  };
329
354
  }
330
355
 
356
+ function parseArtifactDeclaration(text) {
357
+ const lines = text.split(/\r?\n/u);
358
+ const declarations = lines.map((line, index) => line.startsWith(ARTIFACT_MARKER) ? { line, index } : null).filter(Boolean);
359
+ const cleanText = lines.filter((line) => !line.startsWith(ARTIFACT_MARKER)).join("\n").trim();
360
+ const lastNonblank = lines.findLastIndex((line) => line.trim());
361
+ if (declarations.length !== 1 || declarations[0].index !== lastNonblank) return { text: cleanText };
362
+ const declaration = declarations[0].line;
363
+ if (!declaration.startsWith(`${ARTIFACT_MARKER} `) || Buffer.byteLength(declaration) > MAX_ARTIFACT_DECLARATION_BYTES) return { text: cleanText };
364
+ let paths;
365
+ try {
366
+ paths = JSON.parse(declaration.slice(ARTIFACT_MARKER.length + 1));
367
+ } catch {
368
+ return { text: cleanText };
369
+ }
370
+ if (!Array.isArray(paths) || !paths.length || paths.length > MAX_ARTIFACT_FILES || paths.some((item) => typeof item !== "string")) return { text: cleanText };
371
+ if (new Set(paths).size !== paths.length || paths.some((item) => !validArtifactPath(item))) return { text: cleanText };
372
+ return { text: cleanText, paths };
373
+ }
374
+
375
+ function validArtifactPath(value) {
376
+ if (!value || Buffer.byteLength(value) > MAX_ARTIFACT_PATH_BYTES || value.includes("\0") || value.includes("\\") || path.isAbsolute(value)) return false;
377
+ const parts = value.split("/");
378
+ return parts.length === 1 && parts[0] !== "." && parts[0] !== "..";
379
+ }
380
+
381
+ async function readArtifacts(directory, paths, onOpened) {
382
+ const files = [];
383
+ let total = 0;
384
+ try {
385
+ const root = await realpath(directory);
386
+ for (const relativePath of paths) {
387
+ const filename = path.resolve(root, relativePath);
388
+ if (!filename.startsWith(`${root}${path.sep}`)) throw new Error("Artifact path escaped its directory.");
389
+ let current = root;
390
+ for (const part of relativePath.split("/")) {
391
+ current = path.join(current, part);
392
+ if ((await lstat(current)).isSymbolicLink()) throw new Error("Artifact path contains a symbolic link.");
393
+ }
394
+ const handle = await open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
395
+ try {
396
+ const before = await handle.stat({ bigint: true });
397
+ await onOpened?.(filename);
398
+ const size = Number(before.size);
399
+ if (!before.isFile() || size > MAX_ATTACHMENT_BYTES || total + size > MAX_ATTACHMENT_BYTES) throw new Error("Artifact exceeds delivery limits.");
400
+ const data = Buffer.alloc(size + 1);
401
+ let bytesRead = 0;
402
+ while (bytesRead < data.length) {
403
+ const read = await handle.read(data, bytesRead, data.length - bytesRead, bytesRead);
404
+ if (!read.bytesRead) break;
405
+ bytesRead += read.bytesRead;
406
+ }
407
+ const after = await handle.stat({ bigint: true });
408
+ const current = await lstat(filename, { bigint: true });
409
+ if (bytesRead !== size || changedFile(before, after) || current.isSymbolicLink() || current.dev !== before.dev || current.ino !== before.ino) throw new Error("Artifact changed while being read.");
410
+ total += size;
411
+ files.push({ data: data.subarray(0, size), filename: sanitizeFilename(path.basename(relativePath)) });
412
+ } finally {
413
+ await handle.close();
414
+ }
415
+ }
416
+ return files;
417
+ } catch {
418
+ return [];
419
+ }
420
+ }
421
+
422
+ function changedFile(before, after) {
423
+ return before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs;
424
+ }
425
+
426
+ function sanitizeFilename(value, fallback = "artifact") {
427
+ const sanitized = value.replace(/[<>:"/\\|?*\u0000-\u001f]/gu, "_").replace(/[. ]+$/u, "");
428
+ return Array.from(sanitized).reduce((result, character) => Buffer.byteLength(result + character) <= 200 ? result + character : result, "") || fallback;
429
+ }
430
+
331
431
  function latestAssistantMessage(messages, baseline) {
332
432
  for (let index = messages.length - 1; index >= 0; index -= 1) {
333
433
  const message = messages[index];
@@ -458,12 +558,11 @@ function serverUrl(baseUrl, pathname, workingDirectory) {
458
558
  return url;
459
559
  }
460
560
 
461
- function fetchAttachment(attachment, timeoutMs) {
462
- let timer;
561
+ function fetchAttachment(attachment, timeoutMs, signal) {
463
562
  return Promise.race([
464
563
  attachment.fetchData(),
465
- new Promise((_, reject) => timer = setTimeout(() => reject(new Error(`Attachment download timed out after ${timeoutMs}ms.`)), timeoutMs)),
466
- ]).finally(() => clearTimeout(timer));
564
+ delay(timeoutMs, signal).then(() => { throw new Error(`Attachment download timed out after ${timeoutMs}ms.`); }),
565
+ ]);
467
566
  }
468
567
 
469
568
  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",