@usepipa/pipa 0.5.5 → 0.6.0-beta.1
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 +109 -15
- package/bin/pipa.mjs +8 -13
- package/package.json +6 -2
- package/src/app.mjs +75 -23
- package/src/opencode-v1.mjs +380 -0
- package/src/opencode-v2.mjs +722 -0
- package/src/opencode.mjs +244 -363
- package/src/state.mjs +23 -1
package/README.md
CHANGED
|
@@ -1,17 +1,81 @@
|
|
|
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
|
+
### Opt-in 0.6 beta
|
|
7
55
|
|
|
8
|
-
|
|
56
|
+
`0.6.0-beta.1` is being prepared for controlled testing, not stable release.
|
|
57
|
+
Once published, opt in with:
|
|
9
58
|
|
|
10
|
-
|
|
59
|
+
```sh
|
|
60
|
+
npm install --global @usepipa/pipa@0.6.0-beta.1
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Normal installs keep using npm's `latest` tag; subsequent betas use `@beta`.
|
|
64
|
+
This updates Pipa only, not OpenCode. For an existing installation, arrange a
|
|
65
|
+
maintenance window, stop Pipa and back up its profile before installing. Keep
|
|
66
|
+
your current OpenCode version initially; do not rerun `pipa init` or create a
|
|
67
|
+
second listener. See the [beta release notes](https://github.com/lunchpaillola/pipa/blob/main/docs/beta-release.md)
|
|
68
|
+
for changes, limitations, and trial/rollback guidance.
|
|
69
|
+
|
|
70
|
+
## Security model
|
|
71
|
+
|
|
72
|
+
In local mode, Pipa runs on your machine, not behind a relay. The local OpenCode server binds to `127.0.0.1` on an operating-system-assigned port; attached servers follow their own network controls. Slack access is limited by channel, user, and bot allowlists, rechecked on every turn. Tokens stay in the local profile with private file permissions, and OpenCode manages provider credentials.
|
|
73
|
+
|
|
74
|
+
Read [SECURITY.md](SECURITY.md) for the full model and reporting path.
|
|
11
75
|
|
|
12
76
|
## Pipa Managed
|
|
13
77
|
|
|
14
|
-
Want
|
|
78
|
+
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
79
|
|
|
16
80
|
## Local Socket Mode
|
|
17
81
|
|
|
@@ -20,11 +84,13 @@ Profiles created by `pipa init` use Socket Mode. Profiles written before mode su
|
|
|
20
84
|
### Requirements
|
|
21
85
|
|
|
22
86
|
- Node.js 22 or newer
|
|
23
|
-
- [OpenCode](https://opencode.ai) installed and authenticated
|
|
87
|
+
- [OpenCode](https://opencode.ai) installed and authenticated; the dual-adapter candidate selects native v1/v2 automatically (current native v2 qualification target: 2.2.5; historical v2 pin: 2.0.29; v1 pins: 1.18.35, 1.19.0; release-qualified minimums pending)
|
|
24
88
|
- A Slack workspace where you can create an app
|
|
25
89
|
|
|
26
90
|
Invite the Slack app only to channels whose members may use OpenCode in the configured working directory.
|
|
27
91
|
|
|
92
|
+
See [OpenCode compatibility](docs/opencode-compatibility.md) for remaining-on-v1 and deliberate-v2 upgrade paths, matched-snapshot rollback, capability differences and remaining release gates. Upgrading Pipa preserves the existing Slack profile; it does not require recreating the Slack app or upgrading OpenCode.
|
|
93
|
+
|
|
28
94
|
### Install
|
|
29
95
|
|
|
30
96
|
1. Install Pipa:
|
|
@@ -47,11 +113,23 @@ pipa init
|
|
|
47
113
|
pipa start
|
|
48
114
|
```
|
|
49
115
|
|
|
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.
|
|
116
|
+
Keep `pipa start` running, invite Pipa to a trusted public or private Slack channel, and mention it there. In owned local mode, Pipa starts one OpenCode server bound to `127.0.0.1` on an operating-system-assigned port and reuses it for every Slack turn. Port `0` asks the operating system for an available port; no port configuration is required. Pipa replies in a thread, and follow-up messages in that thread reuse the same OpenCode session without another mention. A newer follow-up interrupts an active turn in the same thread, while other threads continue independently. While a turn is active, Pipa shows a typing status in its Slack thread.
|
|
117
|
+
|
|
118
|
+
Ordinary startup detects OpenCode v1/v2 and waits for listening, workspace readiness and Slack initialization without a default overall timeout or migration-status gate. OpenCode owns schema/data upgrades; Pipa never converts that data. Ctrl+C cancels startup and stops owned children, never attached servers. See the [startup contract](docs/opencode-compatibility.md#startup-contract) for retry, failure and explicit-deadline behavior.
|
|
119
|
+
|
|
120
|
+
**Managed external-client upgrade notice:** Before upgrading a Managed profile used by external OpenCode clients, set a shared explicit `OPENCODE_SERVER_PASSWORD` in the Pipa server/restart launch environment and configure that password in every external client. For v2, `OPENCODE_PASSWORD` takes precedence; match it to the shared password or remove conflicting values from the server/restart and client environments. If no explicit password is set, Pipa generates a private per-launch password unavailable to external clients, and unauthenticated clients no longer connect. Keep generated passwords private; use an explicit shared password for external access. See [OpenCode compatibility](docs/opencode-compatibility.md).
|
|
51
121
|
|
|
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
|
|
122
|
+
Pipa keeps naturally short answers inline. For deeper work, OpenCode can return a concise summary with suitable generated files, such as documents, spreadsheets, PDFs, or images. Files are read only from a private session directory under `.pipa/artifacts` in the configured working directory. The directory is cleared before each turn, files are validated and limited to 10 files and 100 MB total, and the directory is deleted locally after delivery. If file delivery fails, Pipa retries the declaration-free summary without the files. Attached OpenCode servers on non-loopback hosts use inline text fallback instead of local artifact delivery.
|
|
53
123
|
|
|
54
|
-
Incoming messages can include up to Slack's 10-file limit, with a maximum size of
|
|
124
|
+
Incoming messages can include up to Slack's 10-file limit, with a maximum size of 10 MiB (10,485,760 bytes) per file. Pipa checks both declared size and downloaded bytes before sending the prompt. Attachments require a text prompt and are copied to a temporary directory only for the duration of the turn. Outgoing artifact limits remain 10 files and 100 MB per file or response.
|
|
125
|
+
|
|
126
|
+
For owned OpenCode v2 servers, Pipa defaults `BUN_JSC_maxRegExpStackSize` to `536870912` (a 512 MiB on-demand regular-expression stack ceiling), preserving any explicit override. This works around native 2.0.29 rejecting valid large base64 attachments. An independently launched attached v2 server needs the same setting in **its server process**, for example `BUN_JSC_maxRegExpStackSize=536870912 opencode serve`; setting it only on the attaching Pipa client cannot configure that server. The model's context/media capabilities still determine which admitted files it can process.
|
|
127
|
+
|
|
128
|
+
### Recovering a blocked OpenCode turn
|
|
129
|
+
|
|
130
|
+
If v2 reports that cleanup failed and new intake is blocked, restore the selected server's connectivity and let any independently submitted work finish, then restart Pipa with `pipa restart`. Use `pipa restart --status` to confirm the outcome. If Pipa already exited, run `pipa start` with the same profile and working directory instead.
|
|
131
|
+
|
|
132
|
+
Startup reconciles the profile's private `~/.pipa/opencode-recovery.json` before accepting Slack or routine work. It removes only owned instructions/admissions and waits for owned execution to settle; it does not replay the failed prompt. Keep the recovery file and session mappings intact. If startup still blocks, resolve the reported server/workspace or foreign-writer conflict before trying again; deleting the recovery file would discard the evidence needed for safe cleanup. Review any partial side effects before manually retrying the original request.
|
|
55
133
|
|
|
56
134
|
### Access control
|
|
57
135
|
|
|
@@ -73,6 +151,18 @@ A human user's mention is only handled when the channel and user pass their resp
|
|
|
73
151
|
|
|
74
152
|
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
153
|
|
|
154
|
+
#### Mention-only mode
|
|
155
|
+
|
|
156
|
+
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:
|
|
157
|
+
|
|
158
|
+
```json
|
|
159
|
+
{
|
|
160
|
+
"mentionOnly": true
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`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.
|
|
165
|
+
|
|
76
166
|
#### Find the sender's bot ID
|
|
77
167
|
|
|
78
168
|
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:
|
|
@@ -130,12 +220,12 @@ If the model window cannot open, its private error distinguishes saved-settings
|
|
|
130
220
|
|
|
131
221
|
**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
222
|
|
|
133
|
-
|
|
223
|
+
To upgrade to `0.5.6`, use the same `PIPA_HOME` as your existing installation (leave it unset for the default `~/.pipa` profile):
|
|
134
224
|
|
|
135
225
|
```sh
|
|
136
|
-
npm install --global @usepipa/pipa@0.5.
|
|
226
|
+
npm install --global @usepipa/pipa@0.5.6
|
|
137
227
|
pipa --version
|
|
138
|
-
pipa manifest > "$HOME/pipa-slack-manifest-0.5.
|
|
228
|
+
pipa manifest > "$HOME/pipa-slack-manifest-0.5.6.json"
|
|
139
229
|
```
|
|
140
230
|
|
|
141
231
|
`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.
|
|
@@ -214,6 +304,8 @@ Anyone allowed by the existing Slack user and channel controls can request a res
|
|
|
214
304
|
|
|
215
305
|
The running Pipa launches a detached worker before stopping intake, cleaning up, and releasing its instance lock. The worker waits for the original process and lock to disappear, then starts a detached replacement and confirms workspace readiness (and Slack readiness for Socket Mode). The replacement continues in the background without terminal output; use `pipa stop` to stop it. This works for Socket and Managed profiles on supported macOS, Linux, and Windows systems. Attached OpenCode servers remain externally owned and are never stopped by Pipa.
|
|
216
306
|
|
|
307
|
+
On Windows, `pipa stop` forcibly terminates Pipa's owned process tree and clears only its unchanged instance lock after exit. It can interrupt active work; `pipa restart` uses the cooperative restart handoff instead.
|
|
308
|
+
|
|
217
309
|
When a restart is requested from Slack, the bot reports that it is restarting and posts to the same thread after the replacement is ready. A manual stop instead reports that the bot will not respond until it starts again.
|
|
218
310
|
|
|
219
311
|
Do not chain `pipa stop` and `pipa start` inside an agent turn: stopping owned OpenCode also kills that turn. OpenCode's `/instance/dispose` disposes an instance; it does not restart the server.
|
|
@@ -241,7 +333,9 @@ npm test
|
|
|
241
333
|
npm run test:pack
|
|
242
334
|
```
|
|
243
335
|
|
|
244
|
-
`npm run test:slack:routines` is a manual real-service smoke test.
|
|
336
|
+
`npm run test:slack:routines` is a manual real-service smoke test. `npm run test:slack:release -- --plan` lists the shared live gates without contacting Slack. The opt-in `--run` collector requires an isolated running Socket candidate and private inputs from `.env.example`; see the testing guide. Human/client and integration evidence remain separate mandatory gates.
|
|
337
|
+
|
|
338
|
+
See the [testing strategy](docs/pipa-testing.md) for repeatable real-runtime and Slack validation, existing-app reuse, evidence, and cleanup.
|
|
245
339
|
|
|
246
340
|
See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
|
|
247
341
|
|
package/bin/pipa.mjs
CHANGED
|
@@ -359,8 +359,11 @@ async function init(io) {
|
|
|
359
359
|
?? (await prompt.question("Allowed Slack user IDs (comma-separated, e.g. UFWBSCZ54; leave empty to allow any user): ")).trim();
|
|
360
360
|
const allowedSlackBotIds = process.env.PIPA_ALLOWED_BOT_IDS
|
|
361
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());
|
|
362
365
|
io.output.write("\nChecking OpenCode and Slack credentials...\n");
|
|
363
|
-
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds, allowedSlackBotIds });
|
|
366
|
+
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds, allowedSlackBotIds, mentionOnly });
|
|
364
367
|
io.output.write(`✓ Credentials validated.\n\nSaved config to ${result.paths.config}. Run \`pipa start\`.\n`);
|
|
365
368
|
} finally {
|
|
366
369
|
prompt.close();
|
|
@@ -408,7 +411,6 @@ async function start(io) {
|
|
|
408
411
|
let failure;
|
|
409
412
|
let stopping = false;
|
|
410
413
|
let ready = false;
|
|
411
|
-
let workspaceReady = true;
|
|
412
414
|
const stop = (termination = "SIGTERM", reason) => {
|
|
413
415
|
stopping = true;
|
|
414
416
|
app?.stop(reason);
|
|
@@ -430,18 +432,11 @@ async function start(io) {
|
|
|
430
432
|
try {
|
|
431
433
|
const config = await loadConfig();
|
|
432
434
|
if (config.slackMode === "managed") {
|
|
433
|
-
server = startOpenCodeServer(config);
|
|
435
|
+
server = await startOpenCodeServer(config, { signal: startup.signal });
|
|
434
436
|
io.output.write(`Pipa is starting OpenCode on ${config.openCodeHostname}:${config.openCodePort}.\n`);
|
|
435
|
-
|
|
436
|
-
// Such an instance cannot accept cooperative restart until it is ready.
|
|
437
|
-
try {
|
|
438
|
-
await Promise.race([server.ready(), signal.promise]);
|
|
439
|
-
} catch (error) {
|
|
440
|
-
if (process.env.PIPA_RESTART_ID) throw error;
|
|
441
|
-
process.stderr.write("Managed restart unavailable: workspace readiness failed.\n");
|
|
442
|
-
workspaceReady = false;
|
|
443
|
-
}
|
|
437
|
+
await Promise.race([server.ready(), signal.promise]);
|
|
444
438
|
} else {
|
|
439
|
+
io.output.write("Waiting for OpenCode... Ctrl+C to stop.\n");
|
|
445
440
|
app = await startPipa({ config, signal: startup.signal });
|
|
446
441
|
io.output.write(app.server.owned
|
|
447
442
|
? `Pipa started a private OpenCode server at ${app.server.baseUrl}.\n`
|
|
@@ -451,7 +446,7 @@ async function start(io) {
|
|
|
451
446
|
const lifetime = app ? app.wait() : server.wait();
|
|
452
447
|
// Observe startup failures already reported by the runtime before ready IPC.
|
|
453
448
|
await Promise.race([lifetime, Promise.resolve()]);
|
|
454
|
-
if (!stopping
|
|
449
|
+
if (!stopping) {
|
|
455
450
|
watcher = startRestartWatcher({
|
|
456
451
|
identity: releaseLock.identity,
|
|
457
452
|
shutdown: () => { stop("SIGTERM", new PipaRestartingError()); return finished.promise; },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usepipa/pipa",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0-beta.1",
|
|
4
4
|
"description": "Run Pipa through Slack Socket Mode with OpenCode",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"slack",
|
|
@@ -21,7 +21,10 @@
|
|
|
21
21
|
"scripts": {
|
|
22
22
|
"test": "node --test",
|
|
23
23
|
"test:pack": "node scripts/pack-smoke.mjs",
|
|
24
|
-
"test:
|
|
24
|
+
"test:engines": "node scripts/test-opencode-matrix.mjs",
|
|
25
|
+
"test:beta": "node scripts/test-opencode-matrix.mjs --smoke",
|
|
26
|
+
"test:slack:routines": "node scripts/slack-routine-eval.mjs",
|
|
27
|
+
"test:slack:release": "node scripts/slack-release-eval.mjs"
|
|
25
28
|
},
|
|
26
29
|
"engines": {
|
|
27
30
|
"node": ">=22"
|
|
@@ -42,6 +45,7 @@
|
|
|
42
45
|
"dependencies": {
|
|
43
46
|
"@chat-adapter/slack": "4.38.1",
|
|
44
47
|
"@chat-adapter/state-memory": "4.38.1",
|
|
48
|
+
"@opencode/client": "2.0.29",
|
|
45
49
|
"chat": "4.38.1",
|
|
46
50
|
"cross-spawn": "7.0.6",
|
|
47
51
|
"luxon": "3.7.2"
|
package/src/app.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import { createSlackAdapter } from "@chat-adapter/slack";
|
|
|
5
5
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
6
6
|
import { canonicalWorkingDirectory, createManifest, createModelSetting, createSessionStore, loadConfig, pipaPaths, saveConfig, slackCommandNames } from "./state.mjs";
|
|
7
7
|
import { createModelPicker } from "./models.mjs";
|
|
8
|
-
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaRestartingError, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
8
|
+
import { checkOpenCodeConnection, createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, parseOpenCodeVersion, PipaRestartingError, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
9
9
|
import { assertRoutineDestinationAllowed, createRoutineScheduler, loadRoutineState } from "./routines.mjs";
|
|
10
10
|
|
|
11
11
|
class RoutineDeniedError extends Error {}
|
|
@@ -21,9 +21,12 @@ export async function initializePipa(input, options = {}) {
|
|
|
21
21
|
allowedSlackChannelIds: normalizeIdList(input.allowedSlackChannelIds),
|
|
22
22
|
allowedSlackUserIds: normalizeIdList(input.allowedSlackUserIds),
|
|
23
23
|
allowedSlackBotIds: normalizeIdList(input.allowedSlackBotIds),
|
|
24
|
+
mentionOnly: input.mentionOnly === true,
|
|
24
25
|
};
|
|
25
|
-
const
|
|
26
|
-
|
|
26
|
+
const environment = options.environment ?? process.env;
|
|
27
|
+
const attachUrl = environment.PIPA_OPENCODE_ATTACH_URL?.trim();
|
|
28
|
+
if (attachUrl) await checkOpenCodeConnection(attachUrl, config.workingDirectory, options);
|
|
29
|
+
else parseOpenCodeVersion(await (options.checkOpenCode ?? runOpenCodeVersion)(options));
|
|
27
30
|
await (options.checkSlackAppToken ?? checkSlackAppToken)(config.slackAppToken);
|
|
28
31
|
const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
29
32
|
warnMissingSlackScopes(slackAuth, options.warn);
|
|
@@ -69,8 +72,12 @@ export async function startPipa(options = {}) {
|
|
|
69
72
|
executor = options.executor ?? (options.createExecutor ?? createOpenCodeExecutor)({
|
|
70
73
|
artifactRoot: path.join(config.workingDirectory, ".pipa", "artifacts"),
|
|
71
74
|
baseUrl: server.baseUrl,
|
|
75
|
+
connection: server.connection,
|
|
76
|
+
recoveryFile: paths.openCodeRecovery,
|
|
72
77
|
onFatal: server.fail,
|
|
73
78
|
});
|
|
79
|
+
await executor.ready?.(config.workingDirectory);
|
|
80
|
+
options.signal?.throwIfAborted();
|
|
74
81
|
} catch (error) {
|
|
75
82
|
server?.stop();
|
|
76
83
|
await withTimeout(server?.wait(), options.shutdownTimeoutMs ?? 15_000, "OpenCode shutdown timed out.").catch(() => undefined);
|
|
@@ -176,11 +183,12 @@ export async function startPipa(options = {}) {
|
|
|
176
183
|
const pending = pendingReactions.get(conversationKey) ?? [];
|
|
177
184
|
if (pending.at(-1)?.message !== currentMessage) return;
|
|
178
185
|
pendingReactions.delete(conversationKey);
|
|
179
|
-
for (const entry of pending) await finishReaction(entry.thread, entry.message, entry.message === currentMessage ? emoji :
|
|
186
|
+
for (const entry of pending) await finishReaction(entry.thread, entry.message, entry.message === currentMessage ? emoji : null);
|
|
180
187
|
};
|
|
181
188
|
|
|
182
189
|
const handle = async (thread, message, subscribe) => {
|
|
183
190
|
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message, config)) return;
|
|
191
|
+
if (config.mentionOnly && !subscribe && !message.isMention) return;
|
|
184
192
|
const messageText = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
185
193
|
const missingLinks = (message.links ?? []).map((link) => link.url)
|
|
186
194
|
.filter((url) => typeof url === "string" && !messageText.split(/\s+/u).includes(url));
|
|
@@ -189,7 +197,7 @@ export async function startPipa(options = {}) {
|
|
|
189
197
|
const attachments = message.attachments ?? [];
|
|
190
198
|
if (subscribe) await thread.subscribe();
|
|
191
199
|
if (attachments.some(({ size }) => size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_ATTACHMENT_BYTES))) {
|
|
192
|
-
await thread.post("Pipa can read files up to
|
|
200
|
+
await thread.post("Pipa can read files up to 10 MiB each.");
|
|
193
201
|
return;
|
|
194
202
|
}
|
|
195
203
|
if (!accepting) return;
|
|
@@ -245,7 +253,7 @@ export async function startPipa(options = {}) {
|
|
|
245
253
|
await chat.thread(conversationKey).subscribe();
|
|
246
254
|
options.signal?.throwIfAborted();
|
|
247
255
|
}
|
|
248
|
-
await withTimeout(chat.initialize(), options.startupTimeoutMs
|
|
256
|
+
await withTimeout(chat.initialize(), options.startupTimeoutMs, "Slack Socket Mode startup timed out.", options.signal);
|
|
249
257
|
options.signal?.throwIfAborted();
|
|
250
258
|
await routineScheduler?.start();
|
|
251
259
|
options.signal?.throwIfAborted();
|
|
@@ -316,8 +324,11 @@ export function createPipaSlackAdapter(options, drainTimeoutMs = 3_000) {
|
|
|
316
324
|
};
|
|
317
325
|
const route = adapter.routeSocketEvent.bind(adapter);
|
|
318
326
|
const disconnect = adapter.disconnect.bind(adapter);
|
|
327
|
+
const startSocketMode = adapter.startSocketMode.bind(adapter);
|
|
319
328
|
const pending = new Set();
|
|
320
329
|
let disconnecting;
|
|
330
|
+
// SDK auth may settle after shutdown; do not create a socket in that case.
|
|
331
|
+
adapter.startSocketMode = (...args) => disconnecting ? Promise.resolve() : startSocketMode(...args);
|
|
321
332
|
// The pinned adapter's async EventEmitter listener neither observes route
|
|
322
333
|
// rejections nor drains acknowledgments before closing its Socket Mode client.
|
|
323
334
|
adapter.routeSocketEvent = (...args) => {
|
|
@@ -368,9 +379,23 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
368
379
|
threadId: context.thread.id,
|
|
369
380
|
loadAllowedUserIds: context.loadAllowedUserIds,
|
|
370
381
|
authorize: context.authorize,
|
|
382
|
+
native: typeof interaction.submit === "function",
|
|
383
|
+
};
|
|
384
|
+
entry.choose = async (value) => {
|
|
385
|
+
if (entry.busy || entry.decision !== undefined) return;
|
|
386
|
+
entry.busy = true;
|
|
387
|
+
try {
|
|
388
|
+
await interaction.submit?.(value);
|
|
389
|
+
if (!interaction.signal.aborted) entry.resolve(value);
|
|
390
|
+
} catch {
|
|
391
|
+
if (entry.decision !== undefined || interaction.signal.aborted) return;
|
|
392
|
+
entry.questionIndex = 0;
|
|
393
|
+
entry.error = "OpenCode rejected or could not confirm this response. Edit your answer and retry.";
|
|
394
|
+
await entry.message?.edit();
|
|
395
|
+
} finally { entry.busy = false; }
|
|
371
396
|
};
|
|
372
397
|
const decision = new Promise((resolve, reject) => {
|
|
373
|
-
const abort = () => reject(interaction.signal.reason);
|
|
398
|
+
const abort = () => { entry.decision ??= { type: "stopped" }; reject(interaction.signal.reason); };
|
|
374
399
|
entry.resolve = (value) => {
|
|
375
400
|
if (entry.decision !== undefined) return;
|
|
376
401
|
entry.decision = value;
|
|
@@ -380,7 +405,12 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
380
405
|
if (interaction.signal.aborted) abort();
|
|
381
406
|
else interaction.signal.addEventListener("abort", abort, { once: true });
|
|
382
407
|
});
|
|
408
|
+
// A queued card can be cancelled before its predecessor releases the thread.
|
|
409
|
+
void decision.catch(() => undefined);
|
|
383
410
|
pending.set(token, entry);
|
|
411
|
+
// Native settlement is independent of the responder callback (another client
|
|
412
|
+
// may answer or a location reload may cancel while this card is queued).
|
|
413
|
+
interaction.settled?.then(() => entry.resolve({ type: "cancelled" }), () => entry.resolve({ type: "cancelled" }));
|
|
384
414
|
const requestId = interaction.request.requestID ?? interaction.request.requestId ?? interaction.request.id;
|
|
385
415
|
const permissionKey = interaction.type === "permission" && requestId ? `${interaction.sessionId}:${requestId}` : null;
|
|
386
416
|
if (permissionKey) permissionRequests.set(permissionKey, entry);
|
|
@@ -401,7 +431,7 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
401
431
|
await submit(entry, result);
|
|
402
432
|
return result;
|
|
403
433
|
} finally {
|
|
404
|
-
if (entry.
|
|
434
|
+
if (!entry.submitted) {
|
|
405
435
|
entry.resolve?.({ type: "stopped" });
|
|
406
436
|
await submit(entry, { type: "stopped" }).catch(() => undefined);
|
|
407
437
|
}
|
|
@@ -414,12 +444,13 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
414
444
|
|
|
415
445
|
function onPermissionReplied({ sessionId, requestId, reply }) {
|
|
416
446
|
const entry = permissionRequests.get(`${sessionId}:${requestId}`);
|
|
447
|
+
if (entry?.native) return;
|
|
417
448
|
entry?.resolve?.(reply === "reject" ? { type: "reject" } : { type: "reply", reply });
|
|
418
449
|
}
|
|
419
450
|
|
|
420
451
|
function onPermissionsReconciled({ sessionId, requestIds }) {
|
|
421
452
|
for (const entry of permissionRequests.values()) {
|
|
422
|
-
if (entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
|
|
453
|
+
if (!entry.native && entry.sessionId === sessionId && !requestIds.has(entry.requestId)) entry.resolve?.({ type: "cancelled" });
|
|
423
454
|
}
|
|
424
455
|
}
|
|
425
456
|
|
|
@@ -435,19 +466,21 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
435
466
|
if (!entry) return;
|
|
436
467
|
if ((event.threadId ?? event.thread?.id) !== entry.threadId) return;
|
|
437
468
|
if (!await canRespond(entry, event.user)) return;
|
|
469
|
+
if (entry.busy || entry.decision !== undefined || entry.type === "form") return;
|
|
438
470
|
if (event.actionId?.startsWith("pipa_dismiss_")) {
|
|
439
|
-
entry.
|
|
471
|
+
await entry.choose({ type: "stop" });
|
|
440
472
|
return;
|
|
441
473
|
}
|
|
442
474
|
if (entry.type === "permission") {
|
|
443
475
|
const reply = String(event.value ?? "").split(".")[1];
|
|
444
476
|
if (!["once", "always", "reject"].includes(reply)) return;
|
|
445
477
|
const selectedBy = displayName(event.user?.fullName ?? event.user?.userName);
|
|
446
|
-
entry.
|
|
478
|
+
await entry.choose(reply === "reject" ? { type: "reject", ...(selectedBy ? { selectedBy } : {}) } : { type: "reply", reply, ...(selectedBy ? { selectedBy } : {}) });
|
|
447
479
|
return;
|
|
448
480
|
}
|
|
449
481
|
if (event.actionId?.startsWith("pipa_custom_")) {
|
|
450
|
-
|
|
482
|
+
const question = entry.request.questions?.[entry.questionIndex] ?? entry.request;
|
|
483
|
+
await event.openModal?.(Modal({ callbackId: "pipa_custom", privateMetadata: token, title: "Custom answer", submitLabel: "Submit", children: [TextInput({ id: "answer", label: question.multiple ? "Answer (replaces checkbox selections)" : "Answer" })] }));
|
|
451
484
|
return;
|
|
452
485
|
}
|
|
453
486
|
if (entry.type !== "question") return;
|
|
@@ -458,8 +491,14 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
458
491
|
return;
|
|
459
492
|
}
|
|
460
493
|
if (event.actionId?.startsWith("pipa_submit_")) {
|
|
494
|
+
// Submit carries the current UI state even if earlier selection events arrive late.
|
|
495
|
+
const values = event.raw?.state?.values;
|
|
496
|
+
const blockId = `pipa_question_${entry.token}_${entry.questionIndex}`;
|
|
497
|
+
if (values && !Object.hasOwn(values, blockId)) return;
|
|
498
|
+
const selection = values?.[blockId]?.[`pipa_select_${entry.token}`];
|
|
499
|
+
if (selection) entry.answers[entry.questionIndex] = selectedAnswers(event, selection);
|
|
461
500
|
if (!entry.answers[entry.questionIndex]?.length) return;
|
|
462
|
-
advance(entry, event.user);
|
|
501
|
+
await advance(entry, event.user);
|
|
463
502
|
return;
|
|
464
503
|
}
|
|
465
504
|
}
|
|
@@ -469,16 +508,18 @@ export function createPendingInteractions(allowedUserIds = []) {
|
|
|
469
508
|
if (!entry) return;
|
|
470
509
|
if (event.relatedThread?.id !== entry.threadId) return;
|
|
471
510
|
if (!await canRespond(entry, event.user)) return;
|
|
511
|
+
if (entry.busy || entry.decision !== undefined || entry.type !== "question") return;
|
|
472
512
|
const answer = event.values?.answer?.trim();
|
|
473
513
|
if (!answer) return { action: "errors", errors: { answer: "Enter an answer." } };
|
|
514
|
+
// Custom answers intentionally replace selections rather than combine with them.
|
|
474
515
|
entry.answers[entry.questionIndex] = [answer];
|
|
475
|
-
advance(entry, event.user);
|
|
516
|
+
await advance(entry, event.user);
|
|
476
517
|
}
|
|
477
518
|
|
|
478
|
-
function advance(entry, user) {
|
|
519
|
+
async function advance(entry, user) {
|
|
479
520
|
if (++entry.questionIndex === (entry.request.questions?.length ?? 1)) {
|
|
480
521
|
const selectedBy = displayName(user?.fullName ?? user?.userName);
|
|
481
|
-
entry.
|
|
522
|
+
await entry.choose({ type: "answer", answers: entry.answers, ...(selectedBy ? { selectedBy } : {}) });
|
|
482
523
|
}
|
|
483
524
|
else entry.message?.edit();
|
|
484
525
|
}
|
|
@@ -544,10 +585,12 @@ async function postInteraction(thread, entry) {
|
|
|
544
585
|
}
|
|
545
586
|
|
|
546
587
|
function renderSlackInteraction(entry) {
|
|
588
|
+
if (entry.type === "form") return [slackHeader(entry.request.title || "OpenCode form"), slackText("This form requires an OpenCode client response. Pipa will remove this notice when it is settled.")];
|
|
547
589
|
if (entry.type === "permission") {
|
|
548
590
|
const resources = entry.request.patterns ?? entry.request.resources ?? [];
|
|
549
591
|
return [
|
|
550
592
|
slackHeader("Permission requested"),
|
|
593
|
+
...(entry.error ? [slackText(entry.error)] : []),
|
|
551
594
|
slackText(permissionDetail(entry.request, resources)),
|
|
552
595
|
slackActions([
|
|
553
596
|
slackButton(`pipa_permission_once_${entry.token}`, "Allow once", `${entry.token}.once`, "primary"),
|
|
@@ -569,7 +612,7 @@ function renderSlackInteraction(entry) {
|
|
|
569
612
|
...(options.length ? [slackButton(`pipa_submit_${entry.token}`, "Submit", entry.token, "primary")] : []),
|
|
570
613
|
slackButton(`pipa_dismiss_${entry.token}`, "Dismiss", entry.token, "danger"),
|
|
571
614
|
];
|
|
572
|
-
return [slackHeader(question.header || "Question"), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [slackActions([selector])] : []), slackActions(actions)];
|
|
615
|
+
return [slackHeader(question.header || "Question"), ...(entry.error ? [slackText(entry.error)] : []), slackText(question.question ?? question.header ?? "Choose an answer."), ...(selector ? [{ ...slackActions([selector]), block_id: `pipa_question_${entry.token}_${entry.questionIndex}` }] : []), slackActions(actions)];
|
|
573
616
|
}
|
|
574
617
|
|
|
575
618
|
function renderSlackSubmitted(entry, decision) {
|
|
@@ -635,9 +678,8 @@ function slackButton(actionId, text, value, style) {
|
|
|
635
678
|
return { type: "button", action_id: actionId, text: { type: "plain_text", text }, value, ...(style ? { style } : {}) };
|
|
636
679
|
}
|
|
637
680
|
|
|
638
|
-
function selectedAnswers(event) {
|
|
639
|
-
const
|
|
640
|
-
const values = action?.selected_options?.map((option) => option.value) ?? [event.value];
|
|
681
|
+
function selectedAnswers(event, action = event.raw?.actions?.find((item) => item.action_id === event.actionId)) {
|
|
682
|
+
const values = action?.selected_options?.map((option) => option.value) ?? [action?.selected_option?.value ?? event.value];
|
|
641
683
|
return values.filter(Boolean).map((value) => String(value).split(".").slice(1).join(".")).filter(Boolean);
|
|
642
684
|
}
|
|
643
685
|
|
|
@@ -922,15 +964,25 @@ async function finishReaction(thread, message, emoji) {
|
|
|
922
964
|
if (emoji) await react(thread, message, emoji);
|
|
923
965
|
}
|
|
924
966
|
|
|
925
|
-
async function withTimeout(promise, timeoutMs, message) {
|
|
967
|
+
async function withTimeout(promise, timeoutMs, message, signal) {
|
|
926
968
|
if (!promise) return;
|
|
969
|
+
if (timeoutMs === undefined && !signal) return promise;
|
|
927
970
|
let timer;
|
|
971
|
+
let abort;
|
|
928
972
|
try {
|
|
929
973
|
return await Promise.race([
|
|
930
974
|
promise,
|
|
931
|
-
new Promise((_, reject) =>
|
|
975
|
+
new Promise((_, reject) => {
|
|
976
|
+
if (timeoutMs !== undefined) timer = setTimeout(() => reject(new Error(message)), timeoutMs);
|
|
977
|
+
if (signal) {
|
|
978
|
+
abort = () => reject(signal.reason);
|
|
979
|
+
if (signal.aborted) abort();
|
|
980
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
981
|
+
}
|
|
982
|
+
}),
|
|
932
983
|
]);
|
|
933
984
|
} finally {
|
|
934
|
-
clearTimeout(timer);
|
|
985
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
986
|
+
if (abort) signal.removeEventListener("abort", abort);
|
|
935
987
|
}
|
|
936
988
|
}
|