@usepipa/pipa 0.3.1 → 0.4.0

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
@@ -3,7 +3,7 @@
3
3
  [![CI](https://github.com/lunchpaillola/pipa/actions/workflows/ci.yml/badge.svg)](https://github.com/lunchpaillola/pipa/actions/workflows/ci.yml)
4
4
  [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
5
5
 
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.
6
+ Pipa runs Slack through one persistent private OpenCode server with 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
 
@@ -43,34 +43,35 @@ pipa start
43
43
 
44
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.
45
45
 
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`:
47
-
48
- ```sh
49
- export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
50
- pipa start
51
- ```
52
-
53
- ## Managed Mode
46
+ ### Access control
54
47
 
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:
48
+ By default Pipa answers anyone who mentions it in a channel it can see. In a shared workspace, restrict who can use it by listing the allowed Slack channel and user IDs. `pipa init` asks for these, and they are stored in the config:
56
49
 
57
50
  ```json
58
51
  {
59
52
  "botName": "Pipa",
60
- "workingDirectory": "/workspace",
61
- "slackMode": "managed",
62
- "openCodeHostname": "127.0.0.1",
63
- "openCodePort": 4096
53
+ "workingDirectory": "/work",
54
+ "slackAppToken": "xapp-...",
55
+ "slackBotToken": "xoxb-...",
56
+ "allowedSlackChannelIds": ["C0BSE2JTYPR"],
57
+ "allowedSlackUserIds": ["UFWBSCZ54"]
64
58
  }
65
59
  ```
66
60
 
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.
61
+ A mention is only handled when the channel ID is in `allowedSlackChannelIds` **and** the author's user ID is in `allowedSlackUserIds`. Leave a list empty to allow any channel or any user. You can also set them non-interactively during setup with `PIPA_ALLOWED_CHANNEL_IDS` and `PIPA_ALLOWED_USER_IDS` (comma-separated).
62
+
63
+ 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`:
64
+
65
+ ```sh
66
+ export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
67
+ pipa start
68
+ ```
68
69
 
69
70
  ## Commands
70
71
 
71
72
  ```text
72
73
  pipa init Configure Slack and the local working directory
73
- pipa start Start the configured Socket or Managed runtime
74
+ pipa start Start the configured Slack runtime
74
75
  pipa --version Print the installed version
75
76
  ```
76
77
 
package/bin/pipa.mjs CHANGED
@@ -5,7 +5,7 @@ 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, loadConfig } from "../src/state.mjs";
8
+ import { acquireInstanceLock, createManifest, createManifestUrl, loadConfig, stopInstance } from "../src/state.mjs";
9
9
  import { initializePipa, startPipa } from "../src/app.mjs";
10
10
  import { startOpenCodeServer } from "../src/opencode.mjs";
11
11
 
@@ -19,7 +19,13 @@ async function main(argv = process.argv.slice(2), io = { input: stdin, output: s
19
19
  }
20
20
  if (command === "init") return init(io);
21
21
  if (command === "start") return start(io);
22
- throw new Error("Usage: pipa init | pipa start | pipa --version");
22
+ if (command === "stop") return stop(io);
23
+ throw new Error("Usage: pipa init | pipa start | pipa stop | pipa --version");
24
+ }
25
+
26
+ async function stop(io) {
27
+ const pid = await stopInstance();
28
+ io.output.write(pid ? `Pipa is stopping (PID ${pid}).\n` : "Pipa is not running.\n");
23
29
  }
24
30
 
25
31
  async function init(io) {
@@ -61,8 +67,12 @@ async function init(io) {
61
67
  };
62
68
  const slackAppToken = process.env.PIPA_SLACK_APP_TOKEN || await askSecret("Slack app token (xapp-, input hidden): ", "App token");
63
69
  const slackBotToken = process.env.PIPA_SLACK_BOT_TOKEN || await askSecret("Slack bot token (xoxb-, input hidden): ", "Bot token");
70
+ const allowedSlackChannelIds = process.env.PIPA_ALLOWED_CHANNEL_IDS
71
+ ?? (await prompt.question("Allowed Slack channel IDs (comma-separated, e.g. C0BSE2JTYPR; leave empty to allow any channel): ")).trim();
72
+ const allowedSlackUserIds = process.env.PIPA_ALLOWED_USER_IDS
73
+ ?? (await prompt.question("Allowed Slack user IDs (comma-separated, e.g. UFWBSCZ54; leave empty to allow any user): ")).trim();
64
74
  io.output.write("\nChecking OpenCode and Slack credentials...\n");
65
- const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken });
75
+ const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds });
66
76
  io.output.write(`✓ Credentials validated.\n\nSaved config to ${result.paths.config}. Run \`pipa start\`.\n`);
67
77
  } finally {
68
78
  prompt.close();
@@ -98,21 +108,19 @@ function openUrl(url) {
98
108
 
99
109
  async function start(io) {
100
110
  const releaseLock = await acquireInstanceLock();
111
+ let stop;
112
+ let stopWithSigint;
113
+ let stopWithSigterm;
101
114
  try {
102
115
  const config = await loadConfig();
103
116
  if (config.slackMode === "managed") {
104
117
  const server = startOpenCodeServer(config);
105
118
  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");
119
+ stopWithSigint = () => server.stop("SIGINT");
120
+ stopWithSigterm = () => server.stop("SIGTERM");
108
121
  process.on("SIGINT", stopWithSigint);
109
122
  process.on("SIGTERM", stopWithSigterm);
110
- try {
111
- await server.wait();
112
- } finally {
113
- process.off("SIGINT", stopWithSigint);
114
- process.off("SIGTERM", stopWithSigterm);
115
- }
123
+ await server.wait();
116
124
  return;
117
125
  }
118
126
 
@@ -121,22 +129,29 @@ async function start(io) {
121
129
  ? `Pipa started a private OpenCode server at ${app.server.baseUrl}.\n`
122
130
  : `Pipa is using the configured OpenCode server at ${app.server.baseUrl}.\n`);
123
131
  io.output.write("Pipa is connected through Slack Socket Mode.\n");
124
- let stop;
125
- const signal = new Promise((resolve) => stop = resolve);
126
- process.once("SIGINT", stop);
127
- process.once("SIGTERM", stop);
132
+ const { promise: signal, resolve: resolveSignal } = Promise.withResolvers();
133
+ stop = () => {
134
+ app.stop();
135
+ resolveSignal();
136
+ };
137
+ process.on("SIGINT", stop);
138
+ process.on("SIGTERM", stop);
128
139
  try {
129
140
  await Promise.race([signal, app.wait()]);
130
141
  } finally {
131
- try {
132
- await app.shutdown();
133
- } finally {
142
+ await app.shutdown();
143
+ }
144
+ } finally {
145
+ try {
146
+ await releaseLock();
147
+ } finally {
148
+ if (stop) {
134
149
  process.off("SIGINT", stop);
135
150
  process.off("SIGTERM", stop);
136
151
  }
152
+ if (stopWithSigint) process.off("SIGINT", stopWithSigint);
153
+ if (stopWithSigterm) process.off("SIGTERM", stopWithSigterm);
137
154
  }
138
- } finally {
139
- await releaseLock();
140
155
  }
141
156
  }
142
157
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@usepipa/pipa",
3
- "version": "0.3.1",
4
- "description": "Run Pipa through Slack Socket Mode or as a managed OpenCode server",
3
+ "version": "0.4.0",
4
+ "description": "Run Pipa through Slack Socket Mode with OpenCode",
5
5
  "keywords": [
6
6
  "slack",
7
7
  "opencode",
package/src/app.mjs CHANGED
@@ -1,8 +1,9 @@
1
- import { Chat } from "chat";
1
+ import { randomUUID } from "node:crypto";
2
+ import { Chat, Modal, TextInput } from "chat";
2
3
  import { createSlackAdapter } from "@chat-adapter/slack";
3
4
  import { createMemoryState } from "@chat-adapter/state-memory";
4
5
  import { canonicalWorkingDirectory, createManifest, createSessionStore, loadConfig, pipaPaths, saveConfig } from "./state.mjs";
5
- import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
6
+ import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
6
7
 
7
8
  export async function initializePipa(input, options = {}) {
8
9
  const paths = options.paths ?? pipaPaths();
@@ -12,6 +13,8 @@ export async function initializePipa(input, options = {}) {
12
13
  slackAppToken: requireToken(input.slackAppToken, "Slack app token", "xapp-"),
13
14
  slackBotToken: requireToken(input.slackBotToken, "Slack bot token", "xoxb-"),
14
15
  workingDirectory: await canonicalWorkingDirectory(input.workingDirectory),
16
+ allowedSlackChannelIds: normalizeIdList(input.allowedSlackChannelIds),
17
+ allowedSlackUserIds: normalizeIdList(input.allowedSlackUserIds),
15
18
  };
16
19
  const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
17
20
  if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
@@ -58,9 +61,12 @@ export async function startPipa(options = {}) {
58
61
  }
59
62
  const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn });
60
63
  let accepting = true;
64
+ const interactions = createPendingInteractions();
65
+ chat.onAction?.(interactions.onAction);
66
+ chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
61
67
 
62
68
  const handle = async (thread, message, subscribe) => {
63
- if (!accepting || shouldIgnore(thread, message)) return;
69
+ if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
64
70
  const prompt = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
65
71
  if (!prompt) return;
66
72
  const attachments = message.attachments ?? [];
@@ -73,23 +79,30 @@ export async function startPipa(options = {}) {
73
79
 
74
80
  await react(thread, message, "eyes");
75
81
  try {
82
+ const interactionContext = { thread };
76
83
  const result = await runner.enqueue(thread.id, {
77
84
  prompt,
78
85
  attachments,
79
86
  workingDirectory: config.workingDirectory,
80
87
  contextEnvironment: slackContext(thread, message),
88
+ onSession: () => undefined,
89
+ onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
90
+ onPermissionReplied: interactions.onPermissionReplied,
91
+ onPermissionsReconciled: interactions.onPermissionsReconciled,
81
92
  deliver: (text) => postInChunks(thread, text),
82
- deliverFailure: (error) => thread.post(`Pipa failed: ${safeError(error)}`),
93
+ deliverFailure: (error) => thread.post(error instanceof PipaStoppedError
94
+ ? `${config.botName} stopped before finishing this request.`
95
+ : `${config.botName} failed: ${safeError(error)}`),
83
96
  });
84
- await finishReaction(thread, message, result.error ? "warning" : "white_check_mark");
97
+ await finishReaction(thread, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
85
98
  } catch (error) {
86
99
  await finishReaction(thread, message, "warning");
87
100
  process.stderr.write("Pipa could not complete or deliver a Slack turn.\n");
88
101
  }
89
102
  };
90
103
 
91
- chat.onNewMention((thread, message) => handle(thread, message, true));
92
- chat.onSubscribedMessage((thread, message) => handle(thread, message, false));
104
+ chat.onNewMention((thread, message) => { void handle(thread, message, true); });
105
+ chat.onSubscribedMessage((thread, message) => { void handle(thread, message, false); });
93
106
  try {
94
107
  await state.connect();
95
108
  for (const conversationKey of sessionStore.keys()) {
@@ -97,6 +110,7 @@ export async function startPipa(options = {}) {
97
110
  }
98
111
  await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
99
112
  } catch (error) {
113
+ await interactions.close();
100
114
  executor.stopAll();
101
115
  await withTimeout(chat.shutdown(), options.shutdownTimeoutMs ?? 15_000, "Slack shutdown timed out.").catch(() => undefined);
102
116
  server?.stop();
@@ -104,13 +118,27 @@ export async function startPipa(options = {}) {
104
118
  throw error;
105
119
  }
106
120
 
121
+ const stop = (reason = new PipaStoppedError()) => {
122
+ if (!accepting) return;
123
+ accepting = false;
124
+ runner.close(reason);
125
+ executor.stopAll(reason);
126
+ };
127
+
107
128
  return {
108
129
  server: server ? { baseUrl: server.baseUrl, owned: server.owned } : null,
109
- wait: () => server?.wait() ?? new Promise(() => undefined),
130
+ async wait() {
131
+ try {
132
+ return await (server?.wait() ?? new Promise(() => undefined));
133
+ } catch (error) {
134
+ stop(error);
135
+ throw error;
136
+ }
137
+ },
138
+ stop: () => stop(),
110
139
  async shutdown() {
111
- accepting = false;
112
- runner.close();
113
- executor.stopAll();
140
+ stop();
141
+ await interactions.close();
114
142
  try {
115
143
  await withTimeout((async () => {
116
144
  await runner.drain();
@@ -125,18 +153,295 @@ export async function startPipa(options = {}) {
125
153
  };
126
154
  }
127
155
 
156
+ function createPendingInteractions() {
157
+ const pending = new Map();
158
+ const permissionRequests = new Map();
159
+ const tails = new Map();
160
+
161
+ async function onInteraction(context, interaction) {
162
+ const token = randomUUID().replaceAll("-", "");
163
+ const entry = {
164
+ token,
165
+ type: interaction.type,
166
+ request: interaction.request,
167
+ sessionId: interaction.sessionId,
168
+ requestId: interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id,
169
+ questionIndex: 0,
170
+ answers: [],
171
+ resolve: null,
172
+ };
173
+ const decision = new Promise((resolve, reject) => {
174
+ const abort = () => reject(interaction.signal.reason);
175
+ entry.resolve = (value) => {
176
+ if (entry.decision !== undefined) return;
177
+ entry.decision = value;
178
+ interaction.signal.removeEventListener("abort", abort);
179
+ resolve(value);
180
+ };
181
+ if (interaction.signal.aborted) abort();
182
+ else interaction.signal.addEventListener("abort", abort, { once: true });
183
+ });
184
+ pending.set(token, entry);
185
+ const requestId = interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id;
186
+ const permissionKey = interaction.type === "permission" && requestId ? `${interaction.sessionId}:${requestId}` : null;
187
+ if (permissionKey) permissionRequests.set(permissionKey, entry);
188
+ const conversationKey = context.thread.id;
189
+ const previous = tails.get(conversationKey) ?? Promise.resolve();
190
+ let release;
191
+ const tail = new Promise((resolve) => { release = resolve; });
192
+ tails.set(conversationKey, tail);
193
+ try {
194
+ await previous;
195
+ if (entry.decision === undefined) {
196
+ entry.message = await postInteraction(context.thread, entry);
197
+ if (interaction.signal.aborted) throw interaction.signal.reason;
198
+ }
199
+ const result = await decision;
200
+ await submit(entry, result);
201
+ return result;
202
+ } finally {
203
+ pending.delete(token);
204
+ if (permissionKey) permissionRequests.delete(permissionKey);
205
+ release();
206
+ if (tails.get(conversationKey) === tail) tails.delete(conversationKey);
207
+ }
208
+ }
209
+
210
+ function onPermissionReplied({ sessionId, requestId, reply }) {
211
+ const entry = permissionRequests.get(`${sessionId}:${requestId}`);
212
+ entry?.resolve?.(reply === "reject" ? { type: "reject" } : { type: "reply", reply });
213
+ }
214
+
215
+ function onPermissionsReconciled({ sessionId, requestIds }) {
216
+ for (const entry of permissionRequests.values()) {
217
+ if (entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
218
+ }
219
+ }
220
+
221
+ async function close() {
222
+ const entries = [...pending.values()];
223
+ for (const entry of entries) entry.resolve?.({ type: "stopped" });
224
+ await Promise.all(entries.map((entry) => submit(entry, { type: "stopped" })));
225
+ }
226
+
227
+ async function onAction(event) {
228
+ const token = interactionToken(event);
229
+ const entry = pending.get(token);
230
+ if (!entry) return;
231
+ if (event.actionId?.startsWith("pipa_dismiss_")) {
232
+ entry.resolve?.({ type: "stop" });
233
+ return;
234
+ }
235
+ if (entry.type === "permission") {
236
+ const reply = String(event.value ?? "").split(".")[1];
237
+ if (!["once", "always", "reject"].includes(reply)) return;
238
+ const selectedBy = displayName(event.user?.fullName ?? event.user?.userName);
239
+ entry.resolve?.(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
240
+ return;
241
+ }
242
+ if (event.actionId?.startsWith("pipa_custom_")) {
243
+ await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: token, title: "Custom answer", submitLabel: "Submit", children: [TextInput({ id: "answer", label: "Answer" })] }));
244
+ return;
245
+ }
246
+ if (entry.type !== "question") return;
247
+ if (event.actionId?.startsWith("pipa_select_")) {
248
+ const answers = selectedAnswers(event);
249
+ if (!answers.length) return;
250
+ entry.answers[entry.questionIndex] = answers;
251
+ return;
252
+ }
253
+ if (event.actionId?.startsWith("pipa_submit_")) {
254
+ if (!entry.answers[entry.questionIndex]?.length) return;
255
+ advance(entry, event.user);
256
+ return;
257
+ }
258
+ }
259
+
260
+ async function onCustomAnswer(event) {
261
+ const entry = pending.get(event.privateMetadata);
262
+ if (!entry) return;
263
+ const answer = event.values?.answer?.trim();
264
+ if (!answer) return { action: "errors", errors: { answer: "Enter an answer." } };
265
+ entry.answers[entry.questionIndex] = [answer];
266
+ advance(entry, event.user);
267
+ }
268
+
269
+ function advance(entry, user) {
270
+ if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
271
+ const selectedBy = displayName(user?.fullName ?? user?.userName);
272
+ entry.resolve?.({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
273
+ }
274
+ else entry.message?.edit();
275
+ }
276
+
277
+ return { onInteraction, onPermissionReplied, onPermissionsReconciled, onAction, onCustomAnswer, close };
278
+ }
279
+
280
+ async function submit(entry, decision) {
281
+ if (entry.submitted) return;
282
+ entry.submitted = true;
283
+ if (decision?.type === "cancelled" || decision?.type === "stopped") {
284
+ await entry.message?.delete?.();
285
+ return;
286
+ }
287
+ await entry.message?.edit(decision);
288
+ }
289
+
290
+ function renderSubmitted(entry, decision) {
291
+ let content = "Answered.";
292
+ let title = entry.type === "permission" ? "Permission requested" : (entry.request.questions?.[0]?.header || "Question");
293
+ if (decision?.type === "stop") content = "Dismissed.";
294
+ else if (entry.type === "permission") ({ title, content } = permissionOutcome(entry.request, decision));
295
+ else {
296
+ const answers = decision?.answers?.flat().filter(Boolean) ?? [];
297
+ content = `${decision?.selectedBy ? `${decision.selectedBy} selected` : "Selected"}: ${answers.map((answer) => `“${answer}”`).join(", ")}.`;
298
+ }
299
+ return { title, content };
300
+ }
301
+
302
+ async function postInteraction(thread, entry) {
303
+ const [, channel, threadTs] = thread.id.split(":");
304
+ const client = thread.adapter?.webClient;
305
+ if (!client || !channel || !threadTs) throw new Error("Slack interaction context is unavailable.");
306
+ const message = await client.chat.postMessage({
307
+ channel,
308
+ thread_ts: threadTs,
309
+ text: interactionFallback(entry),
310
+ blocks: renderSlackInteraction(entry),
311
+ });
312
+ return {
313
+ edit: (decision) => client.chat.update({
314
+ channel,
315
+ ts: message.ts,
316
+ text: decision ? submittedText(entry, decision) : interactionFallback(entry),
317
+ blocks: decision ? renderSlackSubmitted(entry, decision) : renderSlackInteraction(entry),
318
+ }),
319
+ delete: () => client.chat.delete({ channel, ts: message.ts }),
320
+ };
321
+ }
322
+
323
+ function renderSlackInteraction(entry) {
324
+ if (entry.type === "permission") {
325
+ const resources = entry.request.patterns ?? entry.request.resources ?? [];
326
+ return [
327
+ slackHeader("Permission requested"),
328
+ slackText(permissionDetail(entry.request, resources)),
329
+ slackActions([
330
+ slackButton(`pipa_permission_once_${entry.token}`, "Allow once", `${entry.token}.once`, "primary"),
331
+ slackButton(`pipa_permission_always_${entry.token}`, "Always allow", `${entry.token}.always`),
332
+ slackButton(`pipa_permission_reject_${entry.token}`, "Reject", `${entry.token}.reject`, "danger"),
333
+ ]),
334
+ ];
335
+ }
336
+ const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
337
+ const options = (question.options ?? []).map((option) => ({
338
+ text: { type: "plain_text", text: option.label ?? option },
339
+ value: `${entry.token}.${option.label ?? option}`,
340
+ }));
341
+ const selector = options.length && (question.multiple
342
+ ? { type: "checkboxes", action_id: `pipa_select_${entry.token}`, options }
343
+ : { type: "radio_buttons", action_id: `pipa_select_${entry.token}`, options });
344
+ const actions = [
345
+ ...(question.custom || !options.length ? [slackButton(`pipa_custom_${entry.token}`, "Custom answer", entry.token)] : []),
346
+ ...(options.length ? [slackButton(`pipa_submit_${entry.token}`, "Submit", entry.token, "primary")] : []),
347
+ slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
348
+ ];
349
+ return [slackHeader(question.header || "Question"), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [slackActions([selector])] : []), slackActions(actions)];
350
+ }
351
+
352
+ function renderSlackSubmitted(entry, decision) {
353
+ const submitted = renderSubmitted(entry, decision);
354
+ return [slackHeader(submitted.title), slackText(submitted.content)];
355
+ }
356
+
357
+ function submittedText(entry, decision) {
358
+ return renderSubmitted(entry, decision).content;
359
+ }
360
+
361
+ function permissionDetail(request, resources) {
362
+ const input = request.tool?.input;
363
+ const tool = request.tool?.name ? [`Tool: ${request.tool.name}`] : [];
364
+ if (request.tool?.name === "read" && input?.filePath) tool.push(`File: ${input.filePath}`);
365
+ if (request.tool?.name === "glob" && input?.pattern) tool.push(`Pattern: ${input.pattern}`);
366
+ return [`Action: ${request.permission ?? request.action ?? "Unknown"}`, ...tool, ...(resources.length ? ["Resources:", ...resources.map((resource) => `- ${resource}`)] : [])].join("\n");
367
+ }
368
+
369
+ function permissionOutcome(request, decision) {
370
+ const action = permissionAction(request);
371
+ const detail = permissionDetail(request, request.patterns ?? request.resources ?? []);
372
+ const actor = decision?.selectedBy ? ` by ${decision.selectedBy}` : "";
373
+ if (decision?.type === "reject") return {
374
+ title: "Permission rejected",
375
+ content: `Rejected${actor}. Blocked ${action}. OpenCode may cancel related requests from the same batch.\n\n${detail}`,
376
+ };
377
+ if (decision?.reply === "always") return {
378
+ title: "Permission allowed",
379
+ content: `Allowed${actor} in this workspace. Pipa will not ask again for matching access.\n\n${detail}`,
380
+ };
381
+ return {
382
+ title: "Permission allowed once",
383
+ content: `Allowed${actor} for this request. Pipa will ask again for later protected access.\n\n${detail}`,
384
+ };
385
+ }
386
+
387
+ function permissionAction(request) {
388
+ const input = request.tool?.input;
389
+ if (request.tool?.name === "read" && input?.filePath) return `\`read ${input.filePath}\``;
390
+ if (request.tool?.name === "glob" && input?.pattern) return `\`glob ${input.pattern}\``;
391
+ return `the ${request.permission ?? request.action ?? "requested"} action`;
392
+ }
393
+
394
+ function interactionFallback(entry) {
395
+ const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
396
+ return question.question ?? question.header ?? "Action required";
397
+ }
398
+
399
+ function slackHeader(text) {
400
+ return { type: "header", text: { type: "plain_text", text } };
401
+ }
402
+
403
+ function slackText(text) {
404
+ return { type: "section", text: { type: "mrkdwn", text } };
405
+ }
406
+
407
+ function slackActions(elements) {
408
+ return { type: "actions", elements };
409
+ }
410
+
411
+ function slackButton(actionId, text, value, style) {
412
+ return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
413
+ }
414
+
415
+ function selectedAnswers(event) {
416
+ const action = event.raw?.actions?.find((item) => item.action_id === event.actionId);
417
+ const values = action?.selected_options?.map((option) => option.value) ?? [event.value];
418
+ return values.filter(Boolean).map((value) => String(value).split(".").slice(1).join(".")).filter(Boolean);
419
+ }
420
+
421
+ function interactionToken(event) {
422
+ const value = String(event.value ?? "").split(".")[0];
423
+ return value || event.actionId?.split("_").at(-1) || "";
424
+ }
425
+
426
+ function displayName(value) {
427
+ const name = String(value ?? "").trim();
428
+ return name ? name[0].toUpperCase() + name.slice(1) : "";
429
+ }
430
+
128
431
  export function createConversationRunner({ sessionStore, runTurn }) {
129
432
  const tails = new Map();
130
433
  let closed = false;
434
+ let closeReason;
131
435
 
132
436
  function enqueue(conversationKey, input) {
133
- if (closed) return Promise.reject(new Error("Pipa is shutting down."));
437
+ if (closed && input.deliverFailure) return Promise.resolve(input.deliverFailure(closeReason)).then(() => ({ error: closeReason }));
438
+ if (closed) return Promise.reject(closeReason);
134
439
  const previous = tails.get(conversationKey) ?? Promise.resolve();
135
440
  const current = previous.catch(() => undefined).then(async () => {
136
- if (closed) throw new Error("Pipa is shutting down.");
137
441
  const { deliver, deliverFailure, ...turn } = input;
138
442
  let result;
139
443
  try {
444
+ if (closed) throw closeReason;
140
445
  result = await runTurn({ ...turn, sessionId: sessionStore.get(conversationKey) });
141
446
  if (result.sessionId) await sessionStore.set(conversationKey, result.sessionId);
142
447
  } catch (error) {
@@ -159,7 +464,7 @@ export function createConversationRunner({ sessionStore, runTurn }) {
159
464
 
160
465
  return {
161
466
  enqueue,
162
- close() { closed = true; },
467
+ close(reason = new PipaStoppedError()) { closed = true; closeReason ??= reason; },
163
468
  drain: () => Promise.all([...tails.values()]),
164
469
  };
165
470
  }
@@ -201,6 +506,20 @@ function shouldIgnore(thread, message) {
201
506
  || !message.text?.trim();
202
507
  }
203
508
 
509
+ function isAuthorized(thread, message, config) {
510
+ const channelId = thread.id.split(":")[1];
511
+ const userId = message.author?.userId ?? message.author?.id;
512
+ if (config.allowedSlackChannelIds?.length && !config.allowedSlackChannelIds.includes(channelId)) return false;
513
+ if (config.allowedSlackUserIds?.length && !config.allowedSlackUserIds.includes(userId)) return false;
514
+ return true;
515
+ }
516
+
517
+ function normalizeIdList(value) {
518
+ if (value === undefined || value === null) return [];
519
+ const list = Array.isArray(value) ? value : String(value).split(/[\s,]+/u);
520
+ return list.map((item) => String(item).trim()).filter(Boolean);
521
+ }
522
+
204
523
  function stripMention(text = "") {
205
524
  return text.replace(/(?:<@|@)[UW][A-Z0-9]+>?/u, "").trim();
206
525
  }
@@ -240,7 +559,7 @@ async function react(thread, message, emoji) {
240
559
  async function finishReaction(thread, message, emoji) {
241
560
  if (!message.id) return;
242
561
  await thread.adapter.removeReaction(thread.id, message.id, "eyes").catch(() => undefined);
243
- await react(thread, message, emoji);
562
+ if (emoji) await react(thread, message, emoji);
244
563
  }
245
564
 
246
565
  async function withTimeout(promise, timeoutMs, message) {
package/src/opencode.mjs CHANGED
@@ -14,6 +14,12 @@ const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
14
14
 
15
15
  export const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
16
16
 
17
+ export class PipaStoppedError extends Error {
18
+ constructor(message = "Pipa is shutting down.") {
19
+ super(message);
20
+ }
21
+ }
22
+
17
23
  export function cleanChildEnvironment(environment = process.env) {
18
24
  return Object.fromEntries(Object.entries(environment).filter(([key]) => !SECRET_ENV_KEYS.has(key.toUpperCase())));
19
25
  }
@@ -75,9 +81,9 @@ export function createOpenCodeExecutor(options = {}) {
75
81
  const pollIntervalMs = options.pollIntervalMs ?? 1_000;
76
82
  const useDataUrls = !isLoopbackUrl(baseUrl);
77
83
  const active = new Set();
78
- let stopped = false;
84
+ let stopReason;
79
85
 
80
- async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200]) {
86
+ async function request(pathname, init, workingDirectory, controller, acceptedStatuses = [200], reportFatal = true) {
81
87
  const url = serverUrl(baseUrl, pathname, workingDirectory);
82
88
  let response;
83
89
  try {
@@ -92,7 +98,7 @@ export function createOpenCodeExecutor(options = {}) {
92
98
  });
93
99
  } catch (error) {
94
100
  if (controller.signal.aborted) throw controller.signal.reason;
95
- if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
101
+ if (reportFatal && isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
96
102
  throw error;
97
103
  }
98
104
  let text;
@@ -100,7 +106,7 @@ export function createOpenCodeExecutor(options = {}) {
100
106
  text = await response.text();
101
107
  } catch (error) {
102
108
  if (controller.signal.aborted) throw controller.signal.reason;
103
- if (isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
109
+ if (reportFatal && isNetworkError(error)) options.onFatal?.(new Error("OpenCode server became unavailable."));
104
110
  throw error;
105
111
  }
106
112
  if (!acceptedStatuses.includes(response.status)) throw new OpenCodeRequestError(response.status);
@@ -112,15 +118,15 @@ export function createOpenCodeExecutor(options = {}) {
112
118
  }
113
119
  }
114
120
 
115
- async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [] }) {
121
+ async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [], onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
116
122
  if (!prompt?.trim()) throw new Error("A prompt is required.");
117
- if (stopped) throw new Error("Pipa is shutting down.");
123
+ if (stopReason) throw stopReason;
118
124
  const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
119
125
  let turnError;
120
126
 
121
127
  try {
122
128
  const files = await stageAttachments(attachments, temporaryDirectory, timeoutMs, useDataUrls);
123
- if (stopped) throw new Error("Pipa is shutting down.");
129
+ if (stopReason) throw stopReason;
124
130
  const controller = new AbortController();
125
131
  const timer = setTimeout(() => controller.abort(new Error(`OpenCode timed out after ${timeoutMs}ms.`)), timeoutMs);
126
132
  active.add(controller);
@@ -148,7 +154,29 @@ export function createOpenCodeExecutor(options = {}) {
148
154
  messages = [];
149
155
  }
150
156
 
157
+ await onSession?.(selectedSessionId);
158
+
151
159
  const baseline = new Set(messages.map((message) => message?.info?.id).filter(Boolean));
160
+ let dismissed = false;
161
+ let permissionRejected = false;
162
+ if (onInteraction) {
163
+ const watcher = watchInteractions({
164
+ baseUrl,
165
+ fetchImpl,
166
+ headers,
167
+ requestTimeoutMs,
168
+ sessionId: selectedSessionId,
169
+ workingDirectory,
170
+ controller,
171
+ onInteraction,
172
+ onPermissionReplied,
173
+ onPermissionsReconciled,
174
+ onPermissionRejected: () => { permissionRejected = true; },
175
+ onDismiss: () => { dismissed = true; },
176
+ requestTurn: request,
177
+ });
178
+ await watcher.ready;
179
+ }
152
180
  await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
153
181
  method: "POST",
154
182
  body: JSON.stringify(promptBody(prompt.trim(), files, contextEnvironment)),
@@ -161,8 +189,10 @@ export function createOpenCodeExecutor(options = {}) {
161
189
  ]);
162
190
  const finalMessage = latestAssistantMessage(currentMessages, baseline);
163
191
  const status = statuses?.[selectedSessionId]?.type;
192
+ if (dismissed && status !== "busy" && status !== "retry") return { text: "", sessionId: selectedSessionId };
164
193
  if (["error", "failed", "cancelled"].includes(status) || finalMessage?.error) throw new Error("OpenCode failed to complete the turn.");
165
194
  if (finalMessage && (status === "idle" || (!status && finalMessage.completed))) {
195
+ if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
166
196
  if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
167
197
  return { text: finalMessage.text, sessionId: selectedSessionId };
168
198
  }
@@ -175,7 +205,7 @@ export function createOpenCodeExecutor(options = {}) {
175
205
  }
176
206
  } catch (error) {
177
207
  turnError = error;
178
- if (stopped) throw new Error("Pipa is shutting down.");
208
+ if (stopReason) throw stopReason;
179
209
  throw error;
180
210
  } finally {
181
211
  if (temporaryDirectory) {
@@ -191,9 +221,9 @@ export function createOpenCodeExecutor(options = {}) {
191
221
 
192
222
  return {
193
223
  runTurn,
194
- stopAll() {
195
- stopped = true;
196
- for (const controller of active) controller.abort(new Error("Pipa is shutting down."));
224
+ stopAll(reason = new PipaStoppedError()) {
225
+ stopReason ??= reason;
226
+ for (const controller of active) controller.abort(stopReason);
197
227
  },
198
228
  };
199
229
  }
@@ -294,7 +324,7 @@ function promptBody(prompt, files, contextEnvironment) {
294
324
  const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
295
325
  return {
296
326
  parts,
297
- ...(context.length ? { system: `Runtime context for this turn:\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}` } : {}),
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")}` } : {}),
298
328
  };
299
329
  }
300
330
 
@@ -453,6 +483,188 @@ function delay(delayMs, signal) {
453
483
  });
454
484
  }
455
485
 
486
+ function watchInteractions({ baseUrl, fetchImpl, headers, requestTimeoutMs, sessionId, workingDirectory, controller, onInteraction, onPermissionReplied, onPermissionsReconciled, onPermissionRejected, onDismiss, requestTurn }) {
487
+ const seenIds = new Set();
488
+ const messages = new Map();
489
+ const parents = new Map();
490
+ const interactionSessionIds = new Set([sessionId]);
491
+ let resolveReady;
492
+ let rejectReady;
493
+ let subscribed = false;
494
+ const ready = new Promise((resolve, reject) => {
495
+ resolveReady = resolve;
496
+ rejectReady = reject;
497
+ });
498
+ const dispatch = async (event) => {
499
+ const type = event.type === "question.asked" ? "question" : event.type === "permission.asked" ? "permission" : null;
500
+ const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
501
+ const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
502
+ const requestId = properties?.requestID ?? properties?.requestId ?? properties?.id;
503
+ if (!type || (interactionSessionId !== sessionId && !await belongsToSession(interactionSessionId)) || !requestId || seenIds.has(`${type}:${requestId}`)) return;
504
+ seenIds.add(`${type}:${requestId}`);
505
+ const request = type === "permission" ? await hydratePermission(properties, interactionSessionId) : properties;
506
+ void settleInteraction({ type, requestId, sessionId: interactionSessionId, request, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn });
507
+ };
508
+
509
+ const belongsToSession = async (candidate) => {
510
+ const original = candidate;
511
+ const visited = new Set();
512
+ while (candidate && !visited.has(candidate)) {
513
+ if (candidate === sessionId) {
514
+ interactionSessionIds.add(original);
515
+ return true;
516
+ }
517
+ visited.add(candidate);
518
+ if (!parents.has(candidate)) parents.set(candidate, requestTurn(`/session/${encodeURIComponent(candidate)}`, { method: "GET" }, workingDirectory, controller)
519
+ .then((session) => session?.parentID));
520
+ candidate = await parents.get(candidate);
521
+ }
522
+ return false;
523
+ };
524
+
525
+ const hydratePermission = async (permission, interactionSessionId) => {
526
+ const tool = permission.tool;
527
+ if (!tool?.messageID || !tool.callID) return permission;
528
+ if (!messages.has(tool.messageID)) {
529
+ messages.set(tool.messageID, requestTurn(`/session/${encodeURIComponent(interactionSessionId)}/message?limit=100`, { method: "GET" }, workingDirectory, controller)
530
+ .then((items) => items.flatMap((message) => message.info?.id === tool.messageID ? message.parts ?? [] : [])));
531
+ }
532
+ const part = (await messages.get(tool.messageID)).find((item) => item.callID === tool.callID);
533
+ return part ? { ...permission, tool: { ...tool, name: part.tool, input: part.state?.input } } : permission;
534
+ };
535
+
536
+ const reconcile = async () => {
537
+ const permissions = await requestTurn("/permission", { method: "GET" }, workingDirectory, controller);
538
+ const pending = (await Promise.all((permissions ?? []).map(async (permission) => {
539
+ return await belongsToSession(permission?.sessionID) ? permission : null;
540
+ }))).filter(Boolean);
541
+ await Promise.all(pending.map((permission) => dispatch({ type: "permission.asked", properties: permission })));
542
+ for (const interactionSessionId of interactionSessionIds) {
543
+ const requests = pending.filter((permission) => permission.sessionID === interactionSessionId);
544
+ onPermissionsReconciled?.({ sessionId: interactionSessionId, requestIds: new Set(requests.map((permission) => permission.id)) });
545
+ }
546
+ };
547
+
548
+ void (async () => {
549
+ while (!controller.signal.aborted) {
550
+ try {
551
+ const url = serverUrl(baseUrl, "/event", workingDirectory);
552
+ const response = await fetchImpl(url, {
553
+ headers: { ...headers, accept: "text/event-stream" },
554
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(requestTimeoutMs)]),
555
+ });
556
+ if (!response.ok) throw new OpenCodeRequestError(response.status);
557
+ await reconcile();
558
+ if (!subscribed) {
559
+ subscribed = true;
560
+ resolveReady();
561
+ }
562
+ for await (const event of readServerSentEvents(response, controller.signal)) {
563
+ if (controller.signal.aborted) return;
564
+ const properties = event.properties && typeof event.properties === "object" ? event.properties : event.data && typeof event.data === "object" ? event.data : event;
565
+ const interactionSessionId = properties?.sessionID ?? properties?.sessionId;
566
+ if (event.type === "permission.replied" && (interactionSessionId === sessionId || await belongsToSession(interactionSessionId))) {
567
+ onPermissionReplied?.({ sessionId: interactionSessionId, requestId: properties?.requestID ?? properties?.requestId, reply: properties?.reply });
568
+ await reconcile();
569
+ continue;
570
+ }
571
+ await dispatch(event);
572
+ }
573
+ await reconcile();
574
+ await delay(250, controller.signal).catch(() => undefined);
575
+ } catch (error) {
576
+ if (controller.signal.aborted) return;
577
+ if (!subscribed) {
578
+ rejectReady(error);
579
+ return;
580
+ }
581
+ await delay(250, controller.signal).catch(() => undefined);
582
+ }
583
+ }
584
+ })();
585
+ return { ready };
586
+ }
587
+
588
+ async function settleInteraction({ type, requestId, sessionId, request: interactionRequest, onInteraction, onPermissionRejected, onDismiss, controller, workingDirectory, requestTurn }) {
589
+ try {
590
+ const decision = await abortable(Promise.resolve().then(() => onInteraction({
591
+ type,
592
+ sessionId,
593
+ request: interactionRequest,
594
+ signal: controller.signal,
595
+ })), controller.signal);
596
+ if (decision?.type === "cancelled" || decision?.type === "stopped") return;
597
+ if (decision?.type === "stop") {
598
+ onDismiss?.();
599
+ if (type === "question") await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
600
+ else await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply: "reject" }) }, workingDirectory, controller, [200, 204, 404], false);
601
+ await requestTurn(`/session/${encodeURIComponent(sessionId)}/abort`, { method: "POST" }, workingDirectory, controller, [200, 204], false);
602
+ return;
603
+ }
604
+ if (type === "question" && decision?.type === "answer") {
605
+ await requestTurn(`/question/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ answers: decision.answers }) }, workingDirectory, controller, [200, 204, 404], false);
606
+ } else if (type === "question" && decision?.type === "reject") {
607
+ await requestTurn(`/question/${encodeURIComponent(requestId)}/reject`, { method: "POST" }, workingDirectory, controller, [200, 204, 404], false);
608
+ } else if (type === "permission" && (decision?.type === "reply" || decision?.type === "reject")) {
609
+ const reply = decision.type === "reject" ? "reject" : decision.reply;
610
+ if (!["once", "always", "reject"].includes(reply)) throw new Error("Invalid OpenCode permission decision.");
611
+ if (reply === "reject") onPermissionRejected?.();
612
+ await requestTurn(`/permission/${encodeURIComponent(requestId)}/reply`, { method: "POST", body: JSON.stringify({ reply }) }, workingDirectory, controller, [200, 204, 404], false);
613
+ } else {
614
+ throw new Error(`Invalid OpenCode ${type} decision.`);
615
+ }
616
+ } catch (error) {
617
+ if (!controller.signal.aborted) process.stderr.write(`OpenCode interaction handler error: ${error.message}\n`);
618
+ }
619
+ }
620
+
621
+ async function* readServerSentEvents(response, signal) {
622
+ const reader = response.body?.getReader();
623
+ if (!reader) return;
624
+ const abort = () => reader.cancel().catch(() => undefined);
625
+ signal?.addEventListener("abort", abort, { once: true });
626
+ const decoder = new TextDecoder();
627
+ let buffer = "";
628
+ try {
629
+ while (true) {
630
+ const { done, value } = await reader.read();
631
+ if (done) break;
632
+ buffer += decoder.decode(value, { stream: true });
633
+ let boundary = buffer.indexOf("\n\n");
634
+ while (boundary >= 0) {
635
+ const chunk = buffer.slice(0, boundary);
636
+ buffer = buffer.slice(boundary + 2);
637
+ const lines = chunk.split("\n");
638
+ const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
639
+ const id = lines.find((line) => line.startsWith("id:"))?.slice(3).trim();
640
+ const type = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
641
+ if (data) {
642
+ try {
643
+ const event = JSON.parse(data);
644
+ yield type ? { id, type, data: event } : event;
645
+ } catch { /* ponytail: skip non-JSON SSE frames */ }
646
+ }
647
+ boundary = buffer.indexOf("\n\n");
648
+ }
649
+ }
650
+ } finally {
651
+ signal?.removeEventListener("abort", abort);
652
+ }
653
+ }
654
+
655
+ function abortable(operation, signal) {
656
+ if (signal.aborted) return Promise.reject(signal.reason);
657
+ return new Promise((resolve, reject) => {
658
+ const settle = (callback, value) => {
659
+ signal.removeEventListener("abort", abort);
660
+ callback(value);
661
+ };
662
+ const abort = () => settle(reject, signal.reason);
663
+ signal.addEventListener("abort", abort, { once: true });
664
+ Promise.resolve(operation).then((value) => settle(resolve, value), (error) => settle(reject, error));
665
+ });
666
+ }
667
+
456
668
  function isNetworkError(error) {
457
669
  return error instanceof TypeError || ["ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.cause?.code ?? error?.code);
458
670
  }
package/src/state.mjs CHANGED
@@ -76,6 +76,19 @@ export async function acquireInstanceLock(file = pipaPaths().lock) {
76
76
  return () => rm(file, { force: true });
77
77
  }
78
78
 
79
+ export async function stopInstance(file = pipaPaths().lock, kill = process.kill) {
80
+ const pid = Number.parseInt(await readFile(file, "utf8").catch(() => ""), 10);
81
+ if (!pid) return null;
82
+ try {
83
+ kill(pid, "SIGTERM");
84
+ return pid;
85
+ } catch (error) {
86
+ if (error?.code === "ESRCH") await rm(file, { force: true });
87
+ else throw error;
88
+ return null;
89
+ }
90
+ }
91
+
79
92
  export function createManifest(botName) {
80
93
  const name = validateBotName(botName);
81
94
  const manifest = structuredClone(MANIFEST);
@@ -114,6 +127,12 @@ export async function loadConfig(file = pipaPaths().config) {
114
127
  if (slackMode === "managed" && (!Number.isInteger(config.openCodePort) || config.openCodePort < 1 || config.openCodePort > 65535)) {
115
128
  throw new Error("Invalid Pipa config: openCodePort must be an integer from 1 to 65535.");
116
129
  }
130
+ for (const key of ["allowedSlackChannelIds", "allowedSlackUserIds"]) {
131
+ const value = config[key];
132
+ if (value !== undefined && (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim()))) {
133
+ throw new Error(`Invalid Pipa config: ${key} must be a list of non-empty Slack IDs.`);
134
+ }
135
+ }
117
136
  return { ...config, slackMode };
118
137
  }
119
138