@usepipa/pipa 0.5.4 → 0.5.6
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 +123 -10
- package/bin/pipa.mjs +15 -3
- package/package.json +1 -1
- package/src/app.mjs +71 -5
- package/src/models.mjs +156 -0
- package/src/opencode.mjs +49 -3
- package/src/routines.mjs +4 -2
- package/src/state.mjs +46 -0
package/README.md
CHANGED
|
@@ -1,17 +1,65 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://www.usepipa.com/opencode-slack?utm_source=github&utm_medium=repo_readme&utm_campaign=signup&utm_content=readme_banner">
|
|
3
|
+
<img src="docs/assets/banner.png" alt="Pipa: run OpenCode from Slack" width="100%">
|
|
4
|
+
</a>
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://github.com/lunchpaillola/pipa/actions/workflows/ci.yml"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/lunchpaillola/pipa/ci.yml?branch=main&style=flat-square&label=CI"></a>
|
|
9
|
+
<a href="https://www.npmjs.com/package/@usepipa/pipa"><img alt="npm" src="https://img.shields.io/npm/v/@usepipa/pipa?style=flat-square&color=2437F5&label=npm"></a>
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<strong>Pipa turns a Slack thread into a durable OpenCode session on one private server, local by default.</strong><br>
|
|
14
|
+
No relay, no database, no public endpoint.
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
<p align="center">
|
|
18
|
+
<a href="https://www.youtube.com/watch?v=rlTMdkPWPcA"><strong>Watch the 3-minute setup</strong></a>
|
|
19
|
+
·
|
|
20
|
+
<a href="https://www.usepipa.com/opencode-slack?utm_source=github&utm_medium=repo_readme&utm_campaign=signup&utm_content=readme_how_it_works">How it works</a>
|
|
21
|
+
·
|
|
22
|
+
<a href="CONTRIBUTING.md">Contributing</a>
|
|
23
|
+
·
|
|
24
|
+
<a href="https://github.com/lunchpaillola/pipa/issues">Issues</a>
|
|
25
|
+
</p>
|
|
26
|
+
|
|
27
|
+
> **Early preview.** Features may break unintentionally, and CLI commands, configuration, and Slack behavior may continue to change.
|
|
28
|
+
|
|
29
|
+
## Why Pipa
|
|
30
|
+
|
|
31
|
+
| What it does | What that means |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| **One server** | In local mode, Pipa starts one private OpenCode server on `127.0.0.1` and reuses it for every Slack turn. Attached servers follow their own network controls. |
|
|
34
|
+
| **Thread sessions** | A mention starts a session; replies in that thread continue it. Different threads run independently, and a newer message interrupts only its own thread. |
|
|
35
|
+
| **Routines** | Schedule timezone-aware work that runs through the same agent and delivers to an exact channel or thread. |
|
|
36
|
+
| **Generated files** | In local mode, long work returns as a concise summary with generated files from a private per-turn directory. Attached non-loopback servers return inline text. |
|
|
37
|
+
| **Access control** | Restrict by Slack channel, human user, and bot. Allowlists are rechecked on every turn, interaction, and delivery. |
|
|
38
|
+
| **Restart** | `pipa restart` hands off to a detached worker and reports a durable status. |
|
|
39
|
+
|
|
40
|
+
If Pipa is useful, [star the repo](https://github.com/lunchpaillola/pipa).
|
|
41
|
+
|
|
42
|
+
## Quickstart
|
|
43
|
+
|
|
44
|
+
**Runs on** macOS, Linux, and Windows. **Requires** Node.js 22 or newer, [OpenCode](https://opencode.ai) installed and authenticated, and a Slack workspace where you can create an app.
|
|
2
45
|
|
|
3
|
-
|
|
4
|
-
|
|
46
|
+
```sh
|
|
47
|
+
npm install --global @usepipa/pipa
|
|
48
|
+
pipa init
|
|
49
|
+
pipa start
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`pipa init` creates the Slack app manifest, opens the install flow, and saves the profile under `~/.pipa`. Invite Pipa to a channel and mention it. The [3-minute setup video](https://www.youtube.com/watch?v=rlTMdkPWPcA) shows the flow, and the [OpenCode Slack integration guide](https://www.usepipa.com/opencode-slack?utm_source=github&utm_medium=repo_readme&utm_campaign=signup&utm_content=readme_install_guide) is the current written path.
|
|
5
53
|
|
|
6
|
-
|
|
54
|
+
## Security model
|
|
7
55
|
|
|
8
|
-
|
|
56
|
+
In local mode, Pipa runs on your machine, not behind a relay. The local OpenCode server binds to `127.0.0.1` on an operating-system-assigned port; attached servers follow their own network controls. Slack access is limited by channel, user, and bot allowlists, rechecked on every turn. Tokens stay in the local profile with private file permissions, and OpenCode manages provider credentials.
|
|
9
57
|
|
|
10
|
-
|
|
58
|
+
Read [SECURITY.md](SECURITY.md) for the full model and reporting path.
|
|
11
59
|
|
|
12
60
|
## Pipa Managed
|
|
13
61
|
|
|
14
|
-
Want
|
|
62
|
+
Want Lunch Pail Labs to configure, run, and manage agent workflows for your company? Check out [Pipa Managed](https://usepipa.com/managed?utm_source=github&utm_medium=repo_readme&utm_campaign=signup&utm_content=readme_footer). We set up a Slack-native operations agent for your team, then keep the workflows running.
|
|
15
63
|
|
|
16
64
|
## Local Socket Mode
|
|
17
65
|
|
|
@@ -39,7 +87,7 @@ npm install --global @usepipa/pipa
|
|
|
39
87
|
pipa init
|
|
40
88
|
```
|
|
41
89
|
|
|
42
|
-
`pipa init` guides you through creating and installing the Slack app and saving its local configuration. The generated manifest includes `channels:read
|
|
90
|
+
`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
91
|
|
|
44
92
|
3. Start Pipa:
|
|
45
93
|
|
|
@@ -47,9 +95,9 @@ pipa init
|
|
|
47
95
|
pipa start
|
|
48
96
|
```
|
|
49
97
|
|
|
50
|
-
Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. Pipa starts one OpenCode server bound to `127.0.0.1` on an operating-system-assigned port and reuses it for every Slack turn. Port `0` asks the operating system for an available port; no port configuration is required. Pipa replies in a thread, and follow-up messages in that thread reuse the same OpenCode session without another mention. A newer follow-up interrupts an active turn in the same thread, while other threads continue independently. While a turn is active, Pipa shows a typing status in its Slack thread.
|
|
98
|
+
Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. In owned local mode, Pipa starts one OpenCode server bound to `127.0.0.1` on an operating-system-assigned port and reuses it for every Slack turn. Port `0` asks the operating system for an available port; no port configuration is required. Pipa replies in a thread, and follow-up messages in that thread reuse the same OpenCode session without another mention. A newer follow-up interrupts an active turn in the same thread, while other threads continue independently. While a turn is active, Pipa shows a typing status in its Slack thread.
|
|
51
99
|
|
|
52
|
-
Pipa keeps naturally short answers inline. For deeper work, OpenCode can return a concise summary with suitable generated files, such as documents, spreadsheets, PDFs, or images. Files are read only from a private session directory under `.pipa/artifacts` in the configured working directory. The directory is cleared before each turn, files are validated and limited to 10 files and 100 MB
|
|
100
|
+
Pipa keeps naturally short answers inline. For deeper work, OpenCode can return a concise summary with suitable generated files, such as documents, spreadsheets, PDFs, or images. Files are read only from a private session directory under `.pipa/artifacts` in the configured working directory. The directory is cleared before each turn, files are validated and limited to 10 files and 100 MB total, and the directory is deleted locally after delivery. If file delivery fails, Pipa retries the declaration-free summary without the files. Attached OpenCode servers on non-loopback hosts use inline text fallback instead of local artifact delivery.
|
|
53
101
|
|
|
54
102
|
Incoming messages can include up to Slack's 10-file limit, with a maximum size of 100 MB per file. Attachments require a text prompt and are copied to a temporary directory only for the duration of the turn.
|
|
55
103
|
|
|
@@ -73,6 +121,18 @@ A human user's mention is only handled when the channel and user pass their resp
|
|
|
73
121
|
|
|
74
122
|
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
123
|
|
|
124
|
+
#### Mention-only mode
|
|
125
|
+
|
|
126
|
+
By default, once Pipa is mentioned in a thread it subscribes to that thread and answers every later message in it without another mention. Set `mentionOnly` to `true` to require a direct @-mention for every turn, including in threads Pipa is already in:
|
|
127
|
+
|
|
128
|
+
```json
|
|
129
|
+
{
|
|
130
|
+
"mentionOnly": true
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`pipa init` asks for this, and you can set it non-interactively with `PIPA_MENTION_ONLY` (`1`, `true`, or `yes`). An absent or `false` value keeps the default thread-following behavior. Routines are unaffected.
|
|
135
|
+
|
|
76
136
|
#### Find the sender's bot ID
|
|
77
137
|
|
|
78
138
|
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:
|
|
@@ -110,6 +170,58 @@ export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
|
|
|
110
170
|
pipa start
|
|
111
171
|
```
|
|
112
172
|
|
|
173
|
+
### Choosing a model
|
|
174
|
+
|
|
175
|
+
Type your installation's command followed by `model` in an allowed Slack channel: `/chopper model` for `Chopper`, `/pipwick model` for `Pipwick`, or the `/pipa model` compatibility alias when registered to that app. Both forms use the same private native modal, authorization checks, and setting. A loading window opens before catalog discovery, then fills with models grouped by provider. Browse or type to filter, choose a model, and Save. Save closes the window promptly; a private channel message confirms success only after fresh validation and persistence, or explains a failure. Wait for that confirmation before testing the new selection. Cancel leaves the setting unchanged. Existing channel and human-user allowlists are rechecked after discovery, on Save, during persistence, and before delivering the private result.
|
|
176
|
+
|
|
177
|
+
The command is computed from your configured `botName`, not a hardcoded list of bot names. Pipa decomposes accented Latin characters, removes combining marks, lowercases the name, replaces runs of spaces/punctuation/other non-ASCII characters with `-`, trims edge hyphens, and limits the part after `/` to 31 characters (trimming any resulting trailing hyphen). For example, `Workshop "Bot"` becomes `/workshop-bot` and `Café 🧪` becomes `/cafe`. A valid display name with no usable ASCII slug, such as `🤖` or `東京`, falls back to `/pipa` so this optional feature cannot prevent an old profile from starting. Existing display-name validation still applies. Generated commands use a conservative lowercase-letter/digit/hyphen subset within Slack's 32-character limit including `/`.
|
|
178
|
+
|
|
179
|
+
**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.
|
|
180
|
+
|
|
181
|
+
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.
|
|
182
|
+
|
|
183
|
+
New routines snapshot the selection when created; preview JSON shows that snapshot. Existing routines and their saved model are unchanged by later saves or routine edits. A routine with no saved model uses OpenCode's default, never the current installation setting. Human replies to routine results retain the model recorded in that conversation. If a thread's provider stops working, reconnect it or choose a different default and start a new thread.
|
|
184
|
+
|
|
185
|
+
The picker preloads the configured OpenCode model catalog into a native Slack dropdown, grouped by provider. Open the dropdown to browse immediately, or type to filter models; no search callback is needed. Groups contain up to 100 models each, with at most 100 groups. Empty catalogs or catalogs exceeding Slack's limits get a private explanation instead of an empty or truncated list. A listed model may still lack credentials or quota; saving never runs inference to check it. The provider shown beneath each result identifies the connection: `opencode` and `openai` use separate credentials, even for similarly named models. Turn failures identify the provider and HTTP status when available; authentication failures give reconnection guidance, and an explicitly expired API key is reported as expired. Raw upstream errors and credentials are not posted, and Pipa never silently switches models. Abandoned pickers expire after 30 minutes; reopen your installation's model command to continue.
|
|
186
|
+
|
|
187
|
+
If the model window cannot open, its private error distinguishes saved-settings problems, model-catalog loading, configured access restrictions, and Slack window failures. It confirms that the saved model is unchanged; it does not expose raw upstream errors or credentials.
|
|
188
|
+
|
|
189
|
+
### Upgrading an existing installation
|
|
190
|
+
|
|
191
|
+
**An npm upgrade updates local code only. It does not update the installed Slack app, register commands, or grant scopes.** Existing mentions and thread replies still work without model-command registration. Do not rerun `pipa init` or replace credentials to add this feature.
|
|
192
|
+
|
|
193
|
+
After `0.5.5` is published, use the same `PIPA_HOME` as your existing installation (leave it unset for the default `~/.pipa` profile):
|
|
194
|
+
|
|
195
|
+
```sh
|
|
196
|
+
npm install --global @usepipa/pipa@0.5.5
|
|
197
|
+
pipa --version
|
|
198
|
+
pipa manifest > "$HOME/pipa-slack-manifest-0.5.5.json"
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`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.
|
|
202
|
+
|
|
203
|
+
1. Open your **existing app** in [Slack App Management](https://api.slack.com/apps). Keep a copy of its current remote manifest.
|
|
204
|
+
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**.
|
|
205
|
+
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.
|
|
206
|
+
4. Restart the same profile to load the upgraded runtime:
|
|
207
|
+
|
|
208
|
+
```sh
|
|
209
|
+
pipa restart
|
|
210
|
+
pipa restart --status
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
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.
|
|
214
|
+
|
|
215
|
+
Before npm publication, preview the feature branch from this repo without reinstalling or reinitializing your profile:
|
|
216
|
+
|
|
217
|
+
```sh
|
|
218
|
+
npm ci
|
|
219
|
+
node bin/pipa.mjs --version
|
|
220
|
+
node bin/pipa.mjs manifest > "$HOME/pipa-slack-manifest-preview.json"
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
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.
|
|
224
|
+
|
|
113
225
|
### Routines
|
|
114
226
|
|
|
115
227
|
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 +289,7 @@ pipa stop Stop the running local Pipa process
|
|
|
177
289
|
pipa restart [--channel <id> [--thread <ts>]] Request a detached restart
|
|
178
290
|
pipa restart --status Inspect the latest durable restart outcome
|
|
179
291
|
pipa routine Create and manage local scheduled routines
|
|
292
|
+
pipa manifest Print the current local Slack manifest template for an existing profile
|
|
180
293
|
pipa --version Print the installed version
|
|
181
294
|
```
|
|
182
295
|
|
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
|
|
@@ -350,8 +359,11 @@ async function init(io) {
|
|
|
350
359
|
?? (await prompt.question("Allowed Slack user IDs (comma-separated, e.g. UFWBSCZ54; leave empty to allow any user): ")).trim();
|
|
351
360
|
const allowedSlackBotIds = process.env.PIPA_ALLOWED_BOT_IDS
|
|
352
361
|
?? (await prompt.question("Allowed Slack bot IDs (comma-separated, e.g. B0C6Q27E82X; leave empty to ignore bot messages): ")).trim();
|
|
362
|
+
const mentionOnly = process.env.PIPA_MENTION_ONLY !== undefined
|
|
363
|
+
? /^(1|true|yes)$/iu.test(process.env.PIPA_MENTION_ONLY.trim())
|
|
364
|
+
: /^y(es)?$/iu.test((await prompt.question("Only respond when @-mentioned, even in threads Pipa is already in? [y/N]: ")).trim());
|
|
353
365
|
io.output.write("\nChecking OpenCode and Slack credentials...\n");
|
|
354
|
-
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds, allowedSlackBotIds });
|
|
366
|
+
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds, allowedSlackBotIds, mentionOnly });
|
|
355
367
|
io.output.write(`✓ Credentials validated.\n\nSaved config to ${result.paths.config}. Run \`pipa start\`.\n`);
|
|
356
368
|
} finally {
|
|
357
369
|
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
|
|
|
@@ -20,6 +21,7 @@ export async function initializePipa(input, options = {}) {
|
|
|
20
21
|
allowedSlackChannelIds: normalizeIdList(input.allowedSlackChannelIds),
|
|
21
22
|
allowedSlackUserIds: normalizeIdList(input.allowedSlackUserIds),
|
|
22
23
|
allowedSlackBotIds: normalizeIdList(input.allowedSlackBotIds),
|
|
24
|
+
mentionOnly: input.mentionOnly === true,
|
|
23
25
|
};
|
|
24
26
|
const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
|
|
25
27
|
if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
|
|
@@ -35,6 +37,8 @@ export async function startPipa(options = {}) {
|
|
|
35
37
|
options.signal?.throwIfAborted();
|
|
36
38
|
const paths = options.paths ?? pipaPaths();
|
|
37
39
|
const config = options.config ?? await loadConfig(paths.config);
|
|
40
|
+
const commands = slackCommandNames(config.botName);
|
|
41
|
+
const loadCurrentConfig = options.loadCurrentConfig ?? (() => loadConfig(paths.config));
|
|
38
42
|
options.signal?.throwIfAborted();
|
|
39
43
|
const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
40
44
|
options.signal?.throwIfAborted();
|
|
@@ -44,7 +48,7 @@ export async function startPipa(options = {}) {
|
|
|
44
48
|
const state = options.state ?? createMemoryState();
|
|
45
49
|
const chat = options.chat ?? new Chat({
|
|
46
50
|
adapters: {
|
|
47
|
-
slack:
|
|
51
|
+
slack: createPipaSlackAdapter({
|
|
48
52
|
appToken: config.slackAppToken,
|
|
49
53
|
botToken: config.slackBotToken,
|
|
50
54
|
mode: "socket",
|
|
@@ -73,7 +77,10 @@ export async function startPipa(options = {}) {
|
|
|
73
77
|
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
74
78
|
throw error;
|
|
75
79
|
}
|
|
76
|
-
const runner = createConversationRunner({ sessionStore,
|
|
80
|
+
const runner = createConversationRunner({ sessionStore, abortTurn: executor.abortTurn, runTurn: async (input) => {
|
|
81
|
+
const currentConfig = await loadCurrentConfig();
|
|
82
|
+
return executor.runTurn({ ...input, ...(currentConfig.defaultModel ? { defaultModel: currentConfig.defaultModel } : {}) });
|
|
83
|
+
} });
|
|
77
84
|
let accepting = true;
|
|
78
85
|
const interactions = createPendingInteractions(config.allowedSlackUserIds);
|
|
79
86
|
const pendingReactions = new Map();
|
|
@@ -119,6 +126,7 @@ export async function startPipa(options = {}) {
|
|
|
119
126
|
try {
|
|
120
127
|
result = await executor.runTurn({
|
|
121
128
|
prompt: snapshot.prompt,
|
|
129
|
+
...(snapshot.model ? { model: snapshot.model } : {}),
|
|
122
130
|
sessionId: null,
|
|
123
131
|
workingDirectory: config.workingDirectory,
|
|
124
132
|
contextEnvironment: {
|
|
@@ -160,6 +168,8 @@ export async function startPipa(options = {}) {
|
|
|
160
168
|
return { status: "succeeded" };
|
|
161
169
|
},
|
|
162
170
|
}) : null;
|
|
171
|
+
const modelPicker = createModelPicker({ chat, botName: config.botName, commands, loadConfig: loadCurrentConfig,
|
|
172
|
+
listModels: () => executor.listModels(config.workingDirectory), setting: createModelSetting(paths.config) });
|
|
163
173
|
chat.onAction?.(interactions.onAction);
|
|
164
174
|
chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
|
|
165
175
|
|
|
@@ -172,6 +182,7 @@ export async function startPipa(options = {}) {
|
|
|
172
182
|
|
|
173
183
|
const handle = async (thread, message, subscribe) => {
|
|
174
184
|
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message, config)) return;
|
|
185
|
+
if (config.mentionOnly && !subscribe && !message.isMention) return;
|
|
175
186
|
const messageText = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
176
187
|
const missingLinks = (message.links ?? []).map((link) => link.url)
|
|
177
188
|
.filter((url) => typeof url === "string" && !messageText.split(/\s+/u).includes(url));
|
|
@@ -221,6 +232,7 @@ export async function startPipa(options = {}) {
|
|
|
221
232
|
const stop = (reason = new PipaStoppedError()) => {
|
|
222
233
|
if (!accepting) return;
|
|
223
234
|
accepting = false;
|
|
235
|
+
modelPicker.close();
|
|
224
236
|
routineScheduler?.stop(reason);
|
|
225
237
|
runner.close(reason);
|
|
226
238
|
executor.stopAll(reason);
|
|
@@ -241,6 +253,7 @@ export async function startPipa(options = {}) {
|
|
|
241
253
|
options.signal?.throwIfAborted();
|
|
242
254
|
} catch (error) {
|
|
243
255
|
options.signal?.removeEventListener("abort", cancelled);
|
|
256
|
+
modelPicker.close();
|
|
244
257
|
routineScheduler?.stop(error);
|
|
245
258
|
await routineScheduler?.drain();
|
|
246
259
|
await withTimeout(interactions.close(), options.shutdownTimeoutMs ?? 15_000, "Interaction shutdown timed out.").catch(() => undefined);
|
|
@@ -272,6 +285,7 @@ export async function startPipa(options = {}) {
|
|
|
272
285
|
try {
|
|
273
286
|
await withTimeout((async () => {
|
|
274
287
|
await interactions.close();
|
|
288
|
+
await modelPicker.drain();
|
|
275
289
|
await routineScheduler?.drain();
|
|
276
290
|
await runner.drain();
|
|
277
291
|
await chat.shutdown();
|
|
@@ -285,6 +299,58 @@ export async function startPipa(options = {}) {
|
|
|
285
299
|
};
|
|
286
300
|
}
|
|
287
301
|
|
|
302
|
+
export function createPipaSlackAdapter(options, drainTimeoutMs = 3_000) {
|
|
303
|
+
const adapter = createSlackAdapter(options);
|
|
304
|
+
const slashCommand = adapter.handleSlashCommand.bind(adapter);
|
|
305
|
+
const commands = slackCommandNames(options.userName ?? "Pipa");
|
|
306
|
+
adapter.handleSlashCommand = async (params, context) => {
|
|
307
|
+
if (!adapter.chat || !commands.includes(params.get("command")) || params.get("text")?.trim() !== "model") return slashCommand(params, context);
|
|
308
|
+
// The pinned SDK awaits users.info before dispatch. Picker authorization needs
|
|
309
|
+
// only envelope IDs; optional profile enrichment must not expire the trigger.
|
|
310
|
+
const userId = params.get("user_id") ?? "";
|
|
311
|
+
adapter.chat.processSlashCommand({
|
|
312
|
+
command: params.get("command"), text: params.get("text"),
|
|
313
|
+
user: { userId, userName: params.get("user_name") || userId, fullName: params.get("user_name") || userId, isBot: false, isMe: false },
|
|
314
|
+
adapter, raw: Object.fromEntries(params), triggerId: params.get("trigger_id") || undefined,
|
|
315
|
+
channelId: params.get("channel_id") ? `slack:${params.get("channel_id")}` : "",
|
|
316
|
+
}, context);
|
|
317
|
+
return new Response("", { status: 200 });
|
|
318
|
+
};
|
|
319
|
+
const route = adapter.routeSocketEvent.bind(adapter);
|
|
320
|
+
const disconnect = adapter.disconnect.bind(adapter);
|
|
321
|
+
const pending = new Set();
|
|
322
|
+
let disconnecting;
|
|
323
|
+
// The pinned adapter's async EventEmitter listener neither observes route
|
|
324
|
+
// rejections nor drains acknowledgments before closing its Socket Mode client.
|
|
325
|
+
adapter.routeSocketEvent = (...args) => {
|
|
326
|
+
if (disconnecting) return Promise.resolve();
|
|
327
|
+
const task = (async () => {
|
|
328
|
+
try {
|
|
329
|
+
await route(...args);
|
|
330
|
+
} catch {
|
|
331
|
+
// SDK errors can contain payloads/tokens; keep diagnostics credential-free.
|
|
332
|
+
adapter.logger.error("Pipa Slack Socket Mode event failed.");
|
|
333
|
+
}
|
|
334
|
+
})();
|
|
335
|
+
pending.add(task);
|
|
336
|
+
void task.then(() => pending.delete(task));
|
|
337
|
+
return task;
|
|
338
|
+
};
|
|
339
|
+
adapter.disconnect = () => disconnecting ??= (async () => {
|
|
340
|
+
// Stop ingress before draining; otherwise a new envelope can arrive while
|
|
341
|
+
// SocketModeClient.disconnect() is closing the WebSocket and fail its ack.
|
|
342
|
+
adapter.socketClient?.removeAllListeners("slack_event");
|
|
343
|
+
try {
|
|
344
|
+
await withTimeout(Promise.all([...pending]), drainTimeoutMs, "Slack acknowledgment drain timed out.");
|
|
345
|
+
} catch {
|
|
346
|
+
adapter.logger.error("Pipa Slack acknowledgment drain timed out.");
|
|
347
|
+
} finally {
|
|
348
|
+
await disconnect();
|
|
349
|
+
}
|
|
350
|
+
})();
|
|
351
|
+
return adapter;
|
|
352
|
+
}
|
|
353
|
+
|
|
288
354
|
export function createPendingInteractions(allowedUserIds = []) {
|
|
289
355
|
const pending = new Map();
|
|
290
356
|
const permissionRequests = new Map();
|
|
@@ -759,10 +825,10 @@ function normalizeGrantedScopes(value) {
|
|
|
759
825
|
function warnMissingSlackScopes(auth, warn = (message) => process.stderr.write(`${message}\n`)) {
|
|
760
826
|
if (!Array.isArray(auth?.grantedScopes)) return;
|
|
761
827
|
const missing = ["channels:read", "assistant:write"].filter((scope) => !auth.grantedScopes.includes(scope));
|
|
762
|
-
if (!missing.length) return;
|
|
763
828
|
const scopes = missing.join(", ");
|
|
764
829
|
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.`);
|
|
830
|
+
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.`);
|
|
831
|
+
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
832
|
} catch {}
|
|
767
833
|
}
|
|
768
834
|
|
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
|
}
|
|
@@ -169,9 +183,41 @@ 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
|
+
if (config.mentionOnly !== undefined && typeof config.mentionOnly !== "boolean") {
|
|
187
|
+
throw new Error("Invalid Pipa config: mentionOnly must be a boolean.");
|
|
188
|
+
}
|
|
189
|
+
normalizeModel(config.defaultModel);
|
|
172
190
|
return { ...config, slackMode };
|
|
173
191
|
}
|
|
174
192
|
|
|
193
|
+
export function normalizeModel(value) {
|
|
194
|
+
if (value == null) return null;
|
|
195
|
+
if (typeof value !== "object" || Array.isArray(value)
|
|
196
|
+
|| Object.keys(value).some((key) => !["providerID", "modelID"].includes(key))
|
|
197
|
+
|| ![value.providerID, value.modelID].every((id) => typeof id === "string" && id.trim() === id && id.length > 0 && id.length <= 500 && !/[\u0000-\u001f\u007f]/u.test(id))) {
|
|
198
|
+
throw new Error("Invalid model: expected providerID and modelID.");
|
|
199
|
+
}
|
|
200
|
+
return { providerID: value.providerID, modelID: value.modelID };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function createModelSetting(file = pipaPaths().config, writeJson = writePrivateJson) {
|
|
204
|
+
let tail = Promise.resolve();
|
|
205
|
+
return {
|
|
206
|
+
async save(model, authorize = () => undefined) {
|
|
207
|
+
const selected = normalizeModel(model);
|
|
208
|
+
if (!selected) return Promise.reject(new Error("A model selection is required."));
|
|
209
|
+
const write = tail.then(async () => {
|
|
210
|
+
const current = await loadConfig(file);
|
|
211
|
+
await authorize(current);
|
|
212
|
+
await writeJson(file, { ...current, defaultModel: selected });
|
|
213
|
+
return selected;
|
|
214
|
+
});
|
|
215
|
+
tail = write.catch(() => undefined);
|
|
216
|
+
return write;
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
175
221
|
export async function saveConfig(config, paths = pipaPaths(), manifest = createManifest(config.botName)) {
|
|
176
222
|
await writePrivateJson(paths.manifest, manifest);
|
|
177
223
|
await writePrivateJson(paths.config, config);
|