@usepipa/pipa 0.6.0-beta.1 → 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. |
@@ -53,11 +53,11 @@ pipa start
53
53
 
54
54
  ### Opt-in 0.6 beta
55
55
 
56
- `0.6.0-beta.1` is being prepared for controlled testing, not stable release.
56
+ `0.6.0-beta.2` is being prepared for controlled testing, not stable release.
57
57
  Once published, opt in with:
58
58
 
59
59
  ```sh
60
- npm install --global @usepipa/pipa@0.6.0-beta.1
60
+ npm install --global @usepipa/pipa@0.6.0-beta.2
61
61
  ```
62
62
 
63
63
  Normal installs keep using npm's `latest` tag; subsequent betas use `@beta`.
@@ -113,23 +113,25 @@ pipa init
113
113
  pipa start
114
114
  ```
115
115
 
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.
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.
117
119
 
118
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.
119
121
 
120
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).
121
123
 
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.
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.
123
125
 
124
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.
125
127
 
126
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.
127
129
 
128
- ### Recovering a blocked OpenCode turn
130
+ ### Native v2 session context
129
131
 
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.
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.
131
133
 
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.
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.
133
135
 
134
136
  ### Access control
135
137
 
@@ -202,7 +204,7 @@ pipa start
202
204
 
203
205
  ### Choosing a model
204
206
 
205
- 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.
206
208
 
207
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 `/`.
208
210
 
@@ -212,7 +214,7 @@ The default for new threads is stored as optional `defaultModel: { "providerID":
212
214
 
213
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.
214
216
 
215
- 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.
216
218
 
217
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.
218
220
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usepipa/pipa",
3
- "version": "0.6.0-beta.1",
3
+ "version": "0.6.0-beta.2",
4
4
  "description": "Run Pipa through Slack Socket Mode with OpenCode",
5
5
  "keywords": [
6
6
  "slack",
package/src/app.mjs CHANGED
@@ -73,7 +73,6 @@ export async function startPipa(options = {}) {
73
73
  artifactRoot: path.join(config.workingDirectory, ".pipa", "artifacts"),
74
74
  baseUrl: server.baseUrl,
75
75
  connection: server.connection,
76
- recoveryFile: paths.openCodeRecovery,
77
76
  onFatal: server.fail,
78
77
  });
79
78
  await executor.ready?.(config.workingDirectory);
@@ -83,7 +82,8 @@ export async function startPipa(options = {}) {
83
82
  await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
84
83
  throw error;
85
84
  }
86
- 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) => {
87
87
  const currentConfig = await loadCurrentConfig();
88
88
  return executor.runTurn({ ...input, ...(currentConfig.defaultModel ? { defaultModel: currentConfig.defaultModel } : {}) });
89
89
  } });
@@ -186,6 +186,31 @@ export async function startPipa(options = {}) {
186
186
  for (const entry of pending) await finishReaction(entry.thread, entry.message, entry.message === currentMessage ? emoji : null);
187
187
  };
188
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
+
189
214
  const handle = async (thread, message, subscribe) => {
190
215
  if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message, config)) return;
191
216
  if (config.mentionOnly && !subscribe && !message.isMention) return;
@@ -217,6 +242,7 @@ export async function startPipa(options = {}) {
217
242
  onInteraction: (interaction) => interactions.onInteraction(interactionContext, interaction),
218
243
  onPermissionReplied: interactions.onPermissionReplied,
219
244
  onPermissionsReconciled: interactions.onPermissionsReconciled,
245
+ ...(executor.capabilities?.backgroundResponses ? followCallbacks(thread, message) : {}),
220
246
  startTyping: () => thread.startTyping("Working on it..."),
221
247
  deliver: (result, signal) => postResult(thread, result, signal),
222
248
  deliverFailure: (error) => thread.post(error instanceof PipaRestartingError
@@ -226,6 +252,7 @@ export async function startPipa(options = {}) {
226
252
  : `${config.botName} failed: ${safeError(error)}`),
227
253
  });
228
254
  if (result.superseded) return;
255
+ if (result.pending) return;
229
256
  await finishPendingReactions(thread.id, message, result.error instanceof PipaStoppedError ? null : result.error ? "warning" : "white_check_mark");
230
257
  } catch (error) {
231
258
  await finishPendingReactions(thread.id, message, "warning");
@@ -294,6 +321,7 @@ export async function startPipa(options = {}) {
294
321
  await modelPicker.drain();
295
322
  await routineScheduler?.drain();
296
323
  await runner.drain();
324
+ await executor.drain?.();
297
325
  await chat.shutdown();
298
326
  server?.stop();
299
327
  await server?.wait();
@@ -693,7 +721,7 @@ function displayName(value) {
693
721
  return name ? name[0].toUpperCase() + name.slice(1) : "";
694
722
  }
695
723
 
696
- export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined }) {
724
+ export function createConversationRunner({ sessionStore, runTurn, abortTurn = async () => undefined, interruptPrevious = () => true }) {
697
725
  const latest = new Map();
698
726
  let closed = false;
699
727
  let closeReason;
@@ -704,7 +732,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
704
732
  if (closed) return Promise.reject(closeReason);
705
733
  const previous = latest.get(conversationKey);
706
734
  const reason = new Error("Pipa replaced this turn with a newer message.");
707
- previous?.controller.abort(reason);
735
+ if (interruptPrevious()) previous?.controller.abort(reason);
708
736
  const turn = {
709
737
  controller: new AbortController(),
710
738
  generation: (previous?.generation ?? 0) + 1,
@@ -721,7 +749,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
721
749
 
722
750
  async function execute(conversationKey, current, previous, input, abortReason) {
723
751
  const { deliver, deliverFailure, startTyping, onSession, ...turn } = input;
724
- const isLatest = () => latest.get(conversationKey)?.generation === current.generation;
752
+ const isLatest = () => !interruptPrevious() || latest.get(conversationKey)?.generation === current.generation;
725
753
  const stopped = async () => {
726
754
  const error = closeReason ?? current.controller.signal.reason;
727
755
  if (!deliverFailure) throw error;
@@ -731,7 +759,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
731
759
  let result;
732
760
  try {
733
761
  if (previous) {
734
- 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);
735
763
  await previous.done.catch(() => undefined);
736
764
  current.sessionId = previous.sessionId ?? current.sessionId;
737
765
  }
@@ -765,7 +793,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
765
793
  }
766
794
  if (!isLatest()) return { superseded: true };
767
795
  if (current.controller.signal.aborted) return stopped();
768
- if (deliver) await deliver(result, current.controller.signal);
796
+ if (deliver && !result.pending) await deliver(result, current.controller.signal);
769
797
  if (!isLatest()) return { superseded: true };
770
798
  if (current.controller.signal.aborted) return stopped();
771
799
  return result;
@@ -779,7 +807,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
779
807
  const aborts = [];
780
808
  for (const turn of latest.values()) {
781
809
  turn.controller.abort(closeReason);
782
- 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));
783
811
  }
784
812
  closing = Promise.allSettled(aborts);
785
813
  },
package/src/models.mjs CHANGED
@@ -63,27 +63,15 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
63
63
  failure = "No configured models are available. Connect a provider in OpenCode, then reopen the model picker.";
64
64
  throw new Error("empty catalog");
65
65
  }
66
- const groups = [];
67
- for (const model of models) {
68
- const label = model.providerID.slice(0, 75);
69
- if (groups.at(-1)?.label.text !== label || groups.at(-1).options.length === 100) {
70
- if (groups.length === 100) {
71
- failure = "The model catalog exceeds Slack's list limit. Reduce the configured models in OpenCode, then reopen the picker.";
72
- throw new Error("oversized catalog");
73
- }
74
- groups.push({ label: { type: "plain_text", text: label }, options: [] });
75
- }
76
- groups.at(-1).options.push(modelOption(model));
77
- }
66
+ entry.options = models.map((model) => ({ option: modelOption(model), search: `${model.providerID} ${model.modelID} ${model.name ?? ""}`.toLowerCase() }));
78
67
  const initialModel = currentConfig.defaultModel && models.find((model) => model.providerID === currentConfig.defaultModel.providerID && model.modelID === currentConfig.defaultModel.modelID);
79
- // The pinned Chat SDK cannot express grouped selects. Native Slack groups
80
- // preload more than 100 models and filter locally without options callbacks.
81
68
  failure = `Slack couldn't display the model list. Try ${command} model again in a moment.`;
82
69
  await event.adapter.webClient.views.update({ view_id: entry.viewId, view: {
83
70
  ...view, submit: { type: "plain_text", text: "Save" },
84
71
  blocks: [{ type: "input", block_id: `pipa_model_${token}`, label: { type: "plain_text", text: `Default for new ${botName} threads` },
85
- element: { type: "static_select", action_id: `pipa_model_${token}`, option_groups: groups,
86
- placeholder: { type: "plain_text", text: "Browse models or type to filter" }, ...(initialModel ? { initial_option: modelOption(initialModel) } : {}) } }],
72
+ hint: { type: "plain_text", text: "Up to 100 matches shown. Type a model name, ID or provider to narrow the results." },
73
+ element: { type: "external_select", action_id: `pipa_model_${token}`, min_query_length: 0,
74
+ placeholder: { type: "plain_text", text: "Search models or providers" }, ...(initialModel ? { initial_option: modelOption(initialModel) } : {}) } }],
87
75
  } });
88
76
  } catch (error) {
89
77
  const entry = pending.get(token);
@@ -106,6 +94,24 @@ export function createModelPicker({ chat, botName, commands, loadConfig, listMod
106
94
  }
107
95
  });
108
96
 
97
+ chat.onOptionsLoad?.(async (event) => {
98
+ if (!event.actionId?.startsWith("pipa_model_")) return;
99
+ const entry = pending.get(event.actionId.slice("pipa_model_".length));
100
+ try {
101
+ authorize(entry, event, {});
102
+ authorize(entry, event, await loadConfig());
103
+ if (pending.get(event.actionId.slice("pipa_model_".length)) !== entry || entry.saving) return [];
104
+ const terms = String(event.query ?? "").toLowerCase().trim().split(/\s+/u);
105
+ const matches = [];
106
+ for (const { option, search } of entry.options ?? []) {
107
+ if (!terms.every((term) => search.includes(term))) continue;
108
+ matches.push({ label: option.text.text, description: option.description.text, value: option.value });
109
+ if (matches.length === 100) break;
110
+ }
111
+ return matches;
112
+ } catch { return []; }
113
+ });
114
+
109
115
  chat.onModalSubmit?.("pipa_model", (event) => {
110
116
  const entry = pending.get(event.privateMetadata);
111
117
  const inputId = `pipa_model_${event.privateMetadata}`;