@usepipa/pipa 0.5.3 → 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 +90 -4
- package/bin/pipa.mjs +14 -3
- package/package.json +1 -1
- package/src/app.mjs +76 -9
- package/src/models.mjs +156 -0
- package/src/opencode.mjs +49 -3
- package/src/routines.mjs +4 -2
- package/src/state.mjs +44 -1
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
|
|
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
|
|
|
@@ -55,7 +55,7 @@ Incoming messages can include up to Slack's 10-file limit, with a maximum size o
|
|
|
55
55
|
|
|
56
56
|
### Access control
|
|
57
57
|
|
|
58
|
-
By default Pipa answers
|
|
58
|
+
By default Pipa answers any human user who mentions it in a channel it can see, excluding DMs and external channels. In a shared workspace, restrict who can use it by listing the allowed Slack channel and user IDs. `pipa init` asks for these, and they are stored in the config:
|
|
59
59
|
|
|
60
60
|
```json
|
|
61
61
|
{
|
|
@@ -64,11 +64,44 @@ By default Pipa answers anyone who mentions it in a channel it can see. In a sha
|
|
|
64
64
|
"slackAppToken": "xapp-...",
|
|
65
65
|
"slackBotToken": "xoxb-...",
|
|
66
66
|
"allowedSlackChannelIds": ["C0BSE2JTYPR"],
|
|
67
|
-
"allowedSlackUserIds": ["UFWBSCZ54"]
|
|
67
|
+
"allowedSlackUserIds": ["UFWBSCZ54"],
|
|
68
|
+
"allowedSlackBotIds": ["B0C6Q27E82X"]
|
|
68
69
|
}
|
|
69
70
|
```
|
|
70
71
|
|
|
71
|
-
A mention is only handled when the channel
|
|
72
|
+
A human user's mention is only handled when the channel and user pass their respective allowlists. An absent or empty `allowedSlackChannelIds` allows any otherwise eligible channel; an absent or empty `allowedSlackUserIds` allows any human user. You can also set them non-interactively during setup with `PIPA_ALLOWED_CHANNEL_IDS` and `PIPA_ALLOWED_USER_IDS` (comma-separated).
|
|
73
|
+
|
|
74
|
+
By default Pipa ignores messages sent by other Slack apps. Unlike the human user and channel lists, an absent or empty `allowedSlackBotIds` disables all other bots. List their bot IDs to let those messages through; an allowed bot only needs its bot ID (e.g. `B0C6Q27E82X`), not an entry in `allowedSlackUserIds`. Bots still must pass the channel allowlist. Bots not on the list stay ignored even when `allowedSlackUserIds` is empty. Set it non-interactively during setup with `PIPA_ALLOWED_BOT_IDS` (comma-separated).
|
|
75
|
+
|
|
76
|
+
#### Find the sender's bot ID
|
|
77
|
+
|
|
78
|
+
Use the message event's `bot_id` (`B…`), not the app ID (`A…`) or bot user ID (`U…`). To look up the sender app's OAuth bot ID:
|
|
79
|
+
|
|
80
|
+
1. Open the **sender app** at [Slack Apps](https://api.slack.com/apps), not Pipa's app.
|
|
81
|
+
2. Under **OAuth & Permissions**, copy its **Bot User OAuth Token** (`xoxb-…`). If needed, install the app in the workspace via **Install App** first.
|
|
82
|
+
3. Set that token locally in `SLACK_SENDER_BOT_TOKEN`, then call [Slack `auth.test`](https://docs.slack.dev/reference/methods/auth.test/):
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
curl --silent --show-error --request POST \
|
|
86
|
+
--header "Authorization: Bearer ${SLACK_SENDER_BOT_TOKEN}" \
|
|
87
|
+
https://slack.com/api/auth.test
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
No Slack CLI is needed. Keep the token out of config examples, shared output, and commits. A successful response includes fields like:
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
{
|
|
94
|
+
"ok": true,
|
|
95
|
+
"user_id": "U0123456789",
|
|
96
|
+
"bot_id": "B0123456789"
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Use `bot_id` (`B0123456789`) in `allowedSlackBotIds`; `user_id` identifies the bot's user account and is not the bot allowlist ID.
|
|
101
|
+
|
|
102
|
+
**Incoming webhooks:** the posted message's `bot_id` can differ from the sender app's OAuth `bot_id` returned by `auth.test`. Allow the actual incoming message/event's `bot_id`. If you do not have the event payload, find the posted message with [Slack `conversations.history`](https://docs.slack.dev/reference/methods/conversations.history/) (or [`conversations.replies`](https://docs.slack.dev/reference/methods/conversations.replies/) for a thread reply), using a token with access to that conversation and the required history scope, and read its `bot_id`.
|
|
103
|
+
|
|
104
|
+
After saving the config, restart Pipa to load the updated allowlist. The allowed bot can start a conversation by posting `<@PIPA_BOT_USER_ID> triage this alert` in an allowed channel, or continue one by replying in a thread Pipa has subscribed to. For an incoming webhook, send that mention in the payload's `text` field. Allowlisting a bot does not make Pipa handle every message it posts in the channel; the normal mention/thread routing still applies. Only allow bots whose messages you trust as requests to your agent.
|
|
72
105
|
|
|
73
106
|
To use an existing OpenCode server instead, set its URL before starting Pipa. Pipa checks that the server can serve the configured workspace but does not start or stop it. If the server uses authentication, also set `OPENCODE_SERVER_USERNAME` and `OPENCODE_SERVER_PASSWORD`:
|
|
74
107
|
|
|
@@ -77,6 +110,58 @@ export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
|
|
|
77
110
|
pipa start
|
|
78
111
|
```
|
|
79
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
|
+
|
|
80
165
|
### Routines
|
|
81
166
|
|
|
82
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.
|
|
@@ -144,6 +229,7 @@ pipa stop Stop the running local Pipa process
|
|
|
144
229
|
pipa restart [--channel <id> [--thread <ts>]] Request a detached restart
|
|
145
230
|
pipa restart --status Inspect the latest durable restart outcome
|
|
146
231
|
pipa routine Create and manage local scheduled routines
|
|
232
|
+
pipa manifest Print the current local Slack manifest template for an existing profile
|
|
147
233
|
pipa --version Print the installed version
|
|
148
234
|
```
|
|
149
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
|
-
|
|
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
|
|
@@ -348,8 +357,10 @@ async function init(io) {
|
|
|
348
357
|
?? (await prompt.question("Allowed Slack channel IDs (comma-separated, e.g. C0BSE2JTYPR; leave empty to allow any channel): ")).trim();
|
|
349
358
|
const allowedSlackUserIds = process.env.PIPA_ALLOWED_USER_IDS
|
|
350
359
|
?? (await prompt.question("Allowed Slack user IDs (comma-separated, e.g. UFWBSCZ54; leave empty to allow any user): ")).trim();
|
|
360
|
+
const allowedSlackBotIds = process.env.PIPA_ALLOWED_BOT_IDS
|
|
361
|
+
?? (await prompt.question("Allowed Slack bot IDs (comma-separated, e.g. B0C6Q27E82X; leave empty to ignore bot messages): ")).trim();
|
|
351
362
|
io.output.write("\nChecking OpenCode and Slack credentials...\n");
|
|
352
|
-
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds });
|
|
363
|
+
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds, allowedSlackBotIds });
|
|
353
364
|
io.output.write(`✓ Credentials validated.\n\nSaved config to ${result.paths.config}. Run \`pipa start\`.\n`);
|
|
354
365
|
} finally {
|
|
355
366
|
prompt.close();
|
package/package.json
CHANGED
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
|
|
|
@@ -19,6 +20,7 @@ export async function initializePipa(input, options = {}) {
|
|
|
19
20
|
workingDirectory: await canonicalWorkingDirectory(input.workingDirectory),
|
|
20
21
|
allowedSlackChannelIds: normalizeIdList(input.allowedSlackChannelIds),
|
|
21
22
|
allowedSlackUserIds: normalizeIdList(input.allowedSlackUserIds),
|
|
23
|
+
allowedSlackBotIds: normalizeIdList(input.allowedSlackBotIds),
|
|
22
24
|
};
|
|
23
25
|
const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
|
|
24
26
|
if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
|
|
@@ -34,6 +36,8 @@ export async function startPipa(options = {}) {
|
|
|
34
36
|
options.signal?.throwIfAborted();
|
|
35
37
|
const paths = options.paths ?? pipaPaths();
|
|
36
38
|
const config = options.config ?? await loadConfig(paths.config);
|
|
39
|
+
const commands = slackCommandNames(config.botName);
|
|
40
|
+
const loadCurrentConfig = options.loadCurrentConfig ?? (() => loadConfig(paths.config));
|
|
37
41
|
options.signal?.throwIfAborted();
|
|
38
42
|
const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
39
43
|
options.signal?.throwIfAborted();
|
|
@@ -43,7 +47,7 @@ export async function startPipa(options = {}) {
|
|
|
43
47
|
const state = options.state ?? createMemoryState();
|
|
44
48
|
const chat = options.chat ?? new Chat({
|
|
45
49
|
adapters: {
|
|
46
|
-
slack:
|
|
50
|
+
slack: createPipaSlackAdapter({
|
|
47
51
|
appToken: config.slackAppToken,
|
|
48
52
|
botToken: config.slackBotToken,
|
|
49
53
|
mode: "socket",
|
|
@@ -72,7 +76,10 @@ export async function startPipa(options = {}) {
|
|
|
72
76
|
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
73
77
|
throw error;
|
|
74
78
|
}
|
|
75
|
-
const runner = createConversationRunner({ sessionStore,
|
|
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
|
+
} });
|
|
76
83
|
let accepting = true;
|
|
77
84
|
const interactions = createPendingInteractions(config.allowedSlackUserIds);
|
|
78
85
|
const pendingReactions = new Map();
|
|
@@ -118,6 +125,7 @@ export async function startPipa(options = {}) {
|
|
|
118
125
|
try {
|
|
119
126
|
result = await executor.runTurn({
|
|
120
127
|
prompt: snapshot.prompt,
|
|
128
|
+
...(snapshot.model ? { model: snapshot.model } : {}),
|
|
121
129
|
sessionId: null,
|
|
122
130
|
workingDirectory: config.workingDirectory,
|
|
123
131
|
contextEnvironment: {
|
|
@@ -159,6 +167,8 @@ export async function startPipa(options = {}) {
|
|
|
159
167
|
return { status: "succeeded" };
|
|
160
168
|
},
|
|
161
169
|
}) : null;
|
|
170
|
+
const modelPicker = createModelPicker({ chat, botName: config.botName, commands, loadConfig: loadCurrentConfig,
|
|
171
|
+
listModels: () => executor.listModels(config.workingDirectory), setting: createModelSetting(paths.config) });
|
|
162
172
|
chat.onAction?.(interactions.onAction);
|
|
163
173
|
chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
|
|
164
174
|
|
|
@@ -170,7 +180,7 @@ export async function startPipa(options = {}) {
|
|
|
170
180
|
};
|
|
171
181
|
|
|
172
182
|
const handle = async (thread, message, subscribe) => {
|
|
173
|
-
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
|
|
183
|
+
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message, config)) return;
|
|
174
184
|
const messageText = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
175
185
|
const missingLinks = (message.links ?? []).map((link) => link.url)
|
|
176
186
|
.filter((url) => typeof url === "string" && !messageText.split(/\s+/u).includes(url));
|
|
@@ -220,6 +230,7 @@ export async function startPipa(options = {}) {
|
|
|
220
230
|
const stop = (reason = new PipaStoppedError()) => {
|
|
221
231
|
if (!accepting) return;
|
|
222
232
|
accepting = false;
|
|
233
|
+
modelPicker.close();
|
|
223
234
|
routineScheduler?.stop(reason);
|
|
224
235
|
runner.close(reason);
|
|
225
236
|
executor.stopAll(reason);
|
|
@@ -240,6 +251,7 @@ export async function startPipa(options = {}) {
|
|
|
240
251
|
options.signal?.throwIfAborted();
|
|
241
252
|
} catch (error) {
|
|
242
253
|
options.signal?.removeEventListener("abort", cancelled);
|
|
254
|
+
modelPicker.close();
|
|
243
255
|
routineScheduler?.stop(error);
|
|
244
256
|
await routineScheduler?.drain();
|
|
245
257
|
await withTimeout(interactions.close(), options.shutdownTimeoutMs ?? 15_000, "Interaction shutdown timed out.").catch(() => undefined);
|
|
@@ -271,6 +283,7 @@ export async function startPipa(options = {}) {
|
|
|
271
283
|
try {
|
|
272
284
|
await withTimeout((async () => {
|
|
273
285
|
await interactions.close();
|
|
286
|
+
await modelPicker.drain();
|
|
274
287
|
await routineScheduler?.drain();
|
|
275
288
|
await runner.drain();
|
|
276
289
|
await chat.shutdown();
|
|
@@ -284,6 +297,58 @@ export async function startPipa(options = {}) {
|
|
|
284
297
|
};
|
|
285
298
|
}
|
|
286
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
|
+
|
|
287
352
|
export function createPendingInteractions(allowedUserIds = []) {
|
|
288
353
|
const pending = new Map();
|
|
289
354
|
const permissionRequests = new Map();
|
|
@@ -714,12 +779,13 @@ export async function checkSlackAppToken(token, fetchImpl = fetch) {
|
|
|
714
779
|
return result;
|
|
715
780
|
}
|
|
716
781
|
|
|
717
|
-
function shouldIgnore(thread, message) {
|
|
782
|
+
function shouldIgnore(thread, message, config) {
|
|
783
|
+
const allowedSubtypes = config.allowedSlackBotIds?.length ? ["file_share", "bot_message"] : ["file_share"];
|
|
718
784
|
return message.author?.isMe
|
|
719
|
-
|| message.author?.isBot
|
|
785
|
+
|| (message.author?.isBot && !config.allowedSlackBotIds?.length)
|
|
786
|
+
|| Boolean(message.raw?.subtype && !allowedSubtypes.includes(message.raw.subtype))
|
|
720
787
|
|| thread.channel?.isDM
|
|
721
788
|
|| thread.channel?.channelVisibility === "external"
|
|
722
|
-
|| Boolean(message.raw?.subtype && message.raw.subtype !== "file_share")
|
|
723
789
|
|| !message.text?.trim();
|
|
724
790
|
}
|
|
725
791
|
|
|
@@ -727,6 +793,7 @@ function isAuthorized(thread, message, config) {
|
|
|
727
793
|
const channelId = thread.id.split(":")[1];
|
|
728
794
|
const userId = message.author?.userId ?? message.author?.id;
|
|
729
795
|
if (config.allowedSlackChannelIds?.length && !config.allowedSlackChannelIds.includes(channelId)) return false;
|
|
796
|
+
if (message.author?.isBot) return config.allowedSlackBotIds?.includes(message.raw?.bot_id) ?? false;
|
|
730
797
|
if (config.allowedSlackUserIds?.length && !config.allowedSlackUserIds.includes(userId)) return false;
|
|
731
798
|
return true;
|
|
732
799
|
}
|
|
@@ -756,10 +823,10 @@ function normalizeGrantedScopes(value) {
|
|
|
756
823
|
function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`${message}\n`)) {
|
|
757
824
|
if (!Array.isArray(auth?.grantedScopes)) return;
|
|
758
825
|
const missing = ["channels:read", "assistant:write"].filter((scope) => !auth.grantedScopes.includes(scope));
|
|
759
|
-
if (!missing.length) return;
|
|
760
826
|
const scopes = missing.join(", ");
|
|
761
827
|
try {
|
|
762
|
-
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`.");
|
|
763
830
|
} catch {}
|
|
764
831
|
}
|
|
765
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 (
|
|
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
|
}
|
|
@@ -163,15 +177,44 @@ export async function loadConfig(file = pipaPaths().config) {
|
|
|
163
177
|
if (slackMode === "managed" && (!Number.isInteger(config.openCodePort) || config.openCodePort < 1 || config.openCodePort > 65535)) {
|
|
164
178
|
throw new Error("Invalid Pipa config: openCodePort must be an integer from 1 to 65535.");
|
|
165
179
|
}
|
|
166
|
-
for (const key of ["allowedSlackChannelIds", "allowedSlackUserIds"]) {
|
|
180
|
+
for (const key of ["allowedSlackChannelIds", "allowedSlackUserIds", "allowedSlackBotIds"]) {
|
|
167
181
|
const value = config[key];
|
|
168
182
|
if (value !== undefined && (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim()))) {
|
|
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);
|