@usepipa/pipa 0.5.4 → 0.5.5

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
@@ -39,7 +39,7 @@ npm install --global @usepipa/pipa
39
39
  pipa init
40
40
  ```
41
41
 
42
- `pipa init` guides you through creating and installing the Slack app and saving its local configuration. The generated manifest includes `channels:read` and `assistant:write`. If an existing installation has not granted a recommended scope, `pipa init` and `pipa start` print reauthorization guidance but continue running.
42
+ `pipa init` guides you through creating and installing the Slack app and saving its local configuration. The generated manifest includes `channels:read`, `assistant:write`, and `commands`, plus a slash command derived from your configured bot name (`Chopper` gets `/chopper`) and a `/pipa` compatibility alias. For `Pipa`, these are the same command and appear only once. Review the alias collision guidance below before installing multiple apps in one workspace. Known missing scopes produce upgrade guidance without blocking startup.
43
43
 
44
44
  3. Start Pipa:
45
45
 
@@ -110,6 +110,58 @@ export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
110
110
  pipa start
111
111
  ```
112
112
 
113
+ ### Choosing a model
114
+
115
+ 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.
116
+
117
+ 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 `/`.
118
+
119
+ **Alias collision:** [Slack slash commands are not namespaced](https://docs.slack.dev/interactivity/implementing-slash-commands/#naming_your_command). If multiple apps register `/pipa`, Slack routes it to the most recently installed app; Pipa cannot redirect it to another installation. In a multi-app workspace, keep distinct named commands and omit the generic alias from other apps' Slack manifests, or assign `/pipa` to exactly one app. Fallback-only installations also share `/pipa`; use a name with an ASCII slug if you need a distinct command. Check the installation name shown in the modal before saving. Case, punctuation, or truncation can also make different names normalize identically; choose distinct resulting names.
120
+
121
+ The default for new threads is stored as optional `defaultModel: { "providerID": "openai", "modelID": "your-model-id" }` in the existing `.pipa/config.json`. It takes effect without restarting Pipa. Existing threads keep the model recorded in their OpenCode conversation history, including across restarts, so different threads can use different models. New or empty sessions use the current default; when unset, OpenCode chooses its default. If a saved OpenCode session is no longer available, its replacement is a new session and uses the current default. This setting does not select models for separate subagents or external clients.
122
+
123
+ 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.
124
+
125
+ 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.
126
+
127
+ 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.
128
+
129
+ ### Upgrading an existing installation
130
+
131
+ **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.
132
+
133
+ After `0.5.5` is published, use the same `PIPA_HOME` as your existing installation (leave it unset for the default `~/.pipa` profile):
134
+
135
+ ```sh
136
+ npm install --global @usepipa/pipa@0.5.5
137
+ pipa --version
138
+ pipa manifest > "$HOME/pipa-slack-manifest-0.5.5.json"
139
+ ```
140
+
141
+ `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.
142
+
143
+ 1. Open your **existing app** in [Slack App Management](https://api.slack.com/apps). Keep a copy of its current remote manifest.
144
+ 2. In **App Manifest**, merge the generated `features.slash_commands` entries you want (the named command and optionally `/pipa`) and add `commands` to `oauth_config.scopes.bot`. Preserve unrelated remote settings, existing commands, scopes, Socket Mode, and interactivity. **Do not replace a customized remote manifest wholesale with the local template.** Alternatively, add the matching commands under **Slash Commands** and add the bot scope under **OAuth & Permissions**.
145
+ 3. Save, then reinstall or reauthorize that same app. Retain your current tokens unless Slack rotates them; if it does, update the existing local config securely rather than reinitializing the profile.
146
+ 4. Restart the same profile to load the upgraded runtime:
147
+
148
+ ```sh
149
+ pipa restart
150
+ pipa restart --status
151
+ ```
152
+
153
+ Restart reports **requested** first; inspect status for completion. Then try `/chopper model` (for configured `Chopper`) and `/pipa model` if the alias is registered to that app. Merely recognizing an alias in Pipa cannot bypass missing Slack registration. A known missing `commands` scope produces a warning at startup; scope metadata alone cannot verify command registration, and an absent warning does not prove it is installed.
154
+
155
+ Before npm publication, preview the feature branch from this repo without reinstalling or reinitializing your profile:
156
+
157
+ ```sh
158
+ npm ci
159
+ node bin/pipa.mjs --version
160
+ node bin/pipa.mjs manifest > "$HOME/pipa-slack-manifest-preview.json"
161
+ ```
162
+
163
+ For running the unpublished branch, use the separate test app/profile procedure in `CONTRIBUTING.md`; do not start a second Socket listener with a running installation's credentials. Renaming an app/bot in Slack alone does not update command registration or Pipa's local `botName`. A local name change needs matching Slack registration and an installation restart.
164
+
113
165
  ### Routines
114
166
 
115
167
  Local Pipa can save timezone-aware work that runs through the same OpenCode agent and delivers to one exact Slack channel or existing thread. Replies to a routine result continue the OpenCode session that produced it. Routines use the configured working directory, tools, permissions, channel allowlist, and responder allowlist.
@@ -177,6 +229,7 @@ pipa stop Stop the running local Pipa process
177
229
  pipa restart [--channel <id> [--thread <ts>]] Request a detached restart
178
230
  pipa restart --status Inspect the latest durable restart outcome
179
231
  pipa routine Create and manage local scheduled routines
232
+ pipa manifest Print the current local Slack manifest template for an existing profile
180
233
  pipa --version Print the installed version
181
234
  ```
182
235
 
package/bin/pipa.mjs CHANGED
@@ -28,11 +28,20 @@ async function main(argv = process.argv.slice(2), io = { input: stdin, output: s
28
28
  if (command === "stop") return stop(io);
29
29
  if (command === "restart") return restart(argv.slice(1), io);
30
30
  if (command === "routine") return routine(argv.slice(1), io);
31
- const usage = "Usage: pipa init | pipa start | pipa stop | pipa restart [--status] | pipa routine | pipa --version";
31
+ if (command === "manifest") return manifest(argv.slice(1), io);
32
+ const usage = "Usage: pipa init | pipa start | pipa stop | pipa restart [--status] | pipa routine | pipa manifest | pipa --version";
32
33
  if (command === "--help" || command === "-h") return io.output.write(`${usage}\n`);
33
34
  throw new Error(usage);
34
35
  }
35
36
 
37
+ async function manifest(argv, io) {
38
+ const usage = "Usage: pipa manifest\nPrint the current local Slack manifest template from the existing profile without credentials. This does not update Slack or local state.\n";
39
+ if (argv.length === 1 && ["--help", "-h"].includes(argv[0])) return io.output.write(usage);
40
+ if (argv.length) throw new Error(usage.trim());
41
+ const config = await loadConfig();
42
+ io.output.write(`${JSON.stringify(createManifest(config.botName), null, 2)}\n`);
43
+ }
44
+
36
45
  async function restart(argv, io) {
37
46
  if (argv.length === 1 && ["--help", "-h"].includes(argv[0])) {
38
47
  io.output.write("Usage: pipa restart [--status] [--channel <id> [--thread <ts>]]\nRequest a detached restart, or inspect its latest durable outcome.\n");
@@ -137,7 +146,7 @@ async function routine(argv, io) {
137
146
  const changes = await routineInput(values, command === "create", now, config.workingDirectory);
138
147
  const options = { now, allowedChannelIds: config.allowedSlackChannelIds ?? [] };
139
148
  const result = command === "create"
140
- ? await createRoutine({ id, ...changes }, { ...options, preview: values.preview === true })
149
+ ? await createRoutine({ id, ...changes, model: config.defaultModel ?? null }, { ...options, preview: values.preview === true })
141
150
  : await editRoutine(id, changes, options);
142
151
  const preview = command === "create" && values.preview === true;
143
152
  return writeRoutineResult(io.output, json, { routine: result, ...(preview ? { preview: true } : {}) }, preview
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usepipa/pipa",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Run Pipa through Slack Socket Mode with OpenCode",
5
5
  "keywords": [
6
6
  "slack",
package/src/app.mjs CHANGED
@@ -3,7 +3,8 @@ import path from "node:path";
3
3
  import { Chat, Modal, TextInput } from "chat";
4
4
  import { createSlackAdapter } from "@chat-adapter/slack";
5
5
  import { createMemoryState } from "@chat-adapter/state-memory";
6
- import { canonicalWorkingDirectory, createManifest, createSessionStore, loadConfig, pipaPaths, saveConfig } from "./state.mjs";
6
+ import { canonicalWorkingDirectory, createManifest, createModelSetting, createSessionStore, loadConfig, pipaPaths, saveConfig, slackCommandNames } from "./state.mjs";
7
+ import { createModelPicker } from "./models.mjs";
7
8
  import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaRestartingError, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
8
9
  import { assertRoutineDestinationAllowed, createRoutineScheduler, loadRoutineState } from "./routines.mjs";
9
10
 
@@ -35,6 +36,8 @@ export async function startPipa(options = {}) {
35
36
  options.signal?.throwIfAborted();
36
37
  const paths = options.paths ?? pipaPaths();
37
38
  const config = options.config ?? await loadConfig(paths.config);
39
+ const commands = slackCommandNames(config.botName);
40
+ const loadCurrentConfig = options.loadCurrentConfig ?? (() => loadConfig(paths.config));
38
41
  options.signal?.throwIfAborted();
39
42
  const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
40
43
  options.signal?.throwIfAborted();
@@ -44,7 +47,7 @@ export async function startPipa(options = {}) {
44
47
  const state = options.state ?? createMemoryState();
45
48
  const chat = options.chat ?? new Chat({
46
49
  adapters: {
47
- slack: createSlackAdapter({
50
+ slack: createPipaSlackAdapter({
48
51
  appToken: config.slackAppToken,
49
52
  botToken: config.slackBotToken,
50
53
  mode: "socket",
@@ -73,7 +76,10 @@ export async function startPipa(options = {}) {
73
76
  await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
74
77
  throw error;
75
78
  }
76
- const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn, abortTurn: executor.abortTurn });
79
+ const runner = createConversationRunner({ sessionStore, abortTurn: executor.abortTurn, runTurn: async (input) => {
80
+ const currentConfig = await loadCurrentConfig();
81
+ return executor.runTurn({ ...input, ...(currentConfig.defaultModel ? { defaultModel: currentConfig.defaultModel } : {}) });
82
+ } });
77
83
  let accepting = true;
78
84
  const interactions = createPendingInteractions(config.allowedSlackUserIds);
79
85
  const pendingReactions = new Map();
@@ -119,6 +125,7 @@ export async function startPipa(options = {}) {
119
125
  try {
120
126
  result = await executor.runTurn({
121
127
  prompt: snapshot.prompt,
128
+ ...(snapshot.model ? { model: snapshot.model } : {}),
122
129
  sessionId: null,
123
130
  workingDirectory: config.workingDirectory,
124
131
  contextEnvironment: {
@@ -160,6 +167,8 @@ export async function startPipa(options = {}) {
160
167
  return { status: "succeeded" };
161
168
  },
162
169
  }) : null;
170
+ const modelPicker = createModelPicker({ chat, botName: config.botName, commands, loadConfig: loadCurrentConfig,
171
+ listModels: () => executor.listModels(config.workingDirectory), setting: createModelSetting(paths.config) });
163
172
  chat.onAction?.(interactions.onAction);
164
173
  chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
165
174
 
@@ -221,6 +230,7 @@ export async function startPipa(options = {}) {
221
230
  const stop = (reason = new PipaStoppedError()) => {
222
231
  if (!accepting) return;
223
232
  accepting = false;
233
+ modelPicker.close();
224
234
  routineScheduler?.stop(reason);
225
235
  runner.close(reason);
226
236
  executor.stopAll(reason);
@@ -241,6 +251,7 @@ export async function startPipa(options = {}) {
241
251
  options.signal?.throwIfAborted();
242
252
  } catch (error) {
243
253
  options.signal?.removeEventListener("abort", cancelled);
254
+ modelPicker.close();
244
255
  routineScheduler?.stop(error);
245
256
  await routineScheduler?.drain();
246
257
  await withTimeout(interactions.close(), options.shutdownTimeoutMs ?? 15_000, "Interaction shutdown timed out.").catch(() => undefined);
@@ -272,6 +283,7 @@ export async function startPipa(options = {}) {
272
283
  try {
273
284
  await withTimeout((async () => {
274
285
  await interactions.close();
286
+ await modelPicker.drain();
275
287
  await routineScheduler?.drain();
276
288
  await runner.drain();
277
289
  await chat.shutdown();
@@ -285,6 +297,58 @@ export async function startPipa(options = {}) {
285
297
  };
286
298
  }
287
299
 
300
+ export function createPipaSlackAdapter(options, drainTimeoutMs = 3_000) {
301
+ const adapter = createSlackAdapter(options);
302
+ const slashCommand = adapter.handleSlashCommand.bind(adapter);
303
+ const commands = slackCommandNames(options.userName ?? "Pipa");
304
+ adapter.handleSlashCommand = async (params, context) => {
305
+ if (!adapter.chat || !commands.includes(params.get("command")) || params.get("text")?.trim() !== "model") return slashCommand(params, context);
306
+ // The pinned SDK awaits users.info before dispatch. Picker authorization needs
307
+ // only envelope IDs; optional profile enrichment must not expire the trigger.
308
+ const userId = params.get("user_id") ?? "";
309
+ adapter.chat.processSlashCommand({
310
+ command: params.get("command"), text: params.get("text"),
311
+ user: { userId, userName: params.get("user_name") || userId, fullName: params.get("user_name") || userId, isBot: false, isMe: false },
312
+ adapter, raw: Object.fromEntries(params), triggerId: params.get("trigger_id") || undefined,
313
+ channelId: params.get("channel_id") ? `slack:${params.get("channel_id")}` : "",
314
+ }, context);
315
+ return new Response("", { status: 200 });
316
+ };
317
+ const route = adapter.routeSocketEvent.bind(adapter);
318
+ const disconnect = adapter.disconnect.bind(adapter);
319
+ const pending = new Set();
320
+ let disconnecting;
321
+ // The pinned adapter's async EventEmitter listener neither observes route
322
+ // rejections nor drains acknowledgments before closing its Socket Mode client.
323
+ adapter.routeSocketEvent = (...args) => {
324
+ if (disconnecting) return Promise.resolve();
325
+ const task = (async () => {
326
+ try {
327
+ await route(...args);
328
+ } catch {
329
+ // SDK errors can contain payloads/tokens; keep diagnostics credential-free.
330
+ adapter.logger.error("Pipa Slack Socket Mode event failed.");
331
+ }
332
+ })();
333
+ pending.add(task);
334
+ void task.then(() => pending.delete(task));
335
+ return task;
336
+ };
337
+ adapter.disconnect = () => disconnecting ??= (async () => {
338
+ // Stop ingress before draining; otherwise a new envelope can arrive while
339
+ // SocketModeClient.disconnect() is closing the WebSocket and fail its ack.
340
+ adapter.socketClient?.removeAllListeners("slack_event");
341
+ try {
342
+ await withTimeout(Promise.all([...pending]), drainTimeoutMs, "Slack acknowledgment drain timed out.");
343
+ } catch {
344
+ adapter.logger.error("Pipa Slack acknowledgment drain timed out.");
345
+ } finally {
346
+ await disconnect();
347
+ }
348
+ })();
349
+ return adapter;
350
+ }
351
+
288
352
  export function createPendingInteractions(allowedUserIds = []) {
289
353
  const pending = new Map();
290
354
  const permissionRequests = new Map();
@@ -759,10 +823,10 @@ function normalizeGrantedScopes(value) {
759
823
  function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`${message}\n`)) {
760
824
  if (!Array.isArray(auth?.grantedScopes)) return;
761
825
  const missing = ["channels:read", "assistant:write"].filter((scope) => !auth.grantedScopes.includes(scope));
762
- if (!missing.length) return;
763
826
  const scopes = missing.join(", ");
764
827
  try {
765
- warn(`Pipa warning: Slack bot token is missing recommended ${missing.length === 1 ? "scope" : "scopes"} ${scopes}. Add ${missing.length === 1 ? "it" : "them"} and reinstall or reauthorize the Slack app.`);
828
+ if (missing.length) warn(`Pipa warning: Slack bot token is missing recommended ${missing.length === 1 ? "scope" : "scopes"} ${scopes}. Add ${missing.length === 1 ? "it" : "them"} and reinstall or reauthorize the Slack app.`);
829
+ if (!auth.grantedScopes.includes("commands")) warn("Pipa warning: Slack bot token is missing the commands scope. Model slash commands are unavailable until matching commands are registered and granted in Slack. Run `pipa manifest` for the local template, merge the command definitions and commands scope into your existing Slack app, then reinstall or reauthorize it. Existing mentions and thread replies can continue; do not rerun `pipa init`.");
766
830
  } catch {}
767
831
  }
768
832
 
package/src/models.mjs ADDED
@@ -0,0 +1,156 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+
3
+ function modelOption(model) {
4
+ return {
5
+ text: { type: "plain_text", text: (model.name || model.modelID).slice(0, 75) },
6
+ description: { type: "plain_text", text: `${model.providerID} / ${model.modelID}`.slice(0, 75) },
7
+ value: createHash("sha256").update(JSON.stringify([model.providerID, model.modelID])).digest("hex"),
8
+ };
9
+ }
10
+
11
+ export function createModelPicker({ chat, botName, commands, loadConfig, listModels, setting, now = Date.now }) {
12
+ const command = commands[0];
13
+ const pending = new Map();
14
+ const saves = new Set();
15
+ let closed = false;
16
+ const userId = (event) => event.user?.userId ?? event.user?.id;
17
+ const authorize = (entry, event, config) => {
18
+ if (closed || !entry || entry.expires <= now() || entry.userId !== userId(event)
19
+ || (entry.viewId && entry.viewId !== (event.viewId ?? event.raw?.view?.id))
20
+ || (config.allowedSlackUserIds?.length && !config.allowedSlackUserIds.includes(entry.userId))
21
+ || (config.allowedSlackChannelIds?.length && !config.allowedSlackChannelIds.includes(entry.channelId))) {
22
+ throw new Error(`This picker is unavailable or you are not authorized. Reopen ${command} model.`);
23
+ }
24
+ };
25
+ chat.onSlashCommand?.(commands, async (event) => {
26
+ const reply = (text) => event.channel.postEphemeral(event.user, text, { fallbackToDM: false });
27
+ if (closed) return;
28
+ if (event.text.trim() !== "model") return reply(`Use ${command} model to choose the default for this Pipa installation.`);
29
+ let token;
30
+ let failure = `I couldn't read ${botName}'s saved settings. Try ${command} model again in a moment.`;
31
+ try {
32
+ const config = await loadConfig();
33
+ const channelId = event.channel.id.split(":")[1];
34
+ failure = "Model selection isn't enabled for this account or channel. Ask the installation owner to update its access settings.";
35
+ if (!/^[CG][A-Z0-9]+$/u.test(channelId ?? "") || !userId(event) || event.user?.isBot) throw new Error("denied");
36
+ const entry = { userId: userId(event), channelId, expires: now() + 30 * 60_000 };
37
+ authorize(entry, event, config);
38
+ for (const [id, context] of pending) if (context.expires <= now()) pending.delete(id);
39
+ // ponytail: bound abandoned modals in memory; reopen when the oldest context is evicted.
40
+ if (pending.size >= 1000) pending.delete(pending.keys().next().value);
41
+ token = randomUUID();
42
+ pending.set(token, entry);
43
+ const view = {
44
+ type: "modal", callback_id: "pipa_model", private_metadata: JSON.stringify({ m: token }), notify_on_close: true,
45
+ title: { type: "plain_text", text: "Pipa model" }, close: { type: "plain_text", text: "Cancel" },
46
+ };
47
+ failure = `Slack couldn't open the model window. Try ${command} model again in a moment.`;
48
+ // Exchange Slack's short-lived trigger before waiting on catalog discovery.
49
+ const opened = await event.adapter.webClient.views.open({ trigger_id: event.triggerId,
50
+ view: { ...view, blocks: [{ type: "section", text: { type: "plain_text", text: "Loading available models…" } }] } });
51
+ if (!opened?.view?.id) throw new Error("modal unavailable");
52
+ entry.viewId = opened.view.id;
53
+ failure = `I couldn't load the available models from OpenCode. Try ${command} model again in a moment.`;
54
+ const models = await listModels();
55
+ if (closed || !pending.has(token)) return;
56
+ failure = `I couldn't read ${botName}'s saved settings. Try ${command} model again in a moment.`;
57
+ const currentConfig = await loadConfig();
58
+ if (closed || pending.get(token) !== entry) return;
59
+ failure = "Model selection isn't enabled for this account or channel. Ask the installation owner to update its access settings.";
60
+ authorize(entry, { ...event, viewId: entry.viewId }, currentConfig);
61
+ failure = "I couldn't prepare the model list. This is a Pipa issue, not an access problem.";
62
+ if (!models.length) {
63
+ failure = "No configured models are available. Connect a provider in OpenCode, then reopen the model picker.";
64
+ throw new Error("empty catalog");
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
+ }
78
+ 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
+ failure = `Slack couldn't display the model list. Try ${command} model again in a moment.`;
82
+ await event.adapter.webClient.views.update({ view_id: entry.viewId, view: {
83
+ ...view, submit: { type: "plain_text", text: "Save" },
84
+ 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) } : {}) } }],
87
+ } });
88
+ } catch (error) {
89
+ const entry = pending.get(token);
90
+ pending.delete(token);
91
+ if (closed || (token && !entry)) return;
92
+ if (error?.data?.error === "expired_trigger_id") failure = `Slack's request to open this window expired. Run ${command} model again.`;
93
+ if (error?.data?.error === "invalid_trigger_id") failure = `Slack couldn't use the request to open this window. Run ${command} model again.`;
94
+ if (error?.data?.error === "invalid_arguments") failure = "Slack rejected the model window. This is a Pipa issue, not an access problem.";
95
+ const message = `${failure} Your saved model hasn't changed.`;
96
+ if (entry?.viewId) {
97
+ try {
98
+ await event.adapter.webClient.views.update({ view_id: entry.viewId, view: {
99
+ type: "modal", callback_id: "pipa_model_notice", title: { type: "plain_text", text: "Pipa model" }, close: { type: "plain_text", text: "Close" },
100
+ blocks: [{ type: "section", text: { type: "plain_text", text: message } }],
101
+ } });
102
+ return;
103
+ } catch { /* Fall back to a private message if Slack cannot update the window. */ }
104
+ }
105
+ await reply(message);
106
+ }
107
+ });
108
+
109
+ chat.onModalSubmit?.("pipa_model", (event) => {
110
+ const entry = pending.get(event.privateMetadata);
111
+ const inputId = `pipa_model_${event.privateMetadata}`;
112
+ try {
113
+ authorize(entry, event, {});
114
+ } catch {
115
+ return { action: "errors", errors: { [inputId]: `I couldn't verify this model change. Reopen ${command} model. Your saved model hasn't changed.` } };
116
+ }
117
+ if (entry.saving) return { action: "close" };
118
+ entry.saving = true;
119
+ // Acknowledge Save before config I/O as well as catalog/network/persistence work.
120
+ const task = (async () => {
121
+ let message;
122
+ let failure = `I couldn't verify this model change. Reopen ${command} model. Your saved model hasn't changed.`;
123
+ try {
124
+ try {
125
+ authorize(entry, event, await loadConfig());
126
+ failure = `I couldn't check the available models in OpenCode. Reopen ${command} model to try again. Your saved model hasn't changed.`;
127
+ const models = await listModels();
128
+ const model = models.find((item) => modelOption(item).value === event.values?.[inputId]);
129
+ failure = `That model is no longer available. Reopen ${command} model and choose another. Your saved model hasn't changed.`;
130
+ if (!model) throw new Error("unavailable model");
131
+ failure = `I couldn't save your model choice. Reopen ${command} model to try again. Your saved model hasn't changed.`;
132
+ await setting.save({ providerID: model.providerID, modelID: model.modelID }, (config) => authorize(entry, event, config));
133
+ message = `New threads will use ${model.name || model.modelID}.`;
134
+ } catch {
135
+ message = failure;
136
+ }
137
+ if (closed) return;
138
+ authorize(entry, event, await loadConfig());
139
+ await event.adapter.postEphemeral(`slack:${entry.channelId}`, entry.userId, message);
140
+ } finally {
141
+ pending.delete(event.privateMetadata);
142
+ }
143
+ })();
144
+ saves.add(task);
145
+ void task.then(() => saves.delete(task), () => {
146
+ saves.delete(task);
147
+ if (!closed) process.stderr.write("Pipa could not deliver a private model-save result.\n");
148
+ });
149
+ return { action: "close" };
150
+ });
151
+ chat.onModalClose?.("pipa_model", (event) => {
152
+ const entry = pending.get(event.privateMetadata);
153
+ if (entry?.userId === userId(event) && !entry.saving) pending.delete(event.privateMetadata);
154
+ });
155
+ return { close() { closed = true; pending.clear(); }, async drain() { await Promise.allSettled([...saves]); } };
156
+ }
package/src/opencode.mjs CHANGED
@@ -4,6 +4,7 @@ import { chmod, lstat, mkdir, mkdtemp, open, realpath, rm, writeFile } from "nod
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { pathToFileURL } from "node:url";
7
+ import { normalizeModel } from "./state.mjs";
7
8
 
8
9
  const SLACK_SECRET_ENV_KEY = /(?:^|_)SLACK(?:_[A-Z0-9]+)*_(?:TOKEN|SECRET)$/iu;
9
10
  const LISTENING_URL = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):\d+/u;
@@ -124,9 +125,11 @@ export function createOpenCodeExecutor(options = {}) {
124
125
  }
125
126
  }
126
127
 
127
- async function runTurn({ prompt, sessionId, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
128
+ async function runTurn({ prompt, sessionId, model, defaultModel, workingDirectory, contextEnvironment = {}, attachments = [], signal, onSession, onInteraction, onPermissionReplied, onPermissionsReconciled }) {
128
129
  if (!prompt?.trim()) throw new Error("A prompt is required.");
129
130
  if (stopReason) throw stopReason;
131
+ let selectedModel = normalizeModel(model);
132
+ const newThreadModel = normalizeModel(defaultModel);
130
133
  const temporaryDirectory = attachments.length ? await mkdtemp(path.join(os.tmpdir(), "pipa-files-")) : null;
131
134
  const slackTurn = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack";
132
135
  const controller = new AbortController();
@@ -162,6 +165,13 @@ export function createOpenCodeExecutor(options = {}) {
162
165
  messages = [];
163
166
  }
164
167
 
168
+ if (!selectedModel) {
169
+ // OpenCode history persists the thread's model, including interrupted user turns.
170
+ const last = messages.at(-1)?.info;
171
+ const threadModel = last?.role === "user" ? last.model
172
+ : last?.providerID && last?.modelID ? { providerID: last.providerID, modelID: last.modelID } : null;
173
+ selectedModel = normalizeModel(threadModel) ?? newThreadModel;
174
+ }
165
175
  activeSessions.set(selectedSessionId, { controller, workingDirectory });
166
176
  await onSession?.(selectedSessionId);
167
177
  if (controller.signal.aborted) throw controller.signal.reason;
@@ -198,7 +208,7 @@ export function createOpenCodeExecutor(options = {}) {
198
208
  }
199
209
  await request(`/session/${encodeURIComponent(selectedSessionId)}/prompt_async`, {
200
210
  method: "POST",
201
- body: JSON.stringify(promptBody(prompt, files, contextEnvironment, artifactDirectory)),
211
+ body: JSON.stringify({ ...promptBody(prompt, files, contextEnvironment, artifactDirectory), ...(selectedModel ? { model: selectedModel } : {}) }),
202
212
  }, workingDirectory, controller, [204]);
203
213
 
204
214
  while (true) {
@@ -209,7 +219,22 @@ export function createOpenCodeExecutor(options = {}) {
209
219
  const finalMessage = latestAssistantMessage(currentMessages, baseline);
210
220
  const status = statuses?.[selectedSessionId]?.type;
211
221
  if (dismissed && status !== "busy" && status !== "retry") return { text: "", sessionId: selectedSessionId };
212
- if (["error", "failed", "cancelled"].includes(status) || finalMessage?.error) throw new Error("OpenCode failed to complete the turn.");
222
+ if (finalMessage?.error) {
223
+ const error = finalMessage.error;
224
+ const providerID = finalMessage.providerID ?? selectedModel?.providerID;
225
+ const provider = typeof providerID === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/iu.test(providerID) ? `provider "${providerID}"` : "selected provider";
226
+ const statusCode = error.data?.statusCode;
227
+ const http = Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599 ? ` (HTTP ${statusCode})` : "";
228
+ // Classify upstream failures without exposing response bodies, headers, or credentials.
229
+ if (statusCode === 401 || error.name === "ProviderAuthError") {
230
+ const expiredKey = statusCode === 401 && typeof error.data?.message === "string" && /\bAPI key (?:has )?expired\b/iu.test(error.data.message);
231
+ throw new Error(expiredKey
232
+ ? `OpenCode ${provider} API key has expired. Replace that provider's API key in OpenCode, or choose another provider with your installation's model command, then start a new thread.`
233
+ : `OpenCode ${provider} authentication failed${http}. Reconnect that provider in OpenCode, or choose another provider with your installation's model command, then start a new thread.`);
234
+ }
235
+ throw new Error(`OpenCode ${provider} ${http ? `failed${http}` : "failed to complete the turn"}.`);
236
+ }
237
+ if (["error", "failed", "cancelled"].includes(status)) throw new Error("OpenCode failed to complete the turn.");
213
238
  if (finalMessage && ((status !== "retry" && finalMessage.completed && finalMessage.finish === "stop") || status === "idle" || (!status && finalMessage.completed))) {
214
239
  if (!finalMessage.text && permissionRejected) return { text: "Stopped after a permission was rejected.", sessionId: selectedSessionId };
215
240
  if (!finalMessage.text) throw new Error("OpenCode completed without assistant text.");
@@ -254,6 +279,26 @@ export function createOpenCodeExecutor(options = {}) {
254
279
 
255
280
  return {
256
281
  runTurn,
282
+ async listModels(workingDirectory) {
283
+ if (stopReason) throw stopReason;
284
+ const controller = new AbortController();
285
+ const timer = setTimeout(() => controller.abort(new Error("Model discovery timed out.")), 1_500);
286
+ active.add(controller);
287
+ try {
288
+ const catalog = await request("/config/providers", { method: "GET" }, workingDirectory, controller, [200], false);
289
+ if (!Array.isArray(catalog?.providers)) throw new Error("OpenCode returned an invalid model catalog.");
290
+ return catalog.providers.flatMap((provider) => {
291
+ if (!provider?.models || typeof provider.models !== "object" || Array.isArray(provider.models)) throw new Error("Invalid provider models.");
292
+ return Object.entries(provider.models).map(([id, model]) => ({
293
+ ...normalizeModel({ providerID: provider.id, modelID: model.id ?? id }),
294
+ name: typeof model.name === "string" ? model.name : id,
295
+ }));
296
+ });
297
+ } finally {
298
+ clearTimeout(timer);
299
+ active.delete(controller);
300
+ }
301
+ },
257
302
  async abortTurn(sessionId, reason = new Error("OpenCode turn aborted.")) {
258
303
  const turn = activeSessions.get(sessionId);
259
304
  if (!turn) return;
@@ -487,6 +532,7 @@ function latestAssistantMessage(messages, baseline) {
487
532
  if (!message?.info?.id || baseline.has(message.info.id) || message.info.role !== "assistant") continue;
488
533
  return {
489
534
  completed: typeof message.info.time?.completed === "number",
535
+ providerID: message.info.providerID,
490
536
  error: message.info.error,
491
537
  finish: message.info.finish,
492
538
  text: message.parts
package/src/routines.mjs CHANGED
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  import { DateTime, IANAZone } from "luxon";
7
- import { pipaPaths, writePrivateJson } from "./state.mjs";
7
+ import { normalizeModel, pipaPaths, writePrivateJson } from "./state.mjs";
8
8
 
9
9
  const FREQUENCIES = new Set(["minutes", "hours", "daily", "weekly"]);
10
10
  const STATUSES = new Set(["active", "inactive", "completed"]);
@@ -74,6 +74,7 @@ export function normalizeRoutine(input, now = DateTime.utc().toISO()) {
74
74
  return {
75
75
  id,
76
76
  prompt: input.prompt,
77
+ ...(input.model === undefined ? {} : { model: normalizeModel(input.model) }),
77
78
  schedule,
78
79
  timezone: input.timezone,
79
80
  destination,
@@ -464,7 +465,8 @@ function validateRoutineState(state) {
464
465
 
465
466
  function validateCanonicalRoutine(routine) {
466
467
  if (!routine || typeof routine !== "object" || Array.isArray(routine)) invalidState("routine must be an object");
467
- requireKeys(routine, ["id", "prompt", "schedule", "timezone", "destination", "status", "nextRunAt", "runRequestedAt", "createdAt", "updatedAt", "lastRun"], "routine");
468
+ requireKeys(routine, ["id", "prompt", "schedule", "timezone", "destination", "status", "nextRunAt", "runRequestedAt", "createdAt", "updatedAt", "lastRun", ...(Object.hasOwn(routine, "model") ? ["model"] : [])], "routine");
469
+ normalizeModel(routine.model);
468
470
  requiredString(routine.id, "id", invalidState);
469
471
  if (typeof routine.prompt !== "string" || !routine.prompt.trim()) invalidState("prompt is empty");
470
472
  validateTimezone(routine.timezone, invalidState);
package/src/state.mjs CHANGED
@@ -12,6 +12,7 @@ const MANIFEST = {
12
12
  long_description: "Pippette connects Slack to the OpenCode installed on your computer. Send text requests from Slack and receive replies in threads for the local folder you choose. OpenCode runs locally, and your Slack credentials stay on your machine. Learn more at usepipa.com.",
13
13
  },
14
14
  features: {
15
+ slash_commands: [{ description: "Configure this Pipa installation", usage_hint: "model", should_escape: false }],
15
16
  bot_user: {
16
17
  display_name: "Pippette",
17
18
  always_online: true,
@@ -21,6 +22,7 @@ const MANIFEST = {
21
22
  scopes: {
22
23
  user: ["files:read", "files:write"],
23
24
  bot: [
25
+ "commands",
24
26
  "files:read",
25
27
  "app_mentions:read",
26
28
  "assistant:write",
@@ -132,9 +134,21 @@ export function createManifest(botName) {
132
134
  manifest.display_information.description = manifest.display_information.description.replaceAll("Pippette", name);
133
135
  manifest.display_information.long_description = manifest.display_information.long_description.replaceAll("Pippette", name);
134
136
  manifest.features.bot_user.display_name = name;
137
+ const commandTemplate = manifest.features.slash_commands[0];
138
+ manifest.features.slash_commands = slackCommandNames(name).map((command) => ({ ...commandTemplate, command }));
135
139
  return manifest;
136
140
  }
137
141
 
142
+ export function slackCommandName(botName) {
143
+ const slug = validateBotName(botName).normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase()
144
+ .replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 31).replace(/-+$/u, "");
145
+ return slug ? `/${slug}` : "/pipa";
146
+ }
147
+
148
+ export function slackCommandNames(botName) {
149
+ return [...new Set([slackCommandName(botName), "/pipa"])];
150
+ }
151
+
138
152
  export function createManifestUrl(manifest) {
139
153
  return `https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(manifest))}`;
140
154
  }
@@ -169,9 +183,38 @@ export async function loadConfig(file = pipaPaths().config) {
169
183
  throw new Error(`Invalid Pipa config: ${key} must be a list of non-empty Slack IDs.`);
170
184
  }
171
185
  }
186
+ normalizeModel(config.defaultModel);
172
187
  return { ...config, slackMode };
173
188
  }
174
189
 
190
+ export function normalizeModel(value) {
191
+ if (value == null) return null;
192
+ if (typeof value !== "object" || Array.isArray(value)
193
+ || Object.keys(value).some((key) => !["providerID", "modelID"].includes(key))
194
+ || ![value.providerID, value.modelID].every((id) => typeof id === "string" && id.trim() === id && id.length > 0 && id.length <= 500 && !/[\u0000-\u001f\u007f]/u.test(id))) {
195
+ throw new Error("Invalid model: expected providerID and modelID.");
196
+ }
197
+ return { providerID: value.providerID, modelID: value.modelID };
198
+ }
199
+
200
+ export function createModelSetting(file = pipaPaths().config, writeJson = writePrivateJson) {
201
+ let tail = Promise.resolve();
202
+ return {
203
+ async save(model, authorize = () => undefined) {
204
+ const selected = normalizeModel(model);
205
+ if (!selected) return Promise.reject(new Error("A model selection is required."));
206
+ const write = tail.then(async () => {
207
+ const current = await loadConfig(file);
208
+ await authorize(current);
209
+ await writeJson(file, { ...current, defaultModel: selected });
210
+ return selected;
211
+ });
212
+ tail = write.catch(() => undefined);
213
+ return write;
214
+ },
215
+ };
216
+ }
217
+
175
218
  export async function saveConfig(config, paths = pipaPaths(), manifest = createManifest(config.botName)) {
176
219
  await writePrivateJson(paths.manifest, manifest);
177
220
  await writePrivateJson(paths.config, config);