@usepipa/pipa 0.5.6 → 0.6.0-beta.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
@@ -51,6 +51,22 @@ pipa start
51
51
 
52
52
  `pipa init` creates the Slack app manifest, opens the install flow, and saves the profile under `~/.pipa`. Invite Pipa to a channel and mention it. The [3-minute setup video](https://www.youtube.com/watch?v=rlTMdkPWPcA) shows the flow, and the [OpenCode Slack integration guide](https://www.usepipa.com/opencode-slack?utm_source=github&utm_medium=repo_readme&utm_campaign=signup&utm_content=readme_install_guide) is the current written path.
53
53
 
54
+ ### Opt-in 0.6 beta
55
+
56
+ `0.6.0-beta.1` is being prepared for controlled testing, not stable release.
57
+ Once published, opt in with:
58
+
59
+ ```sh
60
+ npm install --global @usepipa/pipa@0.6.0-beta.1
61
+ ```
62
+
63
+ Normal installs keep using npm's `latest` tag; subsequent betas use `@beta`.
64
+ This updates Pipa only, not OpenCode. For an existing installation, arrange a
65
+ maintenance window, stop Pipa and back up its profile before installing. Keep
66
+ your current OpenCode version initially; do not rerun `pipa init` or create a
67
+ second listener. See the [beta release notes](https://github.com/lunchpaillola/pipa/blob/main/docs/beta-release.md)
68
+ for changes, limitations, and trial/rollback guidance.
69
+
54
70
  ## Security model
55
71
 
56
72
  In local mode, Pipa runs on your machine, not behind a relay. The local OpenCode server binds to `127.0.0.1` on an operating-system-assigned port; attached servers follow their own network controls. Slack access is limited by channel, user, and bot allowlists, rechecked on every turn. Tokens stay in the local profile with private file permissions, and OpenCode manages provider credentials.
@@ -68,11 +84,13 @@ Profiles created by `pipa init` use Socket Mode. Profiles written before mode su
68
84
  ### Requirements
69
85
 
70
86
  - Node.js 22 or newer
71
- - [OpenCode](https://opencode.ai) installed and authenticated
87
+ - [OpenCode](https://opencode.ai) installed and authenticated; the dual-adapter candidate selects native v1/v2 automatically (current native v2 qualification target: 2.2.5; historical v2 pin: 2.0.29; v1 pins: 1.18.35, 1.19.0; release-qualified minimums pending)
72
88
  - A Slack workspace where you can create an app
73
89
 
74
90
  Invite the Slack app only to channels whose members may use OpenCode in the configured working directory.
75
91
 
92
+ See [OpenCode compatibility](docs/opencode-compatibility.md) for remaining-on-v1 and deliberate-v2 upgrade paths, matched-snapshot rollback, capability differences and remaining release gates. Upgrading Pipa preserves the existing Slack profile; it does not require recreating the Slack app or upgrading OpenCode.
93
+
76
94
  ### Install
77
95
 
78
96
  1. Install Pipa:
@@ -97,9 +115,21 @@ pipa start
97
115
 
98
116
  Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. In owned local mode, 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.
99
117
 
118
+ Ordinary startup detects OpenCode v1/v2 and waits for listening, workspace readiness and Slack initialization without a default overall timeout or migration-status gate. OpenCode owns schema/data upgrades; Pipa never converts that data. Ctrl+C cancels startup and stops owned children, never attached servers. See the [startup contract](docs/opencode-compatibility.md#startup-contract) for retry, failure and explicit-deadline behavior.
119
+
120
+ **Managed external-client upgrade notice:** Before upgrading a Managed profile used by external OpenCode clients, set a shared explicit `OPENCODE_SERVER_PASSWORD` in the Pipa server/restart launch environment and configure that password in every external client. For v2, `OPENCODE_PASSWORD` takes precedence; match it to the shared password or remove conflicting values from the server/restart and client environments. If no explicit password is set, Pipa generates a private per-launch password unavailable to external clients, and unauthenticated clients no longer connect. Keep generated passwords private; use an explicit shared password for external access. See [OpenCode compatibility](docs/opencode-compatibility.md).
121
+
100
122
  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 total, 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.
101
123
 
102
- 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.
124
+ Incoming messages can include up to Slack's 10-file limit, with a maximum size of 10 MiB (10,485,760 bytes) per file. Pipa checks both declared size and downloaded bytes before sending the prompt. Attachments require a text prompt and are copied to a temporary directory only for the duration of the turn. Outgoing artifact limits remain 10 files and 100 MB per file or response.
125
+
126
+ For owned OpenCode v2 servers, Pipa defaults `BUN_JSC_maxRegExpStackSize` to `536870912` (a 512 MiB on-demand regular-expression stack ceiling), preserving any explicit override. This works around native 2.0.29 rejecting valid large base64 attachments. An independently launched attached v2 server needs the same setting in **its server process**, for example `BUN_JSC_maxRegExpStackSize=536870912 opencode serve`; setting it only on the attaching Pipa client cannot configure that server. The model's context/media capabilities still determine which admitted files it can process.
127
+
128
+ ### Recovering a blocked OpenCode turn
129
+
130
+ If v2 reports that cleanup failed and new intake is blocked, restore the selected server's connectivity and let any independently submitted work finish, then restart Pipa with `pipa restart`. Use `pipa restart --status` to confirm the outcome. If Pipa already exited, run `pipa start` with the same profile and working directory instead.
131
+
132
+ Startup reconciles the profile's private `~/.pipa/opencode-recovery.json` before accepting Slack or routine work. It removes only owned instructions/admissions and waits for owned execution to settle; it does not replay the failed prompt. Keep the recovery file and session mappings intact. If startup still blocks, resolve the reported server/workspace or foreign-writer conflict before trying again; deleting the recovery file would discard the evidence needed for safe cleanup. Review any partial side effects before manually retrying the original request.
103
133
 
104
134
  ### Access control
105
135
 
@@ -190,12 +220,12 @@ If the model window cannot open, its private error distinguishes saved-settings
190
220
 
191
221
  **An npm upgrade updates local code only. It does not update the installed Slack app, register commands, or grant scopes.** Existing mentions and thread replies still work without model-command registration. Do not rerun `pipa init` or replace credentials to add this feature.
192
222
 
193
- After `0.5.5` is published, use the same `PIPA_HOME` as your existing installation (leave it unset for the default `~/.pipa` profile):
223
+ To upgrade to `0.5.6`, use the same `PIPA_HOME` as your existing installation (leave it unset for the default `~/.pipa` profile):
194
224
 
195
225
  ```sh
196
- npm install --global @usepipa/pipa@0.5.5
226
+ npm install --global @usepipa/pipa@0.5.6
197
227
  pipa --version
198
- pipa manifest > "$HOME/pipa-slack-manifest-0.5.5.json"
228
+ pipa manifest > "$HOME/pipa-slack-manifest-0.5.6.json"
199
229
  ```
200
230
 
201
231
  `pipa manifest` reads the existing profile and prints the current **local template** without tokens. It does not write config, sessions, routines, or the cached manifest, call Slack, or run inference. It is not an export of your app's current remote/custom configuration.
@@ -274,6 +304,8 @@ Anyone allowed by the existing Slack user and channel controls can request a res
274
304
 
275
305
  The running Pipa launches a detached worker before stopping intake, cleaning up, and releasing its instance lock. The worker waits for the original process and lock to disappear, then starts a detached replacement and confirms workspace readiness (and Slack readiness for Socket Mode). The replacement continues in the background without terminal output; use `pipa stop` to stop it. This works for Socket and Managed profiles on supported macOS, Linux, and Windows systems. Attached OpenCode servers remain externally owned and are never stopped by Pipa.
276
306
 
307
+ On Windows, `pipa stop` forcibly terminates Pipa's owned process tree and clears only its unchanged instance lock after exit. It can interrupt active work; `pipa restart` uses the cooperative restart handoff instead.
308
+
277
309
  When a restart is requested from Slack, the bot reports that it is restarting and posts to the same thread after the replacement is ready. A manual stop instead reports that the bot will not respond until it starts again.
278
310
 
279
311
  Do not chain `pipa stop` and `pipa start` inside an agent turn: stopping owned OpenCode also kills that turn. OpenCode's `/instance/dispose` disposes an instance; it does not restart the server.
@@ -301,7 +333,9 @@ npm test
301
333
  npm run test:pack
302
334
  ```
303
335
 
304
- `npm run test:slack:routines` is a manual real-service smoke test. It requires a running local Socket Mode process plus `SLACK_USER_TOKEN`, `SLACK_TEST_CHANNEL_ID`, and `SLACK_PIPA_BOT_USER_ID`; it is not part of automatic CI.
336
+ `npm run test:slack:routines` is a manual real-service smoke test. `npm run test:slack:release -- --plan` lists the shared live gates without contacting Slack. The opt-in `--run` collector requires an isolated running Socket candidate and private inputs from `.env.example`; see the testing guide. Human/client and integration evidence remain separate mandatory gates.
337
+
338
+ See the [testing strategy](docs/pipa-testing.md) for repeatable real-runtime and Slack validation, existing-app reuse, evidence, and cleanup.
305
339
 
306
340
  See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
307
341
 
package/bin/pipa.mjs CHANGED
@@ -411,7 +411,6 @@ async function start(io) {
411
411
  let failure;
412
412
  let stopping = false;
413
413
  let ready = false;
414
- let workspaceReady = true;
415
414
  const stop = (termination = "SIGTERM", reason) => {
416
415
  stopping = true;
417
416
  app?.stop(reason);
@@ -433,18 +432,11 @@ async function start(io) {
433
432
  try {
434
433
  const config = await loadConfig();
435
434
  if (config.slackMode === "managed") {
436
- server = startOpenCodeServer(config);
435
+ server = await startOpenCodeServer(config, { signal: startup.signal });
437
436
  io.output.write(`Pipa is starting OpenCode on ${config.openCodeHostname}:${config.openCodePort}.\n`);
438
- // Ordinary Managed starts retain their lifetime even if health is unavailable.
439
- // Such an instance cannot accept cooperative restart until it is ready.
440
- try {
441
- await Promise.race([server.ready(), signal.promise]);
442
- } catch (error) {
443
- if (process.env.PIPA_RESTART_ID) throw error;
444
- process.stderr.write("Managed restart unavailable: workspace readiness failed.\n");
445
- workspaceReady = false;
446
- }
437
+ await Promise.race([server.ready(), signal.promise]);
447
438
  } else {
439
+ io.output.write("Waiting for OpenCode... Ctrl+C to stop.\n");
448
440
  app = await startPipa({ config, signal: startup.signal });
449
441
  io.output.write(app.server.owned
450
442
  ? `Pipa started a private OpenCode server at ${app.server.baseUrl}.\n`
@@ -454,7 +446,7 @@ async function start(io) {
454
446
  const lifetime = app ? app.wait() : server.wait();
455
447
  // Observe startup failures already reported by the runtime before ready IPC.
456
448
  await Promise.race([lifetime, Promise.resolve()]);
457
- if (!stopping && workspaceReady) {
449
+ if (!stopping) {
458
450
  watcher = startRestartWatcher({
459
451
  identity: releaseLock.identity,
460
452
  shutdown: () => { stop("SIGTERM", new PipaRestartingError()); return finished.promise; },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usepipa/pipa",
3
- "version": "0.5.6",
3
+ "version": "0.6.0-beta.1",
4
4
  "description": "Run Pipa through Slack Socket Mode with OpenCode",
5
5
  "keywords": [
6
6
  "slack",
@@ -21,7 +21,10 @@
21
21
  "scripts": {
22
22
  "test": "node --test",
23
23
  "test:pack": "node scripts/pack-smoke.mjs",
24
- "test:slack:routines": "node scripts/slack-routine-eval.mjs"
24
+ "test:engines": "node scripts/test-opencode-matrix.mjs",
25
+ "test:beta": "node scripts/test-opencode-matrix.mjs --smoke",
26
+ "test:slack:routines": "node scripts/slack-routine-eval.mjs",
27
+ "test:slack:release": "node scripts/slack-release-eval.mjs"
25
28
  },
26
29
  "engines": {
27
30
  "node": ">=22"
@@ -42,6 +45,7 @@
42
45
  "dependencies": {
43
46
  "@chat-adapter/slack": "4.38.1",
44
47
  "@chat-adapter/state-memory": "4.38.1",
48
+ "@opencode/client": "2.0.29",
45
49
  "chat": "4.38.1",
46
50
  "cross-spawn": "7.0.6",
47
51
  "luxon": "3.7.2"
package/src/app.mjs CHANGED
@@ -5,7 +5,7 @@ import { createSlackAdapter } from "@chat-adapter/slack";
5
5
  import { createMemoryState } from "@chat-adapter/state-memory";
6
6
  import { canonicalWorkingDirectory, createManifest, createModelSetting, createSessionStore, loadConfig, pipaPaths, saveConfig, slackCommandNames } from "./state.mjs";
7
7
  import { createModelPicker } from "./models.mjs";
8
- import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaRestartingError, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
8
+ import { checkOpenCodeConnection, createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, parseOpenCodeVersion, PipaRestartingError, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
9
9
  import { assertRoutineDestinationAllowed, createRoutineScheduler, loadRoutineState } from "./routines.mjs";
10
10
 
11
11
  class RoutineDeniedError extends Error {}
@@ -23,8 +23,10 @@ export async function initializePipa(input, options = {}) {
23
23
  allowedSlackBotIds: normalizeIdList(input.allowedSlackBotIds),
24
24
  mentionOnly: input.mentionOnly === true,
25
25
  };
26
- const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
27
- if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
26
+ const environment = options.environment ?? process.env;
27
+ const attachUrl = environment.PIPA_OPENCODE_ATTACH_URL?.trim();
28
+ if (attachUrl) await checkOpenCodeConnection(attachUrl, config.workingDirectory, options);
29
+ else parseOpenCodeVersion(await (options.checkOpenCode ?? runOpenCodeVersion)(options));
28
30
  await (options.checkSlackAppToken ?? checkSlackAppToken)(config.slackAppToken);
29
31
  const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
30
32
  warnMissingSlackScopes(slackAuth, options.warn);
@@ -70,8 +72,12 @@ export async function startPipa(options = {}) {
70
72
  executor = options.executor ?? (options.createExecutor ?? createOpenCodeExecutor)({
71
73
  artifactRoot: path.join(config.workingDirectory, ".pipa", "artifacts"),
72
74
  baseUrl: server.baseUrl,
75
+ connection: server.connection,
76
+ recoveryFile: paths.openCodeRecovery,
73
77
  onFatal: server.fail,
74
78
  });
79
+ await executor.ready?.(config.workingDirectory);
80
+ options.signal?.throwIfAborted();
75
81
  } catch (error) {
76
82
  server?.stop();
77
83
  await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
@@ -177,7 +183,7 @@ export async function startPipa(options = {}) {
177
183
  const pending = pendingReactions.get(conversationKey) ?? [];
178
184
  if (pending.at(-1)?.message !== currentMessage) return;
179
185
  pendingReactions.delete(conversationKey);
180
- for (const entry of pending) await finishReaction(entry.thread, entry.message, entry.message === currentMessage ? emoji : "white_check_mark");
186
+ for (const entry of pending) await finishReaction(entry.thread, entry.message, entry.message === currentMessage ? emoji : null);
181
187
  };
182
188
 
183
189
  const handle = async (thread, message, subscribe) => {
@@ -191,7 +197,7 @@ export async function startPipa(options = {}) {
191
197
  const attachments = message.attachments ?? [];
192
198
  if (subscribe) await thread.subscribe();
193
199
  if (attachments.some(({ size }) => size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_ATTACHMENT_BYTES))) {
194
- await thread.post("Pipa can read files up to 100 MB each.");
200
+ await thread.post("Pipa can read files up to 10 MiB each.");
195
201
  return;
196
202
  }
197
203
  if (!accepting) return;
@@ -247,7 +253,7 @@ export async function startPipa(options = {}) {
247
253
  await chat.thread(conversationKey).subscribe();
248
254
  options.signal?.throwIfAborted();
249
255
  }
250
- await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
256
+ await withTimeout(chat.initialize(), options.startupTimeoutMs, "Slack Socket Mode startup timed out.", options.signal);
251
257
  options.signal?.throwIfAborted();
252
258
  await routineScheduler?.start();
253
259
  options.signal?.throwIfAborted();
@@ -318,8 +324,11 @@ export function createPipaSlackAdapter(options, drainTimeoutMs = 3_000) {
318
324
  };
319
325
  const route = adapter.routeSocketEvent.bind(adapter);
320
326
  const disconnect = adapter.disconnect.bind(adapter);
327
+ const startSocketMode = adapter.startSocketMode.bind(adapter);
321
328
  const pending = new Set();
322
329
  let disconnecting;
330
+ // SDK auth may settle after shutdown; do not create a socket in that case.
331
+ adapter.startSocketMode = (...args) => disconnecting ? Promise.resolve() : startSocketMode(...args);
323
332
  // The pinned adapter's async EventEmitter listener neither observes route
324
333
  // rejections nor drains acknowledgments before closing its Socket Mode client.
325
334
  adapter.routeSocketEvent = (...args) => {
@@ -370,9 +379,23 @@ export function createPendingInteractions(allowedUserIds = []) {
370
379
  threadId: context.thread.id,
371
380
  loadAllowedUserIds: context.loadAllowedUserIds,
372
381
  authorize: context.authorize,
382
+ native: typeof interaction.submit === "function",
383
+ };
384
+ entry.choose = async (value) => {
385
+ if (entry.busy || entry.decision !== undefined) return;
386
+ entry.busy = true;
387
+ try {
388
+ await interaction.submit?.(value);
389
+ if (!interaction.signal.aborted) entry.resolve(value);
390
+ } catch {
391
+ if (entry.decision !== undefined || interaction.signal.aborted) return;
392
+ entry.questionIndex = 0;
393
+ entry.error = "OpenCode rejected or could not confirm this response. Edit your answer and retry.";
394
+ await entry.message?.edit();
395
+ } finally { entry.busy = false; }
373
396
  };
374
397
  const decision = new Promise((resolve, reject) => {
375
- const abort = () => reject(interaction.signal.reason);
398
+ const abort = () => { entry.decision ??= { type: "stopped" }; reject(interaction.signal.reason); };
376
399
  entry.resolve = (value) => {
377
400
  if (entry.decision !== undefined) return;
378
401
  entry.decision = value;
@@ -382,7 +405,12 @@ export function createPendingInteractions(allowedUserIds = []) {
382
405
  if (interaction.signal.aborted) abort();
383
406
  else interaction.signal.addEventListener("abort", abort, { once: true });
384
407
  });
408
+ // A queued card can be cancelled before its predecessor releases the thread.
409
+ void decision.catch(() => undefined);
385
410
  pending.set(token, entry);
411
+ // Native settlement is independent of the responder callback (another client
412
+ // may answer or a location reload may cancel while this card is queued).
413
+ interaction.settled?.then(() => entry.resolve({ type: "cancelled" }), () => entry.resolve({ type: "cancelled" }));
386
414
  const requestId = interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id;
387
415
  const permissionKey = interaction.type === "permission" && requestId ? `${interaction.sessionId}:${requestId}` : null;
388
416
  if (permissionKey) permissionRequests.set(permissionKey, entry);
@@ -403,7 +431,7 @@ export function createPendingInteractions(allowedUserIds = []) {
403
431
  await submit(entry, result);
404
432
  return result;
405
433
  } finally {
406
- if (entry.decision === undefined) {
434
+ if (!entry.submitted) {
407
435
  entry.resolve?.({ type: "stopped" });
408
436
  await submit(entry, { type: "stopped" }).catch(() => undefined);
409
437
  }
@@ -416,12 +444,13 @@ export function createPendingInteractions(allowedUserIds = []) {
416
444
 
417
445
  function onPermissionReplied({ sessionId, requestId, reply }) {
418
446
  const entry = permissionRequests.get(`${sessionId}:${requestId}`);
447
+ if (entry?.native) return;
419
448
  entry?.resolve?.(reply === "reject" ? { type: "reject" } : { type: "reply", reply });
420
449
  }
421
450
 
422
451
  function onPermissionsReconciled({ sessionId, requestIds }) {
423
452
  for (const entry of permissionRequests.values()) {
424
- if (entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
453
+ if (!entry.native && entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
425
454
  }
426
455
  }
427
456
 
@@ -437,19 +466,21 @@ export function createPendingInteractions(allowedUserIds = []) {
437
466
  if (!entry) return;
438
467
  if ((event.threadId ?? event.thread?.id) !== entry.threadId) return;
439
468
  if (!await canRespond(entry, event.user)) return;
469
+ if (entry.busy || entry.decision !== undefined || entry.type === "form") return;
440
470
  if (event.actionId?.startsWith("pipa_dismiss_")) {
441
- entry.resolve?.({ type: "stop" });
471
+ await entry.choose({ type: "stop" });
442
472
  return;
443
473
  }
444
474
  if (entry.type === "permission") {
445
475
  const reply = String(event.value ?? "").split(".")[1];
446
476
  if (!["once", "always", "reject"].includes(reply)) return;
447
477
  const selectedBy = displayName(event.user?.fullName ?? event.user?.userName);
448
- entry.resolve?.(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
478
+ await entry.choose(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
449
479
  return;
450
480
  }
451
481
  if (event.actionId?.startsWith("pipa_custom_")) {
452
- await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: token, title: "Custom answer", submitLabel: "Submit", children: [TextInput({ id: "answer", label: "Answer" })] }));
482
+ const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
483
+ await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: token, title: "Custom answer", submitLabel: "Submit", children: [TextInput({ id: "answer", label: question.multiple ? "Answer (replaces checkbox selections)" : "Answer" })] }));
453
484
  return;
454
485
  }
455
486
  if (entry.type !== "question") return;
@@ -460,8 +491,14 @@ export function createPendingInteractions(allowedUserIds = []) {
460
491
  return;
461
492
  }
462
493
  if (event.actionId?.startsWith("pipa_submit_")) {
494
+ // Submit carries the current UI state even if earlier selection events arrive late.
495
+ const values = event.raw?.state?.values;
496
+ const blockId = `pipa_question_${entry.token}_${entry.questionIndex}`;
497
+ if (values && !Object.hasOwn(values, blockId)) return;
498
+ const selection = values?.[blockId]?.[`pipa_select_${entry.token}`];
499
+ if (selection) entry.answers[entry.questionIndex] = selectedAnswers(event, selection);
463
500
  if (!entry.answers[entry.questionIndex]?.length) return;
464
- advance(entry, event.user);
501
+ await advance(entry, event.user);
465
502
  return;
466
503
  }
467
504
  }
@@ -471,16 +508,18 @@ export function createPendingInteractions(allowedUserIds = []) {
471
508
  if (!entry) return;
472
509
  if (event.relatedThread?.id !== entry.threadId) return;
473
510
  if (!await canRespond(entry, event.user)) return;
511
+ if (entry.busy || entry.decision !== undefined || entry.type !== "question") return;
474
512
  const answer = event.values?.answer?.trim();
475
513
  if (!answer) return { action: "errors", errors: { answer: "Enter an answer." } };
514
+ // Custom answers intentionally replace selections rather than combine with them.
476
515
  entry.answers[entry.questionIndex] = [answer];
477
- advance(entry, event.user);
516
+ await advance(entry, event.user);
478
517
  }
479
518
 
480
- function advance(entry, user) {
519
+ async function advance(entry, user) {
481
520
  if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
482
521
  const selectedBy = displayName(user?.fullName ?? user?.userName);
483
- entry.resolve?.({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
522
+ await entry.choose({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
484
523
  }
485
524
  else entry.message?.edit();
486
525
  }
@@ -546,10 +585,12 @@ async function postInteraction(thread, entry) {
546
585
  }
547
586
 
548
587
  function renderSlackInteraction(entry) {
588
+ if (entry.type === "form") return [slackHeader(entry.request.title || "OpenCode form"), slackText("This form requires an OpenCode client response. Pipa will remove this notice when it is settled.")];
549
589
  if (entry.type === "permission") {
550
590
  const resources = entry.request.patterns ?? entry.request.resources ?? [];
551
591
  return [
552
592
  slackHeader("Permission requested"),
593
+ ...(entry.error ? [slackText(entry.error)] : []),
553
594
  slackText(permissionDetail(entry.request, resources)),
554
595
  slackActions([
555
596
  slackButton(`pipa_permission_once_${entry.token}`, "Allow once", `${entry.token}.once`, "primary"),
@@ -571,7 +612,7 @@ function renderSlackInteraction(entry) {
571
612
  ...(options.length ? [slackButton(`pipa_submit_${entry.token}`, "Submit", entry.token, "primary")] : []),
572
613
  slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
573
614
  ];
574
- return [slackHeader(question.header || "Question"), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [slackActions([selector])] : []), slackActions(actions)];
615
+ return [slackHeader(question.header || "Question"), ...(entry.error ? [slackText(entry.error)] : []), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [{ ...slackActions([selector]), block_id: `pipa_question_${entry.token}_${entry.questionIndex}` }] : []), slackActions(actions)];
575
616
  }
576
617
 
577
618
  function renderSlackSubmitted(entry, decision) {
@@ -637,9 +678,8 @@ function slackButton(actionId, text, value, style) {
637
678
  return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
638
679
  }
639
680
 
640
- function selectedAnswers(event) {
641
- const action = event.raw?.actions?.find((item) => item.action_id === event.actionId);
642
- const values = action?.selected_options?.map((option) => option.value) ?? [event.value];
681
+ function selectedAnswers(event, action = event.raw?.actions?.find((item) => item.action_id === event.actionId)) {
682
+ const values = action?.selected_options?.map((option) => option.value) ?? [action?.selected_option?.value ?? event.value];
643
683
  return values.filter(Boolean).map((value) => String(value).split(".").slice(1).join(".")).filter(Boolean);
644
684
  }
645
685
 
@@ -924,15 +964,25 @@ async function finishReaction(thread, message, emoji) {
924
964
  if (emoji) await react(thread, message, emoji);
925
965
  }
926
966
 
927
- async function withTimeout(promise, timeoutMs, message) {
967
+ async function withTimeout(promise, timeoutMs, message, signal) {
928
968
  if (!promise) return;
969
+ if (timeoutMs === undefined && !signal) return promise;
929
970
  let timer;
971
+ let abort;
930
972
  try {
931
973
  return await Promise.race([
932
974
  promise,
933
- new Promise((_, reject) => timer = setTimeout(() => reject(new Error(message)), timeoutMs)),
975
+ new Promise((_, reject) => {
976
+ if (timeoutMs !== undefined) timer = setTimeout(() => reject(new Error(message)), timeoutMs);
977
+ if (signal) {
978
+ abort = () => reject(signal.reason);
979
+ if (signal.aborted) abort();
980
+ else signal.addEventListener("abort", abort, { once: true });
981
+ }
982
+ }),
934
983
  ]);
935
984
  } finally {
936
- clearTimeout(timer);
985
+ if (timer !== undefined) clearTimeout(timer);
986
+ if (abort) signal.removeEventListener("abort", abort);
937
987
  }
938
988
  }