@usepipa/pipa 0.5.6 → 0.6.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@
31
31
  | What it does | What that means |
32
32
  | --- | --- |
33
33
  | **One server** | In local mode, Pipa starts one private OpenCode server on `127.0.0.1` and reuses it for every Slack turn. Attached servers follow their own network controls. |
34
- | **Thread sessions** | A mention starts a session; replies in that thread continue it. Different threads run independently, and a newer message interrupts only its own thread. |
34
+ | **Thread sessions** | A mention starts a session; replies continue it. On OpenCode v2, messages steer native work and later background responses return to the same Slack thread. |
35
35
  | **Routines** | Schedule timezone-aware work that runs through the same agent and delivers to an exact channel or thread. |
36
36
  | **Generated files** | In local mode, long work returns as a concise summary with generated files from a private per-turn directory. Attached non-loopback servers return inline text. |
37
37
  | **Access control** | Restrict by Slack channel, human user, and bot. Allowlists are rechecked on every turn, interaction, and delivery. |
@@ -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.2` 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.2
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:
@@ -95,11 +113,25 @@ pipa init
95
113
  pipa start
96
114
  ```
97
115
 
98
- 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.
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 thread. Port `0` asks the operating system for an available port; no port configuration is required. Follow-up messages reuse the same OpenCode session without another mention. On v2, they enter OpenCode's native steering queue without Pipa cancelling the current execution. V1 retains its interrupt-and-replace behavior. Different threads remain independent.
117
+
118
+ For v2, Pipa keeps following live native session events after the first reply. The agent can say a render is running, resume when it finishes, and send the result into the same Slack thread without another message from you. Replies missed during a disconnect or restart are not recovered. Restarting preserves the conversation mapping, but background forwarding starts again only when you send another message in that thread. Pipa does not scan response history or maintain a second execution or delivery journal. Failed Slack deliveries are reported when possible, not replayed; later live replies can still arrive.
99
119
 
100
- 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.
120
+ 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.
101
121
 
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.
122
+ **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).
123
+
124
+ Pipa keeps naturally short answers inline. For deeper work, OpenCode can return a concise summary with generated files. Files are read only from a private session directory under `.pipa/artifacts` in the configured working directory and validated against the existing path, type, identity, count, and size limits. V2 keeps that directory available for later background responses; v1 clears it around each turn. 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.
125
+
126
+ 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.
127
+
128
+ 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.
129
+
130
+ ### Native v2 session context
131
+
132
+ Slack routing and attachment guidance live in a stable native session instruction entry. They remain available when background work resumes; Pipa no longer installs and removes temporary instructions around each response. Restart instructions are not repeated in every turn—an agent can use `pipa restart` and its CLI help like any other command.
133
+
134
+ Pipa no longer reads or writes `~/.pipa/opencode-recovery.json`, rejects native activity as a competing writer, or blocks unrelated threads after one session fails. Old journal files are left untouched. Existing Slack-to-session mappings are preserved.
103
135
 
104
136
  ### Access control
105
137
 
@@ -172,7 +204,7 @@ pipa start
172
204
 
173
205
  ### Choosing a model
174
206
 
175
- Type your installation's command followed by `model` in an allowed Slack channel: `/chopper model` for `Chopper`, `/pipwick model` for `Pipwick`, or the `/pipa model` compatibility alias when registered to that app. Both forms use the same private native modal, authorization checks, and setting. A loading window opens before catalog discovery, then fills with models grouped by provider. Browse or type to filter, choose a model, and Save. Save closes the window promptly; a private channel message confirms success only after fresh validation and persistence, or explains a failure. Wait for that confirmation before testing the new selection. Cancel leaves the setting unchanged. Existing channel and human-user allowlists are rechecked after discovery, on Save, during persistence, and before delivering the private result.
207
+ Type your installation's command followed by `model` in an allowed Slack channel: `/chopper model` for `Chopper`, `/pipwick model` for `Pipwick`, or the `/pipa model` compatibility alias when registered to that app. Both forms use the same private native modal, authorization checks, and setting. A loading window opens before catalog discovery, then becomes a searchable picker. Search by model name, ID or provider, choose a model, and Save. Save closes the window promptly; a private channel message confirms success only after fresh validation and persistence, or explains a failure. Wait for that confirmation before testing the new selection. Cancel leaves the setting unchanged. Existing channel and human-user allowlists are rechecked after discovery, on each search, on Save, during persistence, and before delivering the private result.
176
208
 
177
209
  The command is computed from your configured `botName`, not a hardcoded list of bot names. Pipa decomposes accented Latin characters, removes combining marks, lowercases the name, replaces runs of spaces/punctuation/other non-ASCII characters with `-`, trims edge hyphens, and limits the part after `/` to 31 characters (trimming any resulting trailing hyphen). For example, `Workshop "Bot"` becomes `/workshop-bot` and `Café 🧪` becomes `/cafe`. A valid display name with no usable ASCII slug, such as `🤖` or `東京`, falls back to `/pipa` so this optional feature cannot prevent an old profile from starting. Existing display-name validation still applies. Generated commands use a conservative lowercase-letter/digit/hyphen subset within Slack's 32-character limit including `/`.
178
210
 
@@ -182,7 +214,7 @@ The default for new threads is stored as optional `defaultModel: { "providerID":
182
214
 
183
215
  New routines snapshot the selection when created; preview JSON shows that snapshot. Existing routines and their saved model are unchanged by later saves or routine edits. A routine with no saved model uses OpenCode's default, never the current installation setting. Human replies to routine results retain the model recorded in that conversation. If a thread's provider stops working, reconnect it or choose a different default and start a new thread.
184
216
 
185
- The picker preloads the configured OpenCode model catalog into a native Slack dropdown, grouped by provider. Open the dropdown to browse immediately, or type to filter models; no search callback is needed. Groups contain up to 100 models each, with at most 100 groups. Empty catalogs or catalogs exceeding Slack's limits get a private explanation instead of an empty or truncated list. A listed model may still lack credentials or quota; saving never runs inference to check it. The provider shown beneath each result identifies the connection: `opencode` and `openai` use separate credentials, even for similarly named models. Turn failures identify the provider and HTTP status when available; authentication failures give reconnection guidance, and an explicitly expired API key is reported as expired. Raw upstream errors and credentials are not posted, and Pipa never silently switches models. Abandoned pickers expire after 30 minutes; reopen your installation's model command to continue.
217
+ The picker loads the configured OpenCode model catalog once per window, with up to 30 seconds for discovery. Searches use that cached catalog without contacting OpenCode again. Slack displays up to 100 matches at a time; type more specific terms to find models anywhere in a large catalog. Search is case-insensitive and matches all entered terms across model names, IDs and providers. The saved model remains selected even when it is outside the first 100 results. Empty catalogs get a private explanation. Save checks the current OpenCode catalog again before persisting. A listed model may still lack credentials or quota; saving never runs inference to check it. The provider shown beneath each result identifies the connection: `opencode` and `openai` use separate credentials, even for similarly named models. Turn failures identify the provider and HTTP status when available; authentication failures give reconnection guidance, and an explicitly expired API key is reported as expired. Raw upstream errors and credentials are not posted, and Pipa never silently switches models. Abandoned pickers expire after 30 minutes; reopen your installation's model command to continue.
186
218
 
187
219
  If the model window cannot open, its private error distinguishes saved-settings problems, model-catalog loading, configured access restrictions, and Slack window failures. It confirms that the saved model is unchanged; it does not expose raw upstream errors or credentials.
188
220
 
@@ -190,12 +222,12 @@ If the model window cannot open, its private error distinguishes saved-settings
190
222
 
191
223
  **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
224
 
193
- After `0.5.5` is published, use the same `PIPA_HOME` as your existing installation (leave it unset for the default `~/.pipa` profile):
225
+ To upgrade to `0.5.6`, use the same `PIPA_HOME` as your existing installation (leave it unset for the default `~/.pipa` profile):
194
226
 
195
227
  ```sh
196
- npm install --global @usepipa/pipa@0.5.5
228
+ npm install --global @usepipa/pipa@0.5.6
197
229
  pipa --version
198
- pipa manifest > "$HOME/pipa-slack-manifest-0.5.5.json"
230
+ pipa manifest > "$HOME/pipa-slack-manifest-0.5.6.json"
199
231
  ```
200
232
 
201
233
  `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 +306,8 @@ Anyone allowed by the existing Slack user and channel controls can request a res
274
306
 
275
307
  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
308
 
309
+ 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.
310
+
277
311
  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
312
 
279
313
  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 +335,9 @@ npm test
301
335
  npm run test:pack
302
336
  ```
303
337
 
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.
338
+ `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.
339
+
340
+ See the [testing strategy](docs/pipa-testing.md) for repeatable real-runtime and Slack validation, existing-app reuse, evidence, and cleanup.
305
341
 
306
342
  See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
307
343
 
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.2",
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,14 +72,18 @@ 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,
73
76
  onFatal: server.fail,
74
77
  });
78
+ await executor.ready?.(config.workingDirectory);
79
+ options.signal?.throwIfAborted();
75
80
  } catch (error) {
76
81
  server?.stop();
77
82
  await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
78
83
  throw error;
79
84
  }
80
- const runner = createConversationRunner({ sessionStore, abortTurn: executor.abortTurn, runTurn: async (input) => {
85
+ const runner = createConversationRunner({ sessionStore, abortTurn: executor.abortTurn,
86
+ interruptPrevious: () => !executor.capabilities?.backgroundResponses, runTurn: async (input) => {
81
87
  const currentConfig = await loadCurrentConfig();
82
88
  return executor.runTurn({ ...input, ...(currentConfig.defaultModel ? { defaultModel: currentConfig.defaultModel } : {}) });
83
89
  } });
@@ -177,9 +183,34 @@ 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
 
189
+ function followCallbacks(thread, message) {
190
+ const allowed = async (signal) => {
191
+ if (!accepting || signal?.aborted) return false;
192
+ const current = await loadCurrentConfig();
193
+ return isAuthorized(thread, message, current);
194
+ };
195
+ return {
196
+ onResponse: async (result, signal) => {
197
+ if (!await allowed(signal)) return;
198
+ await postResult(thread, result, signal);
199
+ if (message) await finishPendingReactions(thread.id, message, "white_check_mark");
200
+ },
201
+ onError: async (error, signal) => {
202
+ if (!await allowed(signal)) return;
203
+ await thread.post(`${config.botName} failed: ${safeError(error)}`);
204
+ if (message) await finishPendingReactions(thread.id, message, "warning");
205
+ },
206
+ onInteraction: (interaction) => interactions.onInteraction({ thread, authorize: async () => {
207
+ if (!await allowed(interaction.signal)) throw new Error("Slack destination is no longer allowed.");
208
+ }, loadAllowedUserIds: async () => (await loadCurrentConfig()).allowedSlackUserIds ?? [] }, interaction),
209
+ onPermissionReplied: interactions.onPermissionReplied,
210
+ onPermissionsReconciled: interactions.onPermissionsReconciled,
211
+ };
212
+ }
213
+
183
214
  const handle = async (thread, message, subscribe) => {
184
215
  if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message, config)) return;
185
216
  if (config.mentionOnly && !subscribe && !message.isMention) return;
@@ -191,7 +222,7 @@ export async function startPipa(options = {}) {
191
222
  const attachments = message.attachments ?? [];
192
223
  if (subscribe) await thread.subscribe();
193
224
  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.");
225
+ await thread.post("Pipa can read files up to 10 MiB each.");
195
226
  return;
196
227
  }
197
228
  if (!accepting) return;
@@ -211,6 +242,7 @@ export async function startPipa(options = {}) {
211
242
  onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
212
243
  onPermissionReplied: interactions.onPermissionReplied,
213
244
  onPermissionsReconciled: interactions.onPermissionsReconciled,
245
+ ...(executor.capabilities?.backgroundResponses ? followCallbacks(thread, message) : {}),
214
246
  startTyping: () => thread.startTyping("Working on it..."),
215
247
  deliver: (result, signal) => postResult(thread, result, signal),
216
248
  deliverFailure: (error) => thread.post(error instanceof PipaRestartingError
@@ -220,6 +252,7 @@ export async function startPipa(options = {}) {
220
252
  : `${config.botName} failed: ${safeError(error)}`),
221
253
  });
222
254
  if (result.superseded) return;
255
+ if (result.pending) return;
223
256
  await finishPendingReactions(thread.id, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
224
257
  } catch (error) {
225
258
  await finishPendingReactions(thread.id, message, "warning");
@@ -247,7 +280,7 @@ export async function startPipa(options = {}) {
247
280
  await chat.thread(conversationKey).subscribe();
248
281
  options.signal?.throwIfAborted();
249
282
  }
250
- await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
283
+ await withTimeout(chat.initialize(), options.startupTimeoutMs, "Slack Socket Mode startup timed out.", options.signal);
251
284
  options.signal?.throwIfAborted();
252
285
  await routineScheduler?.start();
253
286
  options.signal?.throwIfAborted();
@@ -288,6 +321,7 @@ export async function startPipa(options = {}) {
288
321
  await modelPicker.drain();
289
322
  await routineScheduler?.drain();
290
323
  await runner.drain();
324
+ await executor.drain?.();
291
325
  await chat.shutdown();
292
326
  server?.stop();
293
327
  await server?.wait();
@@ -318,8 +352,11 @@ export function createPipaSlackAdapter(options, drainTimeoutMs = 3_000) {
318
352
  };
319
353
  const route = adapter.routeSocketEvent.bind(adapter);
320
354
  const disconnect = adapter.disconnect.bind(adapter);
355
+ const startSocketMode = adapter.startSocketMode.bind(adapter);
321
356
  const pending = new Set();
322
357
  let disconnecting;
358
+ // SDK auth may settle after shutdown; do not create a socket in that case.
359
+ adapter.startSocketMode = (...args) => disconnecting ? Promise.resolve() : startSocketMode(...args);
323
360
  // The pinned adapter's async EventEmitter listener neither observes route
324
361
  // rejections nor drains acknowledgments before closing its Socket Mode client.
325
362
  adapter.routeSocketEvent = (...args) => {
@@ -370,9 +407,23 @@ export function createPendingInteractions(allowedUserIds = []) {
370
407
  threadId: context.thread.id,
371
408
  loadAllowedUserIds: context.loadAllowedUserIds,
372
409
  authorize: context.authorize,
410
+ native: typeof interaction.submit === "function",
411
+ };
412
+ entry.choose = async (value) => {
413
+ if (entry.busy || entry.decision !== undefined) return;
414
+ entry.busy = true;
415
+ try {
416
+ await interaction.submit?.(value);
417
+ if (!interaction.signal.aborted) entry.resolve(value);
418
+ } catch {
419
+ if (entry.decision !== undefined || interaction.signal.aborted) return;
420
+ entry.questionIndex = 0;
421
+ entry.error = "OpenCode rejected or could not confirm this response. Edit your answer and retry.";
422
+ await entry.message?.edit();
423
+ } finally { entry.busy = false; }
373
424
  };
374
425
  const decision = new Promise((resolve, reject) => {
375
- const abort = () => reject(interaction.signal.reason);
426
+ const abort = () => { entry.decision ??= { type: "stopped" }; reject(interaction.signal.reason); };
376
427
  entry.resolve = (value) => {
377
428
  if (entry.decision !== undefined) return;
378
429
  entry.decision = value;
@@ -382,7 +433,12 @@ export function createPendingInteractions(allowedUserIds = []) {
382
433
  if (interaction.signal.aborted) abort();
383
434
  else interaction.signal.addEventListener("abort", abort, { once: true });
384
435
  });
436
+ // A queued card can be cancelled before its predecessor releases the thread.
437
+ void decision.catch(() => undefined);
385
438
  pending.set(token, entry);
439
+ // Native settlement is independent of the responder callback (another client
440
+ // may answer or a location reload may cancel while this card is queued).
441
+ interaction.settled?.then(() => entry.resolve({ type: "cancelled" }), () => entry.resolve({ type: "cancelled" }));
386
442
  const requestId = interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id;
387
443
  const permissionKey = interaction.type === "permission" && requestId ? `${interaction.sessionId}:${requestId}` : null;
388
444
  if (permissionKey) permissionRequests.set(permissionKey, entry);
@@ -403,7 +459,7 @@ export function createPendingInteractions(allowedUserIds = []) {
403
459
  await submit(entry, result);
404
460
  return result;
405
461
  } finally {
406
- if (entry.decision === undefined) {
462
+ if (!entry.submitted) {
407
463
  entry.resolve?.({ type: "stopped" });
408
464
  await submit(entry, { type: "stopped" }).catch(() => undefined);
409
465
  }
@@ -416,12 +472,13 @@ export function createPendingInteractions(allowedUserIds = []) {
416
472
 
417
473
  function onPermissionReplied({ sessionId, requestId, reply }) {
418
474
  const entry = permissionRequests.get(`${sessionId}:${requestId}`);
475
+ if (entry?.native) return;
419
476
  entry?.resolve?.(reply === "reject" ? { type: "reject" } : { type: "reply", reply });
420
477
  }
421
478
 
422
479
  function onPermissionsReconciled({ sessionId, requestIds }) {
423
480
  for (const entry of permissionRequests.values()) {
424
- if (entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
481
+ if (!entry.native && entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
425
482
  }
426
483
  }
427
484
 
@@ -437,19 +494,21 @@ export function createPendingInteractions(allowedUserIds = []) {
437
494
  if (!entry) return;
438
495
  if ((event.threadId ?? event.thread?.id) !== entry.threadId) return;
439
496
  if (!await canRespond(entry, event.user)) return;
497
+ if (entry.busy || entry.decision !== undefined || entry.type === "form") return;
440
498
  if (event.actionId?.startsWith("pipa_dismiss_")) {
441
- entry.resolve?.({ type: "stop" });
499
+ await entry.choose({ type: "stop" });
442
500
  return;
443
501
  }
444
502
  if (entry.type === "permission") {
445
503
  const reply = String(event.value ?? "").split(".")[1];
446
504
  if (!["once", "always", "reject"].includes(reply)) return;
447
505
  const selectedBy = displayName(event.user?.fullName ?? event.user?.userName);
448
- entry.resolve?.(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
506
+ await entry.choose(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
449
507
  return;
450
508
  }
451
509
  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" })] }));
510
+ const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
511
+ 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
512
  return;
454
513
  }
455
514
  if (entry.type !== "question") return;
@@ -460,8 +519,14 @@ export function createPendingInteractions(allowedUserIds = []) {
460
519
  return;
461
520
  }
462
521
  if (event.actionId?.startsWith("pipa_submit_")) {
522
+ // Submit carries the current UI state even if earlier selection events arrive late.
523
+ const values = event.raw?.state?.values;
524
+ const blockId = `pipa_question_${entry.token}_${entry.questionIndex}`;
525
+ if (values && !Object.hasOwn(values, blockId)) return;
526
+ const selection = values?.[blockId]?.[`pipa_select_${entry.token}`];
527
+ if (selection) entry.answers[entry.questionIndex] = selectedAnswers(event, selection);
463
528
  if (!entry.answers[entry.questionIndex]?.length) return;
464
- advance(entry, event.user);
529
+ await advance(entry, event.user);
465
530
  return;
466
531
  }
467
532
  }
@@ -471,16 +536,18 @@ export function createPendingInteractions(allowedUserIds = []) {
471
536
  if (!entry) return;
472
537
  if (event.relatedThread?.id !== entry.threadId) return;
473
538
  if (!await canRespond(entry, event.user)) return;
539
+ if (entry.busy || entry.decision !== undefined || entry.type !== "question") return;
474
540
  const answer = event.values?.answer?.trim();
475
541
  if (!answer) return { action: "errors", errors: { answer: "Enter an answer." } };
542
+ // Custom answers intentionally replace selections rather than combine with them.
476
543
  entry.answers[entry.questionIndex] = [answer];
477
- advance(entry, event.user);
544
+ await advance(entry, event.user);
478
545
  }
479
546
 
480
- function advance(entry, user) {
547
+ async function advance(entry, user) {
481
548
  if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
482
549
  const selectedBy = displayName(user?.fullName ?? user?.userName);
483
- entry.resolve?.({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
550
+ await entry.choose({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
484
551
  }
485
552
  else entry.message?.edit();
486
553
  }
@@ -546,10 +613,12 @@ async function postInteraction(thread, entry) {
546
613
  }
547
614
 
548
615
  function renderSlackInteraction(entry) {
616
+ 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
617
  if (entry.type === "permission") {
550
618
  const resources = entry.request.patterns ?? entry.request.resources ?? [];
551
619
  return [
552
620
  slackHeader("Permission requested"),
621
+ ...(entry.error ? [slackText(entry.error)] : []),
553
622
  slackText(permissionDetail(entry.request, resources)),
554
623
  slackActions([
555
624
  slackButton(`pipa_permission_once_${entry.token}`, "Allow once", `${entry.token}.once`, "primary"),
@@ -571,7 +640,7 @@ function renderSlackInteraction(entry) {
571
640
  ...(options.length ? [slackButton(`pipa_submit_${entry.token}`, "Submit", entry.token, "primary")] : []),
572
641
  slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
573
642
  ];
574
- return [slackHeader(question.header || "Question"), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [slackActions([selector])] : []), slackActions(actions)];
643
+ 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
644
  }
576
645
 
577
646
  function renderSlackSubmitted(entry, decision) {
@@ -637,9 +706,8 @@ function slackButton(actionId, text, value, style) {
637
706
  return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
638
707
  }
639
708
 
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];
709
+ function selectedAnswers(event, action = event.raw?.actions?.find((item) => item.action_id === event.actionId)) {
710
+ const values = action?.selected_options?.map((option) => option.value) ?? [action?.selected_option?.value ?? event.value];
643
711
  return values.filter(Boolean).map((value) => String(value).split(".").slice(1).join(".")).filter(Boolean);
644
712
  }
645
713
 
@@ -653,7 +721,7 @@ function displayName(value) {
653
721
  return name ? name[0].toUpperCase() + name.slice(1) : "";
654
722
  }
655
723
 
656
- export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined }) {
724
+ export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined, interruptPrevious = () => true }) {
657
725
  const latest = new Map();
658
726
  let closed = false;
659
727
  let closeReason;
@@ -664,7 +732,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
664
732
  if (closed) return Promise.reject(closeReason);
665
733
  const previous = latest.get(conversationKey);
666
734
  const reason = new Error("Pipa replaced this turn with a newer message.");
667
- previous?.controller.abort(reason);
735
+ if (interruptPrevious()) previous?.controller.abort(reason);
668
736
  const turn = {
669
737
  controller: new AbortController(),
670
738
  generation: (previous?.generation ?? 0) + 1,
@@ -681,7 +749,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
681
749
 
682
750
  async function execute(conversationKey, current, previous, input, abortReason) {
683
751
  const { deliver, deliverFailure, startTyping, onSession, ...turn } = input;
684
- const isLatest = () => latest.get(conversationKey)?.generation === current.generation;
752
+ const isLatest = () => !interruptPrevious() || latest.get(conversationKey)?.generation === current.generation;
685
753
  const stopped = async () => {
686
754
  const error = closeReason ?? current.controller.signal.reason;
687
755
  if (!deliverFailure) throw error;
@@ -691,7 +759,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
691
759
  let result;
692
760
  try {
693
761
  if (previous) {
694
- if (previous.sessionId) await Promise.resolve(abortTurn(previous.sessionId, abortReason)).catch(() => undefined);
762
+ if (previous.sessionId && interruptPrevious()) await Promise.resolve(abortTurn(previous.sessionId, abortReason)).catch(() => undefined);
695
763
  await previous.done.catch(() => undefined);
696
764
  current.sessionId = previous.sessionId ?? current.sessionId;
697
765
  }
@@ -725,7 +793,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
725
793
  }
726
794
  if (!isLatest()) return { superseded: true };
727
795
  if (current.controller.signal.aborted) return stopped();
728
- if (deliver) await deliver(result, current.controller.signal);
796
+ if (deliver && !result.pending) await deliver(result, current.controller.signal);
729
797
  if (!isLatest()) return { superseded: true };
730
798
  if (current.controller.signal.aborted) return stopped();
731
799
  return result;
@@ -739,7 +807,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
739
807
  const aborts = [];
740
808
  for (const turn of latest.values()) {
741
809
  turn.controller.abort(closeReason);
742
- if (turn.sessionId) aborts.push(Promise.resolve(abortTurn(turn.sessionId, closeReason)).catch(() => undefined));
810
+ if (turn.sessionId && interruptPrevious()) aborts.push(Promise.resolve(abortTurn(turn.sessionId, closeReason)).catch(() => undefined));
743
811
  }
744
812
  closing = Promise.allSettled(aborts);
745
813
  },
@@ -924,15 +992,25 @@ async function finishReaction(thread, message, emoji) {
924
992
  if (emoji) await react(thread, message, emoji);
925
993
  }
926
994
 
927
- async function withTimeout(promise, timeoutMs, message) {
995
+ async function withTimeout(promise, timeoutMs, message, signal) {
928
996
  if (!promise) return;
997
+ if (timeoutMs === undefined && !signal) return promise;
929
998
  let timer;
999
+ let abort;
930
1000
  try {
931
1001
  return await Promise.race([
932
1002
  promise,
933
- new Promise((_, reject) => timer = setTimeout(() => reject(new Error(message)), timeoutMs)),
1003
+ new Promise((_, reject) => {
1004
+ if (timeoutMs !== undefined) timer = setTimeout(() => reject(new Error(message)), timeoutMs);
1005
+ if (signal) {
1006
+ abort = () => reject(signal.reason);
1007
+ if (signal.aborted) abort();
1008
+ else signal.addEventListener("abort", abort, { once: true });
1009
+ }
1010
+ }),
934
1011
  ]);
935
1012
  } finally {
936
- clearTimeout(timer);
1013
+ if (timer !== undefined) clearTimeout(timer);
1014
+ if (abort) signal.removeEventListener("abort", abort);
937
1015
  }
938
1016
  }