@usepipa/pipa 0.5.2 → 0.5.4
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 +57 -3
- package/bin/pipa.mjs +118 -38
- package/package.json +1 -1
- package/src/app.mjs +40 -16
- package/src/opencode.mjs +37 -10
- package/src/restart.mjs +304 -0
- package/src/state.mjs +43 -10
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ Incoming messages can include up to Slack's 10-file limit, with a maximum size o
|
|
|
55
55
|
|
|
56
56
|
### Access control
|
|
57
57
|
|
|
58
|
-
By default Pipa answers
|
|
58
|
+
By default Pipa answers any human user who mentions it in a channel it can see, excluding DMs and external channels. In a shared workspace, restrict who can use it by listing the allowed Slack channel and user IDs. `pipa init` asks for these, and they are stored in the config:
|
|
59
59
|
|
|
60
60
|
```json
|
|
61
61
|
{
|
|
@@ -64,11 +64,44 @@ By default Pipa answers anyone who mentions it in a channel it can see. In a sha
|
|
|
64
64
|
"slackAppToken": "xapp-...",
|
|
65
65
|
"slackBotToken": "xoxb-...",
|
|
66
66
|
"allowedSlackChannelIds": ["C0BSE2JTYPR"],
|
|
67
|
-
"allowedSlackUserIds": ["UFWBSCZ54"]
|
|
67
|
+
"allowedSlackUserIds": ["UFWBSCZ54"],
|
|
68
|
+
"allowedSlackBotIds": ["B0C6Q27E82X"]
|
|
68
69
|
}
|
|
69
70
|
```
|
|
70
71
|
|
|
71
|
-
A mention is only handled when the channel
|
|
72
|
+
A human user's mention is only handled when the channel and user pass their respective allowlists. An absent or empty `allowedSlackChannelIds` allows any otherwise eligible channel; an absent or empty `allowedSlackUserIds` allows any human user. You can also set them non-interactively during setup with `PIPA_ALLOWED_CHANNEL_IDS` and `PIPA_ALLOWED_USER_IDS` (comma-separated).
|
|
73
|
+
|
|
74
|
+
By default Pipa ignores messages sent by other Slack apps. Unlike the human user and channel lists, an absent or empty `allowedSlackBotIds` disables all other bots. List their bot IDs to let those messages through; an allowed bot only needs its bot ID (e.g. `B0C6Q27E82X`), not an entry in `allowedSlackUserIds`. Bots still must pass the channel allowlist. Bots not on the list stay ignored even when `allowedSlackUserIds` is empty. Set it non-interactively during setup with `PIPA_ALLOWED_BOT_IDS` (comma-separated).
|
|
75
|
+
|
|
76
|
+
#### Find the sender's bot ID
|
|
77
|
+
|
|
78
|
+
Use the message event's `bot_id` (`B…`), not the app ID (`A…`) or bot user ID (`U…`). To look up the sender app's OAuth bot ID:
|
|
79
|
+
|
|
80
|
+
1. Open the **sender app** at [Slack Apps](https://api.slack.com/apps), not Pipa's app.
|
|
81
|
+
2. Under **OAuth & Permissions**, copy its **Bot User OAuth Token** (`xoxb-…`). If needed, install the app in the workspace via **Install App** first.
|
|
82
|
+
3. Set that token locally in `SLACK_SENDER_BOT_TOKEN`, then call [Slack `auth.test`](https://docs.slack.dev/reference/methods/auth.test/):
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
curl --silent --show-error --request POST \
|
|
86
|
+
--header "Authorization: Bearer ${SLACK_SENDER_BOT_TOKEN}" \
|
|
87
|
+
https://slack.com/api/auth.test
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
No Slack CLI is needed. Keep the token out of config examples, shared output, and commits. A successful response includes fields like:
|
|
91
|
+
|
|
92
|
+
```json
|
|
93
|
+
{
|
|
94
|
+
"ok": true,
|
|
95
|
+
"user_id": "U0123456789",
|
|
96
|
+
"bot_id": "B0123456789"
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Use `bot_id` (`B0123456789`) in `allowedSlackBotIds`; `user_id` identifies the bot's user account and is not the bot allowlist ID.
|
|
101
|
+
|
|
102
|
+
**Incoming webhooks:** the posted message's `bot_id` can differ from the sender app's OAuth `bot_id` returned by `auth.test`. Allow the actual incoming message/event's `bot_id`. If you do not have the event payload, find the posted message with [Slack `conversations.history`](https://docs.slack.dev/reference/methods/conversations.history/) (or [`conversations.replies`](https://docs.slack.dev/reference/methods/conversations.replies/) for a thread reply), using a token with access to that conversation and the required history scope, and read its `bot_id`.
|
|
103
|
+
|
|
104
|
+
After saving the config, restart Pipa to load the updated allowlist. The allowed bot can start a conversation by posting `<@PIPA_BOT_USER_ID> triage this alert` in an allowed channel, or continue one by replying in a thread Pipa has subscribed to. For an incoming webhook, send that mention in the payload's `text` field. Allowlisting a bot does not make Pipa handle every message it posts in the channel; the normal mention/thread routing still applies. Only allow bots whose messages you trust as requests to your agent.
|
|
72
105
|
|
|
73
106
|
To use an existing OpenCode server instead, set its URL before starting Pipa. Pipa checks that the server can serve the configured workspace but does not start or stop it. If the server uses authentication, also set `OPENCODE_SERVER_USERNAME` and `OPENCODE_SERVER_PASSWORD`:
|
|
74
107
|
|
|
@@ -116,12 +149,33 @@ Use `pipa routine list`, `show`, `edit`, `run`, and `delete` for the lifecycle.
|
|
|
116
149
|
|
|
117
150
|
Routines run only while the Socket Mode `pipa start` process is running and the machine is awake. Restart skips missed scheduled occurrences instead of backfilling them. Explicit run requests survive restart, but can repeat if the process crashes after agent side effects or Slack delivery and before completion is saved. Managed profiles do not execute routines. Run `pipa routine --help` for the complete syntax and JSON contract.
|
|
118
151
|
|
|
152
|
+
### Restarting Pipa
|
|
153
|
+
|
|
154
|
+
Ask Pipa to restart, or run:
|
|
155
|
+
|
|
156
|
+
```sh
|
|
157
|
+
pipa restart
|
|
158
|
+
pipa restart --status
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Anyone allowed by the existing Slack user and channel controls can request a restart; there is no separate restart approval. The first command reports **requested**, not completed. The read-only status command shows the latest request ID, state (`requested`, `running`, `completed`, `failed`, or `unconfirmed`), phase, and any failure guidance. An expired handoff is unconfirmed, never assumed successful. Private records under `.pipa/restarts` remain available after the initiating turn exits.
|
|
162
|
+
|
|
163
|
+
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.
|
|
164
|
+
|
|
165
|
+
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.
|
|
166
|
+
|
|
167
|
+
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.
|
|
168
|
+
|
|
169
|
+
Commands must use the same `PIPA_HOME` (the parent of `.pipa`) as the running profile. Pipa passes the resolved absolute home to its owned OpenCode and restart processes. With an attached server, ensure the agent's command environment uses that home; a remote server needs command access to the Pipa host. An older running Pipa needs one manual stop/start after upgrading. If status reports failure or an unconfirmed handoff, inspect the reported phase and current instance before attempting a manual start.
|
|
170
|
+
|
|
119
171
|
## Commands
|
|
120
172
|
|
|
121
173
|
```text
|
|
122
174
|
pipa init Configure Slack and the local working directory
|
|
123
175
|
pipa start Start the configured Slack runtime
|
|
124
176
|
pipa stop Stop the running local Pipa process
|
|
177
|
+
pipa restart [--channel <id> [--thread <ts>]] Request a detached restart
|
|
178
|
+
pipa restart --status Inspect the latest durable restart outcome
|
|
125
179
|
pipa routine Create and manage local scheduled routines
|
|
126
180
|
pipa --version Print the installed version
|
|
127
181
|
```
|
package/bin/pipa.mjs
CHANGED
|
@@ -5,13 +5,15 @@ import { constants } from "node:fs";
|
|
|
5
5
|
import { lstat, open, readFile, realpath } from "node:fs/promises";
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
import path from "node:path";
|
|
8
|
+
import os from "node:os";
|
|
8
9
|
import { createInterface } from "node:readline/promises";
|
|
9
10
|
import { Writable } from "node:stream";
|
|
10
11
|
import { stdin, stdout } from "node:process";
|
|
11
12
|
import { acquireInstanceLock, createManifest, createManifestUrl, loadConfig, stopInstance } from "../src/state.mjs";
|
|
12
13
|
import { initializePipa, startPipa } from "../src/app.mjs";
|
|
13
|
-
import { startOpenCodeServer } from "../src/opencode.mjs";
|
|
14
|
+
import { PipaRestartingError, startOpenCodeServer } from "../src/opencode.mjs";
|
|
14
15
|
import { createRoutine, deleteRoutine, editRoutine, loadRoutineState, requestRoutineRun } from "../src/routines.mjs";
|
|
16
|
+
import { requestRestart, restartStatus, startRestartWatcher, reportRestartReady, reportRestartFailure } from "../src/restart.mjs";
|
|
15
17
|
|
|
16
18
|
const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
|
|
17
19
|
|
|
@@ -24,8 +26,34 @@ async function main(argv = process.argv.slice(2), io = { input: stdin, output: s
|
|
|
24
26
|
if (command === "init") return init(io);
|
|
25
27
|
if (command === "start") return start(io);
|
|
26
28
|
if (command === "stop") return stop(io);
|
|
29
|
+
if (command === "restart") return restart(argv.slice(1), io);
|
|
27
30
|
if (command === "routine") return routine(argv.slice(1), io);
|
|
28
|
-
|
|
31
|
+
const usage = "Usage: pipa init | pipa start | pipa stop | pipa restart [--status] | pipa routine | pipa --version";
|
|
32
|
+
if (command === "--help" || command === "-h") return io.output.write(`${usage}\n`);
|
|
33
|
+
throw new Error(usage);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function restart(argv, io) {
|
|
37
|
+
if (argv.length === 1 && ["--help", "-h"].includes(argv[0])) {
|
|
38
|
+
io.output.write("Usage: pipa restart [--status] [--channel <id> [--thread <ts>]]\nRequest a detached restart, or inspect its latest durable outcome.\n");
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (argv[0] === "--status") {
|
|
42
|
+
if (argv.length !== 1) throw new Error("Usage: pipa restart [--status] [--channel <id> [--thread <ts>]]");
|
|
43
|
+
const status = await restartStatus();
|
|
44
|
+
io.output.write(status ? `${JSON.stringify(status, null, 2)}\n` : "No restart requested.\n");
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
let channelId;
|
|
48
|
+
let threadTs;
|
|
49
|
+
for (let index = 0; index < argv.length; index += 2) {
|
|
50
|
+
if (argv[index] === "--channel" && argv[index + 1]) channelId = argv[index + 1];
|
|
51
|
+
else if (argv[index] === "--thread" && argv[index + 1]) threadTs = argv[index + 1];
|
|
52
|
+
else throw new Error("Usage: pipa restart [--status] [--channel <id> [--thread <ts>]]");
|
|
53
|
+
}
|
|
54
|
+
if (threadTs && !channelId) throw new Error("Usage: pipa restart [--status] [--channel <id> [--thread <ts>]]");
|
|
55
|
+
const request = await requestRestart({ destination: channelId ? { channelId, ...(threadTs ? { threadTs } : {}) } : undefined });
|
|
56
|
+
io.output.write(`Restart requested (${request.id}). Check \`pipa restart --status\` for the outcome.\n`);
|
|
29
57
|
}
|
|
30
58
|
|
|
31
59
|
const ROUTINE_HELP = `Usage: pipa routine <command>
|
|
@@ -320,8 +348,10 @@ async function init(io) {
|
|
|
320
348
|
?? (await prompt.question("Allowed Slack channel IDs (comma-separated, e.g. C0BSE2JTYPR; leave empty to allow any channel): ")).trim();
|
|
321
349
|
const allowedSlackUserIds = process.env.PIPA_ALLOWED_USER_IDS
|
|
322
350
|
?? (await prompt.question("Allowed Slack user IDs (comma-separated, e.g. UFWBSCZ54; leave empty to allow any user): ")).trim();
|
|
351
|
+
const allowedSlackBotIds = process.env.PIPA_ALLOWED_BOT_IDS
|
|
352
|
+
?? (await prompt.question("Allowed Slack bot IDs (comma-separated, e.g. B0C6Q27E82X; leave empty to ignore bot messages): ")).trim();
|
|
323
353
|
io.output.write("\nChecking OpenCode and Slack credentials...\n");
|
|
324
|
-
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds });
|
|
354
|
+
const result = await initializePipa({ botName, workingDirectory, slackAppToken, slackBotToken, allowedSlackChannelIds, allowedSlackUserIds, allowedSlackBotIds });
|
|
325
355
|
io.output.write(`✓ Credentials validated.\n\nSaved config to ${result.paths.config}. Run \`pipa start\`.\n`);
|
|
326
356
|
} finally {
|
|
327
357
|
prompt.close();
|
|
@@ -356,55 +386,105 @@ function openUrl(url) {
|
|
|
356
386
|
}
|
|
357
387
|
|
|
358
388
|
async function start(io) {
|
|
389
|
+
// Resolve before OpenCode changes cwd, so its tools address this same profile.
|
|
390
|
+
process.env.PIPA_HOME = path.resolve(process.env.PIPA_HOME || os.homedir());
|
|
359
391
|
const releaseLock = await acquireInstanceLock();
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
392
|
+
const finished = Promise.withResolvers();
|
|
393
|
+
void finished.promise.catch(() => undefined);
|
|
394
|
+
const signal = Promise.withResolvers();
|
|
395
|
+
const startup = new AbortController();
|
|
396
|
+
let app;
|
|
397
|
+
let server;
|
|
398
|
+
let watcher;
|
|
399
|
+
let failure;
|
|
400
|
+
let stopping = false;
|
|
401
|
+
let ready = false;
|
|
402
|
+
let workspaceReady = true;
|
|
403
|
+
const stop = (termination = "SIGTERM", reason) => {
|
|
404
|
+
stopping = true;
|
|
405
|
+
app?.stop(reason);
|
|
406
|
+
startup.abort();
|
|
407
|
+
server?.stop(termination);
|
|
408
|
+
signal.resolve();
|
|
409
|
+
};
|
|
410
|
+
const stopWithSigint = () => stop("SIGINT");
|
|
411
|
+
const stopWithSigterm = () => stop();
|
|
412
|
+
const disconnected = () => {
|
|
413
|
+
if (!ready) {
|
|
414
|
+
failure ??= new Error("Restart readiness handoff disconnected before startup completed.");
|
|
415
|
+
stop();
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
if (process.env.PIPA_RESTART_ID) process.on("disconnect", disconnected);
|
|
419
|
+
process.on("SIGINT", stopWithSigint);
|
|
420
|
+
process.on("SIGTERM", stopWithSigterm);
|
|
363
421
|
try {
|
|
364
422
|
const config = await loadConfig();
|
|
365
423
|
if (config.slackMode === "managed") {
|
|
366
|
-
|
|
424
|
+
server = startOpenCodeServer(config);
|
|
367
425
|
io.output.write(`Pipa is starting OpenCode on ${config.openCodeHostname}:${config.openCodePort}.\n`);
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
426
|
+
// Ordinary Managed starts retain their lifetime even if health is unavailable.
|
|
427
|
+
// Such an instance cannot accept cooperative restart until it is ready.
|
|
428
|
+
try {
|
|
429
|
+
await Promise.race([server.ready(), signal.promise]);
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (process.env.PIPA_RESTART_ID) throw error;
|
|
432
|
+
process.stderr.write("Managed restart unavailable: workspace readiness failed.\n");
|
|
433
|
+
workspaceReady = false;
|
|
434
|
+
}
|
|
435
|
+
} else {
|
|
436
|
+
app = await startPipa({ config, signal: startup.signal });
|
|
437
|
+
io.output.write(app.server.owned
|
|
438
|
+
? `Pipa started a private OpenCode server at ${app.server.baseUrl}.\n`
|
|
439
|
+
: `Pipa is using the configured OpenCode server at ${app.server.baseUrl}.\n`);
|
|
440
|
+
io.output.write("Pipa is connected through Slack Socket Mode.\n");
|
|
374
441
|
}
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
442
|
+
const lifetime = app ? app.wait() : server.wait();
|
|
443
|
+
// Observe startup failures already reported by the runtime before ready IPC.
|
|
444
|
+
await Promise.race([lifetime, Promise.resolve()]);
|
|
445
|
+
if (!stopping && workspaceReady) {
|
|
446
|
+
watcher = startRestartWatcher({
|
|
447
|
+
identity: releaseLock.identity,
|
|
448
|
+
shutdown: () => { stop("SIGTERM", new PipaRestartingError()); return finished.promise; },
|
|
449
|
+
onError: () => process.stderr.write("Pipa could not inspect restart requests.\n"),
|
|
450
|
+
});
|
|
451
|
+
await reportRestartReady(releaseLock.identity);
|
|
452
|
+
ready = true;
|
|
453
|
+
if (app && process.env.PIPA_RESTART_CHANNEL_ID) {
|
|
454
|
+
await app.postRestartReady({
|
|
455
|
+
channelId: process.env.PIPA_RESTART_CHANNEL_ID,
|
|
456
|
+
...(process.env.PIPA_RESTART_THREAD_TS ? { threadTs: process.env.PIPA_RESTART_THREAD_TS } : {}),
|
|
457
|
+
}).catch(() => process.stderr.write("Pipa could not post restart readiness to Slack.\n"));
|
|
458
|
+
}
|
|
392
459
|
}
|
|
460
|
+
await Promise.race([signal.promise, lifetime]);
|
|
461
|
+
} catch (error) {
|
|
462
|
+
failure = error;
|
|
393
463
|
} finally {
|
|
464
|
+
watcher?.stop();
|
|
394
465
|
try {
|
|
395
|
-
|
|
466
|
+
stop();
|
|
467
|
+
if (app) await app.shutdown();
|
|
468
|
+
if (server) await server.wait();
|
|
469
|
+
} catch (error) {
|
|
470
|
+
failure ??= error;
|
|
396
471
|
} finally {
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
472
|
+
try { await releaseLock(); } catch (error) { failure ??= error; }
|
|
473
|
+
if (failure) finished.reject(failure);
|
|
474
|
+
else finished.resolve();
|
|
475
|
+
// poll returns the in-flight handoff even after stop: don't exit before IPC.
|
|
476
|
+
await watcher?.poll().catch(() => { failure ??= new Error("Restart handoff failed."); });
|
|
477
|
+
process.off("SIGINT", stopWithSigint);
|
|
478
|
+
process.off("SIGTERM", stopWithSigterm);
|
|
479
|
+
process.off("disconnect", disconnected);
|
|
403
480
|
}
|
|
404
481
|
}
|
|
482
|
+
if (failure) throw failure;
|
|
405
483
|
}
|
|
406
484
|
|
|
407
|
-
main().catch((error) => {
|
|
485
|
+
main().catch(async (error) => {
|
|
486
|
+
await reportRestartFailure();
|
|
487
|
+
if (process.connected) process.disconnect();
|
|
408
488
|
const message = error instanceof Error ? error.message : String(error);
|
|
409
489
|
if (process.argv.includes("--json")) process.stdout.write(`${JSON.stringify({ ok: false, error: { code: error?.code ?? "routine_error", message } })}\n`);
|
|
410
490
|
else process.stderr.write(`Pipa failed: ${message}\n`);
|
package/package.json
CHANGED
package/src/app.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { Chat, Modal, TextInput } from "chat";
|
|
|
4
4
|
import { createSlackAdapter } from "@chat-adapter/slack";
|
|
5
5
|
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
6
6
|
import { canonicalWorkingDirectory, createManifest, createSessionStore, loadConfig, pipaPaths, saveConfig } from "./state.mjs";
|
|
7
|
-
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
7
|
+
import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaRestartingError, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
|
|
8
8
|
import { assertRoutineDestinationAllowed, createRoutineScheduler, loadRoutineState } from "./routines.mjs";
|
|
9
9
|
|
|
10
10
|
class RoutineDeniedError extends Error {}
|
|
@@ -19,6 +19,7 @@ export async function initializePipa(input, options = {}) {
|
|
|
19
19
|
workingDirectory: await canonicalWorkingDirectory(input.workingDirectory),
|
|
20
20
|
allowedSlackChannelIds: normalizeIdList(input.allowedSlackChannelIds),
|
|
21
21
|
allowedSlackUserIds: normalizeIdList(input.allowedSlackUserIds),
|
|
22
|
+
allowedSlackBotIds: normalizeIdList(input.allowedSlackBotIds),
|
|
22
23
|
};
|
|
23
24
|
const openCodeVersion = await (options.checkOpenCode ?? runOpenCodeVersion)();
|
|
24
25
|
if (!/^v?1(?:\.|$)/u.test(openCodeVersion)) throw new Error(`Pipa requires OpenCode v1; found ${openCodeVersion || "an unknown version"}.`);
|
|
@@ -31,11 +32,15 @@ export async function initializePipa(input, options = {}) {
|
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
export async function startPipa(options = {}) {
|
|
35
|
+
options.signal?.throwIfAborted();
|
|
34
36
|
const paths = options.paths ?? pipaPaths();
|
|
35
37
|
const config = options.config ?? await loadConfig(paths.config);
|
|
38
|
+
options.signal?.throwIfAborted();
|
|
36
39
|
const slackAuth = await (options.checkSlackToken ?? checkSlackToken)(config.slackBotToken);
|
|
40
|
+
options.signal?.throwIfAborted();
|
|
37
41
|
warnMissingSlackScopes(slackAuth, options.warn);
|
|
38
42
|
const sessionStore = options.sessionStore ?? await createSessionStore(paths.sessions);
|
|
43
|
+
options.signal?.throwIfAborted();
|
|
39
44
|
const state = options.state ?? createMemoryState();
|
|
40
45
|
const chat = options.chat ?? new Chat({
|
|
41
46
|
adapters: {
|
|
@@ -53,9 +58,11 @@ export async function startPipa(options = {}) {
|
|
|
53
58
|
});
|
|
54
59
|
const server = options.server ?? (options.executor ? null : await (options.startServer ?? startSocketOpenCodeServer)(config, {
|
|
55
60
|
startupTimeoutMs: options.startupTimeoutMs,
|
|
61
|
+
signal: options.signal,
|
|
56
62
|
}));
|
|
57
63
|
let executor;
|
|
58
64
|
try {
|
|
65
|
+
options.signal?.throwIfAborted();
|
|
59
66
|
executor = options.executor ?? (options.createExecutor ?? createOpenCodeExecutor)({
|
|
60
67
|
artifactRoot: path.join(config.workingDirectory, ".pipa", "artifacts"),
|
|
61
68
|
baseUrl: server.baseUrl,
|
|
@@ -164,7 +171,7 @@ export async function startPipa(options = {}) {
|
|
|
164
171
|
};
|
|
165
172
|
|
|
166
173
|
const handle = async (thread, message, subscribe) => {
|
|
167
|
-
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
|
|
174
|
+
if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message, config)) return;
|
|
168
175
|
const messageText = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
|
|
169
176
|
const missingLinks = (message.links ?? []).map((link) => link.url)
|
|
170
177
|
.filter((url) => typeof url === "string" && !messageText.split(/\s+/u).includes(url));
|
|
@@ -195,8 +202,10 @@ export async function startPipa(options = {}) {
|
|
|
195
202
|
onPermissionsReconciled: interactions.onPermissionsReconciled,
|
|
196
203
|
startTyping: () => thread.startTyping("Working on it..."),
|
|
197
204
|
deliver: (result, signal) => postResult(thread, result, signal),
|
|
198
|
-
deliverFailure: (error) => thread.post(error instanceof
|
|
199
|
-
? `${config.botName}
|
|
205
|
+
deliverFailure: (error) => thread.post(error instanceof PipaRestartingError
|
|
206
|
+
? `${config.botName} is restarting. I'll post here when it's ready.`
|
|
207
|
+
: error instanceof PipaStoppedError
|
|
208
|
+
? `${config.botName} was stopped. It won't respond until it starts again.`
|
|
200
209
|
: `${config.botName} failed: ${safeError(error)}`),
|
|
201
210
|
});
|
|
202
211
|
if (result.superseded) return;
|
|
@@ -209,14 +218,29 @@ export async function startPipa(options = {}) {
|
|
|
209
218
|
|
|
210
219
|
chat.onNewMention((thread, message) => { void handle(thread, message, true); });
|
|
211
220
|
chat.onSubscribedMessage((thread, message) => { void handle(thread, message, false); });
|
|
221
|
+
const stop = (reason = new PipaStoppedError()) => {
|
|
222
|
+
if (!accepting) return;
|
|
223
|
+
accepting = false;
|
|
224
|
+
routineScheduler?.stop(reason);
|
|
225
|
+
runner.close(reason);
|
|
226
|
+
executor.stopAll(reason);
|
|
227
|
+
};
|
|
228
|
+
const cancelled = () => stop();
|
|
229
|
+
options.signal?.addEventListener("abort", cancelled, { once: true });
|
|
212
230
|
try {
|
|
231
|
+
options.signal?.throwIfAborted();
|
|
213
232
|
await state.connect();
|
|
233
|
+
options.signal?.throwIfAborted();
|
|
214
234
|
for (const conversationKey of sessionStore.keys()) {
|
|
215
235
|
await chat.thread(conversationKey).subscribe();
|
|
236
|
+
options.signal?.throwIfAborted();
|
|
216
237
|
}
|
|
217
238
|
await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
|
|
239
|
+
options.signal?.throwIfAborted();
|
|
218
240
|
await routineScheduler?.start();
|
|
241
|
+
options.signal?.throwIfAborted();
|
|
219
242
|
} catch (error) {
|
|
243
|
+
options.signal?.removeEventListener("abort", cancelled);
|
|
220
244
|
routineScheduler?.stop(error);
|
|
221
245
|
await routineScheduler?.drain();
|
|
222
246
|
await withTimeout(interactions.close(), options.shutdownTimeoutMs ?? 15_000, "Interaction shutdown timed out.").catch(() => undefined);
|
|
@@ -227,14 +251,6 @@ export async function startPipa(options = {}) {
|
|
|
227
251
|
throw error;
|
|
228
252
|
}
|
|
229
253
|
|
|
230
|
-
const stop = (reason = new PipaStoppedError()) => {
|
|
231
|
-
if (!accepting) return;
|
|
232
|
-
accepting = false;
|
|
233
|
-
routineScheduler?.stop(reason);
|
|
234
|
-
runner.close(reason);
|
|
235
|
-
executor.stopAll(reason);
|
|
236
|
-
};
|
|
237
|
-
|
|
238
254
|
return {
|
|
239
255
|
server: server ? { baseUrl: server.baseUrl, owned: server.owned } : null,
|
|
240
256
|
async wait() {
|
|
@@ -245,8 +261,13 @@ export async function startPipa(options = {}) {
|
|
|
245
261
|
throw error;
|
|
246
262
|
}
|
|
247
263
|
},
|
|
248
|
-
stop
|
|
264
|
+
stop,
|
|
265
|
+
async postRestartReady(destination) {
|
|
266
|
+
assertRoutineDestinationAllowed(destination, config.allowedSlackChannelIds ?? []);
|
|
267
|
+
return chat.thread(slackDestinationId(destination)).post(`${config.botName} restarted and is ready.`);
|
|
268
|
+
},
|
|
249
269
|
async shutdown() {
|
|
270
|
+
options.signal?.removeEventListener("abort", cancelled);
|
|
250
271
|
stop();
|
|
251
272
|
try {
|
|
252
273
|
await withTimeout((async () => {
|
|
@@ -619,6 +640,7 @@ export function createConversationRunner({ sessionStore, runTurn, abortTurn = as
|
|
|
619
640
|
sessionId: current.sessionId,
|
|
620
641
|
onSession: async (sessionId) => {
|
|
621
642
|
current.sessionId = sessionId;
|
|
643
|
+
if (isLatest()) await sessionStore.set(conversationKey, sessionId);
|
|
622
644
|
await onSession?.(sessionId);
|
|
623
645
|
},
|
|
624
646
|
});
|
|
@@ -693,12 +715,13 @@ export async function checkSlackAppToken(token, fetchImpl = fetch) {
|
|
|
693
715
|
return result;
|
|
694
716
|
}
|
|
695
717
|
|
|
696
|
-
function shouldIgnore(thread, message) {
|
|
718
|
+
function shouldIgnore(thread, message, config) {
|
|
719
|
+
const allowedSubtypes = config.allowedSlackBotIds?.length ? ["file_share", "bot_message"] : ["file_share"];
|
|
697
720
|
return message.author?.isMe
|
|
698
|
-
|| message.author?.isBot
|
|
721
|
+
|| (message.author?.isBot && !config.allowedSlackBotIds?.length)
|
|
722
|
+
|| Boolean(message.raw?.subtype && !allowedSubtypes.includes(message.raw.subtype))
|
|
699
723
|
|| thread.channel?.isDM
|
|
700
724
|
|| thread.channel?.channelVisibility === "external"
|
|
701
|
-
|| Boolean(message.raw?.subtype && message.raw.subtype !== "file_share")
|
|
702
725
|
|| !message.text?.trim();
|
|
703
726
|
}
|
|
704
727
|
|
|
@@ -706,6 +729,7 @@ function isAuthorized(thread, message, config) {
|
|
|
706
729
|
const channelId = thread.id.split(":")[1];
|
|
707
730
|
const userId = message.author?.userId ?? message.author?.id;
|
|
708
731
|
if (config.allowedSlackChannelIds?.length && !config.allowedSlackChannelIds.includes(channelId)) return false;
|
|
732
|
+
if (message.author?.isBot) return config.allowedSlackBotIds?.includes(message.raw?.bot_id) ?? false;
|
|
709
733
|
if (config.allowedSlackUserIds?.length && !config.allowedSlackUserIds.includes(userId)) return false;
|
|
710
734
|
return true;
|
|
711
735
|
}
|
package/src/opencode.mjs
CHANGED
|
@@ -20,8 +20,13 @@ export class PipaStoppedError extends Error {
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
export class PipaRestartingError extends PipaStoppedError {}
|
|
24
|
+
|
|
23
25
|
export function cleanChildEnvironment(environment = process.env) {
|
|
24
|
-
return
|
|
26
|
+
return {
|
|
27
|
+
...Object.fromEntries(Object.entries(environment).filter(([key]) => !SLACK_SECRET_ENV_KEY.test(key))),
|
|
28
|
+
PIPA_HOME: path.resolve(environment.PIPA_HOME || os.homedir()),
|
|
29
|
+
};
|
|
25
30
|
}
|
|
26
31
|
|
|
27
32
|
export async function startSocketOpenCodeServer(config, options = {}) {
|
|
@@ -33,7 +38,7 @@ export async function startSocketOpenCodeServer(config, options = {}) {
|
|
|
33
38
|
|
|
34
39
|
if (attachUrl) {
|
|
35
40
|
const baseUrl = normalizeBaseUrl(attachUrl);
|
|
36
|
-
await waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs);
|
|
41
|
+
await waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs, options.signal);
|
|
37
42
|
return externalServer(baseUrl);
|
|
38
43
|
}
|
|
39
44
|
|
|
@@ -60,7 +65,7 @@ export async function startSocketOpenCodeServer(config, options = {}) {
|
|
|
60
65
|
child.stdout?.resume();
|
|
61
66
|
child.stderr?.resume();
|
|
62
67
|
await Promise.race([
|
|
63
|
-
waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs),
|
|
68
|
+
waitForWorkspace(baseUrl, config.workingDirectory, fetchImpl, headers, startupTimeoutMs, options.signal),
|
|
64
69
|
exit.then((code) => { throw new Error(`OpenCode server exited before startup with code ${code}.`); }),
|
|
65
70
|
]);
|
|
66
71
|
return ownedServer(baseUrl, child, exit, platform);
|
|
@@ -297,8 +302,20 @@ export function startOpenCodeServer(config, options = {}) {
|
|
|
297
302
|
const exit = waitForExit(child).then((code) => {
|
|
298
303
|
if (!stopping) throw new Error(`OpenCode server exited unexpectedly with code ${code}.`);
|
|
299
304
|
});
|
|
305
|
+
void exit.catch(() => undefined);
|
|
300
306
|
|
|
301
307
|
return {
|
|
308
|
+
async ready() {
|
|
309
|
+
const controller = new AbortController();
|
|
310
|
+
const hostname = config.openCodeHostname.includes(":") && !config.openCodeHostname.startsWith("[") ? `[${config.openCodeHostname}]` : config.openCodeHostname;
|
|
311
|
+
try {
|
|
312
|
+
await Promise.race([
|
|
313
|
+
waitForWorkspace(`http://${hostname}:${config.openCodePort}`, config.workingDirectory,
|
|
314
|
+
options.fetch ?? fetch, authenticationHeaders(options.environment ?? process.env), options.startupTimeoutMs ?? 30_000, controller.signal),
|
|
315
|
+
exit.then(() => { throw new Error("OpenCode stopped before workspace readiness."); }),
|
|
316
|
+
]);
|
|
317
|
+
} finally { controller.abort(); }
|
|
318
|
+
},
|
|
302
319
|
wait: () => exit,
|
|
303
320
|
stop(signal) {
|
|
304
321
|
if (stopping) return;
|
|
@@ -368,10 +385,14 @@ function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
|
|
|
368
385
|
const parts = [{ type: "text", text: prompt }, ...files.map((file) => ({ type: "file", ...file }))];
|
|
369
386
|
const context = Object.entries(contextEnvironment).filter(([, value]) => value !== undefined && value !== null && String(value));
|
|
370
387
|
const instructions = ["For scheduling requests, consult `pipa routine --help`, convert timezone wording to an IANA timezone, preview first, show the normalized details, and create only after user confirmation."];
|
|
388
|
+
const restartCommand = contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack" && contextEnvironment.PIPA_CURRENT_SLACK_CHANNEL_ID
|
|
389
|
+
? `pipa restart --channel ${contextEnvironment.PIPA_CURRENT_SLACK_CHANNEL_ID}${contextEnvironment.PIPA_CURRENT_SLACK_THREAD_TS ? ` --thread ${contextEnvironment.PIPA_CURRENT_SLACK_THREAD_TS}` : ""}`
|
|
390
|
+
: "pipa restart";
|
|
391
|
+
instructions.push(`When asked to restart Pipa, run \`${restartCommand}\`; existing messaging authorization is sufficient. It requests a detached restart and may end this turn. Use \`pipa restart --status\` to inspect the durable outcome; do not claim completion from the request alone. Both commands must run on the Pipa host, not a remote attached OpenCode host. If you lack command access to the Pipa host, explain that limitation instead of running them remotely. The Pipa profile home on that host is ${JSON.stringify(path.resolve(process.env.PIPA_HOME || os.homedir()))}; ensure PIPA_HOME has this value in the command environment. Do not use sequential stop/start or OpenCode /instance/dispose: that disposes an instance, not restarts the server.`);
|
|
371
392
|
if (context.length) instructions.push(`Slack context for this turn (provided here, not as shell environment variables):\n${context.map(([key, value]) => `${key}=${value}`).join("\n")}`);
|
|
372
393
|
if (contextEnvironment.PIPA_MESSAGE_CHANNEL === "slack") {
|
|
373
394
|
instructions.push("Keep naturally short answers inline. For deeper work or larger deliverables, keep the Slack response concise and use the most suitable artifact format.");
|
|
374
|
-
if (artifactDirectory) instructions.push(`To attach files, copy up to 10 top-level files (100 MB total) to this private artifact directory: ${artifactDirectory}\
|
|
395
|
+
if (artifactDirectory) instructions.push(`To attach files, copy up to 10 top-level files (100 MB total) to this private artifact directory: ${artifactDirectory}\nOnly if you created files, end your response with exactly one final line in this format: ${ARTIFACT_MARKER} [\"report.csv\",\"brief.pdf\"]\nDo not emit ${ARTIFACT_MARKER} otherwise.`);
|
|
375
396
|
}
|
|
376
397
|
return {
|
|
377
398
|
parts,
|
|
@@ -381,10 +402,16 @@ function promptBody(prompt, files, contextEnvironment, artifactDirectory) {
|
|
|
381
402
|
|
|
382
403
|
function parseArtifactDeclaration(text) {
|
|
383
404
|
const lines = text.split(/\r?\n/u);
|
|
384
|
-
const declarations = lines.map((line, index) =>
|
|
385
|
-
|
|
405
|
+
const declarations = lines.map((line, index) => {
|
|
406
|
+
const markerIndex = line.indexOf(ARTIFACT_MARKER);
|
|
407
|
+
return markerIndex < 0 ? null : { line: line.slice(markerIndex), index, markerIndex };
|
|
408
|
+
}).filter(Boolean);
|
|
409
|
+
const cleanText = lines.map((line) => {
|
|
410
|
+
const markerIndex = line.indexOf(ARTIFACT_MARKER);
|
|
411
|
+
return markerIndex < 0 ? line : line.slice(0, markerIndex).trimEnd();
|
|
412
|
+
}).join("\n").trim();
|
|
386
413
|
const lastNonblank = lines.findLastIndex((line) => line.trim());
|
|
387
|
-
if (declarations.length !== 1 || declarations[0].index !== lastNonblank) return { text: cleanText };
|
|
414
|
+
if (declarations.length !== 1 || declarations[0].index !== lastNonblank || declarations[0].markerIndex !== 0) return { text: cleanText };
|
|
388
415
|
const declaration = declarations[0].line;
|
|
389
416
|
if (!declaration.startsWith(`${ARTIFACT_MARKER} `) || Buffer.byteLength(declaration) > MAX_ARTIFACT_DECLARATION_BYTES) return { text: cleanText };
|
|
390
417
|
let paths;
|
|
@@ -519,13 +546,13 @@ function externalServer(baseUrl) {
|
|
|
519
546
|
};
|
|
520
547
|
}
|
|
521
548
|
|
|
522
|
-
async function waitForWorkspace(baseUrl, workingDirectory, fetchImpl, headers, timeoutMs) {
|
|
549
|
+
async function waitForWorkspace(baseUrl, workingDirectory, fetchImpl, headers, timeoutMs, signal) {
|
|
523
550
|
const deadline = Date.now() + timeoutMs;
|
|
524
551
|
while (Date.now() < deadline) {
|
|
525
552
|
try {
|
|
526
553
|
const status = await fetchImpl(serverUrl(baseUrl, "/session/status", workingDirectory), {
|
|
527
554
|
headers,
|
|
528
|
-
signal: AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))),
|
|
555
|
+
signal: AbortSignal.any([AbortSignal.timeout(Math.min(5_000, Math.max(1, deadline - Date.now()))), ...(signal ? [signal] : [])]),
|
|
529
556
|
});
|
|
530
557
|
const sessions = status.ok ? await status.json() : null;
|
|
531
558
|
if (sessions && typeof sessions === "object" && !Array.isArray(sessions)
|
|
@@ -533,7 +560,7 @@ async function waitForWorkspace(baseUrl, workingDirectory, fetchImpl, headers, t
|
|
|
533
560
|
} catch {
|
|
534
561
|
// OpenCode can accept its socket before the configured workspace is ready.
|
|
535
562
|
}
|
|
536
|
-
await delay(Math.min(250, Math.max(0, deadline - Date.now())));
|
|
563
|
+
await delay(Math.min(250, Math.max(0, deadline - Date.now())), signal);
|
|
537
564
|
}
|
|
538
565
|
throw new Error("OpenCode workspace readiness check timed out.");
|
|
539
566
|
}
|
package/src/restart.mjs
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { link, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
8
|
+
import { cleanChildEnvironment } from "./opencode.mjs";
|
|
9
|
+
import { isRunning, pipaPaths, readInstanceLock, writePrivateJson } from "./state.mjs";
|
|
10
|
+
|
|
11
|
+
const WORKER = fileURLToPath(import.meta.url);
|
|
12
|
+
const CLI = fileURLToPath(new URL("../bin/pipa.mjs", import.meta.url));
|
|
13
|
+
const LIMITS = { armMs: 10_000, cleanupMs: 30_000, stopMs: 15_000, readyMs: 60_000, pollMs: 100 };
|
|
14
|
+
const ACCEPT_MS = 15_000;
|
|
15
|
+
const SAFE_FAILURES = new Set([
|
|
16
|
+
"Child startup failed.", "Child process could not start.", "Child exited before handoff.",
|
|
17
|
+
"Restart IPC disconnected before handoff.", "Restart handoff timed out.",
|
|
18
|
+
"Restart IPC send timed out.", "Restart IPC send failed.", "Restart IPC unavailable.",
|
|
19
|
+
"Restart acceptance expired.", "Cleanup timed out.", "Cleanup failed.",
|
|
20
|
+
"Instance changed.", "Original instance did not stop.", "Replacement identity not confirmed.",
|
|
21
|
+
]);
|
|
22
|
+
const safeFailure = (error) => SAFE_FAILURES.has(error?.message) ? ` ${error.message}` : "";
|
|
23
|
+
const validId = (id) => typeof id === "string" && /^[a-f0-9-]{36}$/u.test(id);
|
|
24
|
+
const same = (a, b) => a && b && a.pid === b.pid && a.generation === b.generation;
|
|
25
|
+
const homePath = (home) => path.resolve(home ?? (process.env.PIPA_HOME || os.homedir()));
|
|
26
|
+
const fileFor = (home, id, kind) => {
|
|
27
|
+
if (!validId(id)) throw new Error("Invalid restart identity.");
|
|
28
|
+
return path.join(pipaPaths(home).directory, "restarts", `${id}.${kind}.json`);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
async function readOptional(file) {
|
|
32
|
+
try { return JSON.parse(await readFile(file, "utf8")); }
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error?.code === "ENOENT") return null;
|
|
35
|
+
throw new Error("Could not read restart state.");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function publish(file, value) {
|
|
40
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
41
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
42
|
+
try {
|
|
43
|
+
await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });
|
|
44
|
+
await link(temporary, file);
|
|
45
|
+
return true;
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (error?.code === "EEXIST") return false;
|
|
48
|
+
throw error;
|
|
49
|
+
} finally { await rm(temporary, { force: true }); }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function validRequest(request, identity) {
|
|
53
|
+
return request && validId(request.id) && request.id === request.generation
|
|
54
|
+
&& same(request, identity) && Number.isFinite(request.createdAt)
|
|
55
|
+
&& request.expiresAt === request.createdAt + ACCEPT_MS
|
|
56
|
+
&& (!request.destination || (typeof request.destination.channelId === "string"
|
|
57
|
+
&& /^[A-Z][A-Z0-9]+$/u.test(request.destination.channelId)
|
|
58
|
+
&& (request.destination.threadTs === undefined || /^\d+\.\d+$/u.test(request.destination.threadTs))));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Generation is identity, not a grant: local execution keeps the existing local-user authority.
|
|
62
|
+
export async function requestRestart({ home, running = isRunning, now = Date.now, destination } = {}) {
|
|
63
|
+
home = homePath(home);
|
|
64
|
+
const identity = await readInstanceLock(pipaPaths(home).lock);
|
|
65
|
+
if (!identity || !running(identity.pid)) throw new Error("Pipa is not running.");
|
|
66
|
+
if (!identity.generation) throw new Error("This Pipa needs one manual stop/start before restart is available.");
|
|
67
|
+
const createdAt = now();
|
|
68
|
+
if (destination && (!/^[A-Z][A-Z0-9]+$/u.test(destination.channelId ?? "")
|
|
69
|
+
|| (destination.threadTs !== undefined && !/^\d+\.\d+$/u.test(destination.threadTs)))) {
|
|
70
|
+
throw new Error("Invalid restart destination.");
|
|
71
|
+
}
|
|
72
|
+
const request = { ...identity, id: identity.generation, createdAt, expiresAt: createdAt + ACCEPT_MS, ...(destination ? { destination } : {}) };
|
|
73
|
+
const file = fileFor(home, request.id, "request");
|
|
74
|
+
const created = await publish(file, request);
|
|
75
|
+
const stored = await readOptional(file);
|
|
76
|
+
if (!validRequest(stored, identity)) throw new Error("Invalid restart request.");
|
|
77
|
+
if (!created) {
|
|
78
|
+
const status = await restartStatus({ home, id: stored.id, now });
|
|
79
|
+
if (!["requested", "running"].includes(status?.state)) {
|
|
80
|
+
throw new Error(`Restart ${stored.id} is ${status?.state ?? "unconfirmed"}. Inspect \`pipa restart --status\` before a manual stop/start.`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return stored;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Read-only: expiry changes the displayed outcome, never the persisted records.
|
|
87
|
+
export async function restartStatus({ home, id, now = Date.now } = {}) {
|
|
88
|
+
home = homePath(home);
|
|
89
|
+
if (!id) {
|
|
90
|
+
const directory = path.join(pipaPaths(home).directory, "restarts");
|
|
91
|
+
const files = await readdir(directory).catch((error) => {
|
|
92
|
+
if (error.code === "ENOENT") return [];
|
|
93
|
+
throw error;
|
|
94
|
+
});
|
|
95
|
+
const requests = await Promise.all(files.filter((file) => /^[a-f0-9-]{36}\.request\.json$/u.test(file))
|
|
96
|
+
.map((file) => readOptional(path.join(directory, file))));
|
|
97
|
+
id = requests.filter(Boolean).sort((a, b) => b.createdAt - a.createdAt)[0]?.id;
|
|
98
|
+
if (!id) return null;
|
|
99
|
+
}
|
|
100
|
+
const request = await readOptional(fileFor(home, id, "request"));
|
|
101
|
+
if (!request) return null;
|
|
102
|
+
const status = await readOptional(fileFor(home, id, "status"))
|
|
103
|
+
?? await readOptional(fileFor(home, id, "acceptance"))
|
|
104
|
+
?? { id, state: "requested", phase: "acceptance", updatedAt: request.createdAt, deadline: request.expiresAt };
|
|
105
|
+
if (!["completed", "failed"].includes(status.state) && now() > status.deadline) {
|
|
106
|
+
return { ...status, state: "unconfirmed", error: `Restart ${status.phase} was not confirmed before its deadline. Inspect Pipa before trying a manual start.` };
|
|
107
|
+
}
|
|
108
|
+
return status;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function statusRecord(id, state, phase, deadline, error) {
|
|
112
|
+
return { id, state, phase, updatedAt: Date.now(), deadline, ...(error ? { error } : {}) };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function detach(child) {
|
|
116
|
+
if (child?.connected) child.disconnect();
|
|
117
|
+
child?.unref();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// One bounded listener handles spawn errors, early exits, disconnects and expected IPC.
|
|
121
|
+
function receive(peer, type, id, timeoutMs) {
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
const finish = (error, message) => {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
peer.off("message", messageReceived);
|
|
126
|
+
peer.off("exit", exited);
|
|
127
|
+
peer.off("disconnect", disconnected);
|
|
128
|
+
// Keep a harmless error listener for a delayed spawn error after timeout.
|
|
129
|
+
peer.off("error", failed);
|
|
130
|
+
peer.on("error", ignoreError);
|
|
131
|
+
if (error) reject(error);
|
|
132
|
+
else resolve(message);
|
|
133
|
+
};
|
|
134
|
+
const messageReceived = (message) => {
|
|
135
|
+
if (message?.id !== id) return;
|
|
136
|
+
if (message.type === "failed") finish(new Error("Child startup failed."));
|
|
137
|
+
else if (message.type === type) finish(null, message);
|
|
138
|
+
};
|
|
139
|
+
const failed = () => finish(new Error("Child process could not start."));
|
|
140
|
+
const exited = () => finish(new Error("Child exited before handoff."));
|
|
141
|
+
const disconnected = () => finish(new Error("Restart IPC disconnected before handoff."));
|
|
142
|
+
const timer = setTimeout(() => finish(new Error("Restart handoff timed out.")), timeoutMs);
|
|
143
|
+
peer.on("message", messageReceived);
|
|
144
|
+
peer.once("error", failed);
|
|
145
|
+
peer.once("exit", exited);
|
|
146
|
+
peer.once("disconnect", disconnected);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function ignoreError() {}
|
|
150
|
+
|
|
151
|
+
function send(peer, message, timeoutMs) {
|
|
152
|
+
return new Promise((resolve, reject) => {
|
|
153
|
+
const timer = setTimeout(() => reject(new Error("Restart IPC send timed out.")), timeoutMs);
|
|
154
|
+
try {
|
|
155
|
+
peer.send(message, (error) => {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
if (error) reject(new Error("Restart IPC send failed."));
|
|
158
|
+
else resolve();
|
|
159
|
+
});
|
|
160
|
+
} catch {
|
|
161
|
+
clearTimeout(timer);
|
|
162
|
+
reject(new Error("Restart IPC unavailable."));
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function spawnOptions(home, environment) {
|
|
168
|
+
const env = cleanChildEnvironment(environment);
|
|
169
|
+
delete env.PIPA_RESTART_ID;
|
|
170
|
+
delete env.PIPA_RESTART_CHANNEL_ID;
|
|
171
|
+
delete env.PIPA_RESTART_THREAD_TS;
|
|
172
|
+
return { detached: true, shell: false, stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
173
|
+
env: { ...env, PIPA_HOME: home }, windowsHide: true };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Call only inside the lock-owning Pipa process, never the requesting OpenCode turn.
|
|
177
|
+
// shutdown must stop intake, await cleanup AND release its own lock, then resolve.
|
|
178
|
+
export function startRestartWatcher({ home, identity, shutdown, spawn: spawnImpl = spawn,
|
|
179
|
+
environment = process.env, limits = {}, onError = () => {} }) {
|
|
180
|
+
home = homePath(home);
|
|
181
|
+
const timing = { ...LIMITS, ...limits };
|
|
182
|
+
let pending;
|
|
183
|
+
let stopped = false;
|
|
184
|
+
let accepted = false;
|
|
185
|
+
const poll = () => {
|
|
186
|
+
if (pending) return pending;
|
|
187
|
+
if (stopped || accepted) return Promise.resolve();
|
|
188
|
+
pending = accept().finally(() => { pending = null; });
|
|
189
|
+
return pending;
|
|
190
|
+
};
|
|
191
|
+
async function accept() {
|
|
192
|
+
const request = await readOptional(fileFor(home, identity.generation, "request"));
|
|
193
|
+
if (stopped || !validRequest(request, identity) || Date.now() > request.expiresAt
|
|
194
|
+
|| !same(await readInstanceLock(pipaPaths(home).lock), identity)) return;
|
|
195
|
+
const file = fileFor(home, request.id, "acceptance");
|
|
196
|
+
if (!await publish(file, statusRecord(request.id, "requested", "arming", Date.now() + timing.armMs))) return;
|
|
197
|
+
accepted = true;
|
|
198
|
+
let child;
|
|
199
|
+
let phase = "arming";
|
|
200
|
+
try {
|
|
201
|
+
child = spawnImpl(process.execPath, [WORKER, "--worker", request.id], spawnOptions(home, environment));
|
|
202
|
+
await receive(child, "armed", request.id, timing.armMs);
|
|
203
|
+
if (stopped || !child.connected || child.exitCode != null || child.signalCode != null
|
|
204
|
+
|| Date.now() > request.expiresAt || !same(await readInstanceLock(pipaPaths(home).lock), identity)) {
|
|
205
|
+
throw new Error("Restart acceptance expired.");
|
|
206
|
+
}
|
|
207
|
+
await writePrivateJson(file, statusRecord(request.id, "running", "cleanup", Date.now() + timing.cleanupMs));
|
|
208
|
+
phase = "cleanup";
|
|
209
|
+
let timer;
|
|
210
|
+
try {
|
|
211
|
+
await Promise.race([Promise.resolve().then(shutdown), new Promise((_, reject) => {
|
|
212
|
+
timer = setTimeout(() => reject(new Error("Cleanup timed out.")), timing.cleanupMs);
|
|
213
|
+
})]);
|
|
214
|
+
} finally { clearTimeout(timer); }
|
|
215
|
+
phase = "handoff";
|
|
216
|
+
await send(child, { type: "cleanup", id: request.id, ok: true }, timing.armMs);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
await writePrivateJson(file, statusRecord(request.id, "failed", phase, Date.now(),
|
|
219
|
+
`Restart ${phase} failed.${safeFailure(error)} Inspect Pipa and its owned runtime before a manual stop/start.`));
|
|
220
|
+
} finally { detach(child); }
|
|
221
|
+
}
|
|
222
|
+
const timer = setInterval(() => { void poll().catch(onError); }, timing.pollMs);
|
|
223
|
+
timer.unref();
|
|
224
|
+
return { poll, stop() { stopped = true; clearInterval(timer); } };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export async function runRestartWorker({ home, id, peer = process, spawn: spawnImpl = spawn,
|
|
228
|
+
environment = process.env, running = isRunning, limits = {} }) {
|
|
229
|
+
home = homePath(home);
|
|
230
|
+
const timing = { ...LIMITS, ...limits };
|
|
231
|
+
const request = await readOptional(fileFor(home, id, "request"));
|
|
232
|
+
if (!validRequest(request, await readInstanceLock(pipaPaths(home).lock)) || Date.now() > request.expiresAt) return;
|
|
233
|
+
let child;
|
|
234
|
+
let phase = "cleanup";
|
|
235
|
+
let ownsStatus = false;
|
|
236
|
+
const file = fileFor(home, id, "status");
|
|
237
|
+
try {
|
|
238
|
+
const cleanup = receive(peer, "cleanup", id, timing.cleanupMs + timing.armMs);
|
|
239
|
+
// Attach a rejection handler before the asynchronous send can fail.
|
|
240
|
+
void cleanup.catch(ignoreError);
|
|
241
|
+
await send(peer, { type: "armed", id }, timing.armMs);
|
|
242
|
+
const outcome = await cleanup;
|
|
243
|
+
if (outcome.ok !== true) throw new Error("Cleanup failed.");
|
|
244
|
+
const acceptance = await readOptional(fileFor(home, id, "acceptance"));
|
|
245
|
+
if (acceptance?.state !== "running" || Date.now() > acceptance.deadline) return;
|
|
246
|
+
// Parent writes only acceptance; this worker alone writes progress after cleanup handoff.
|
|
247
|
+
ownsStatus = true;
|
|
248
|
+
phase = "waiting-for-stop";
|
|
249
|
+
await writePrivateJson(file, statusRecord(id, "running", phase, Date.now() + timing.stopMs));
|
|
250
|
+
if (peer.connected) peer.disconnect();
|
|
251
|
+
const deadline = Date.now() + timing.stopMs;
|
|
252
|
+
while (true) {
|
|
253
|
+
const lock = await readInstanceLock(pipaPaths(home).lock);
|
|
254
|
+
if (lock && !same(lock, request)) throw new Error("Instance changed.");
|
|
255
|
+
if (!lock && !running(request.pid)) break;
|
|
256
|
+
if (Date.now() >= deadline) throw new Error("Original instance did not stop.");
|
|
257
|
+
await delay(timing.pollMs);
|
|
258
|
+
}
|
|
259
|
+
phase = "starting";
|
|
260
|
+
await writePrivateJson(file, statusRecord(id, "running", phase, Date.now() + timing.readyMs));
|
|
261
|
+
const options = spawnOptions(home, environment);
|
|
262
|
+
options.env.PIPA_RESTART_ID = id;
|
|
263
|
+
if (request.destination) {
|
|
264
|
+
options.env.PIPA_RESTART_CHANNEL_ID = request.destination.channelId;
|
|
265
|
+
options.env.PIPA_RESTART_THREAD_TS = request.destination.threadTs ?? "";
|
|
266
|
+
}
|
|
267
|
+
child = spawnImpl(process.execPath, [CLI, "start"], options);
|
|
268
|
+
const ready = await receive(child, "ready", id, timing.readyMs);
|
|
269
|
+
const replacement = await readInstanceLock(pipaPaths(home).lock);
|
|
270
|
+
if (ready.pid !== child.pid || !validId(ready.generation) || ready.generation === request.generation
|
|
271
|
+
|| !same(ready, replacement) || !running(ready.pid) || child.exitCode != null || child.signalCode != null) {
|
|
272
|
+
throw new Error("Replacement identity not confirmed.");
|
|
273
|
+
}
|
|
274
|
+
await send(child, { type: "accepted", id }, timing.armMs);
|
|
275
|
+
await writePrivateJson(file, { ...statusRecord(id, "completed", "ready", Date.now()), replacement });
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (ownsStatus) await writePrivateJson(file, statusRecord(id, "failed", phase, Date.now(),
|
|
278
|
+
`Restart ${phase} failed.${safeFailure(error)} Inspect Pipa before a manual start; a replacement may still be starting.`));
|
|
279
|
+
} finally {
|
|
280
|
+
detach(child);
|
|
281
|
+
if (peer.connected) peer.disconnect();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Report readiness only after full profile startup; wait for worker acceptance.
|
|
286
|
+
export async function reportRestartReady(identity, { peer = process, environment = process.env } = {}) {
|
|
287
|
+
const id = environment.PIPA_RESTART_ID;
|
|
288
|
+
if (!id) return;
|
|
289
|
+
if (!validId(id) || !validId(identity?.generation)) throw new Error("Invalid restart readiness identity.");
|
|
290
|
+
const accepted = receive(peer, "accepted", id, LIMITS.armMs);
|
|
291
|
+
void accepted.catch(ignoreError);
|
|
292
|
+
await send(peer, { type: "ready", id, ...identity }, LIMITS.armMs);
|
|
293
|
+
await accepted;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export async function reportRestartFailure({ peer = process, environment = process.env } = {}) {
|
|
297
|
+
const id = environment.PIPA_RESTART_ID;
|
|
298
|
+
if (validId(id) && peer.connected) await send(peer, { type: "failed", id }, LIMITS.armMs).catch(ignoreError);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === WORKER && process.argv[2] === "--worker") {
|
|
302
|
+
await runRestartWorker({ id: process.argv[3] }).catch(() => { process.exitCode = 1; });
|
|
303
|
+
if (process.connected) process.disconnect();
|
|
304
|
+
}
|
package/src/state.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { constants } from "node:fs";
|
|
1
|
+
import { constants, readFileSync, unlinkSync } from "node:fs";
|
|
2
2
|
import { access, chmod, link, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
@@ -64,34 +64,67 @@ export function pipaPaths(home = process.env.PIPA_HOME || os.homedir()) {
|
|
|
64
64
|
export async function acquireInstanceLock(file = pipaPaths().lock) {
|
|
65
65
|
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
66
66
|
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
67
|
-
|
|
67
|
+
const identity = Object.freeze({ pid: process.pid, generation: randomUUID() });
|
|
68
|
+
await writeFile(temporary, JSON.stringify(identity), { mode: 0o600 });
|
|
68
69
|
try {
|
|
69
70
|
await claimLock(temporary, file);
|
|
70
71
|
} catch (error) {
|
|
71
72
|
if (error?.code !== "EEXIST") throw error;
|
|
72
|
-
const
|
|
73
|
-
if (
|
|
74
|
-
|
|
73
|
+
const previous = await readInstanceLock(file);
|
|
74
|
+
if (previous && isRunning(previous.pid)) throw new Error(`Pipa is already running (PID ${previous.pid}).`);
|
|
75
|
+
removeInstanceLock(file, previous);
|
|
75
76
|
await claimLock(temporary, file);
|
|
76
77
|
} finally {
|
|
77
78
|
await rm(temporary, { force: true });
|
|
78
79
|
}
|
|
79
|
-
|
|
80
|
+
const release = async () => removeInstanceLock(file, identity);
|
|
81
|
+
release.identity = identity;
|
|
82
|
+
return release;
|
|
80
83
|
}
|
|
81
84
|
|
|
82
85
|
export async function stopInstance(file = pipaPaths().lock, kill = process.kill) {
|
|
83
|
-
const
|
|
86
|
+
const identity = await readInstanceLock(file);
|
|
87
|
+
const pid = identity?.pid;
|
|
84
88
|
if (!pid) return null;
|
|
85
89
|
try {
|
|
86
90
|
kill(pid, "SIGTERM");
|
|
87
91
|
return pid;
|
|
88
92
|
} catch (error) {
|
|
89
|
-
if (error?.code === "ESRCH")
|
|
93
|
+
if (error?.code === "ESRCH") removeInstanceLock(file, identity);
|
|
90
94
|
else throw error;
|
|
91
95
|
return null;
|
|
92
96
|
}
|
|
93
97
|
}
|
|
94
98
|
|
|
99
|
+
export async function readInstanceLock(file = pipaPaths().lock) {
|
|
100
|
+
try {
|
|
101
|
+
return parseInstanceLock(await readFile(file, "utf8"));
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (error?.code === "ENOENT") return null;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function parseInstanceLock(text) {
|
|
109
|
+
const value = JSON.parse(text);
|
|
110
|
+
const identity = typeof value === "number" ? { pid: value, generation: null } : value;
|
|
111
|
+
if (!Number.isSafeInteger(identity?.pid) || identity.pid <= 0
|
|
112
|
+
|| (identity.generation !== null && !/^[a-f0-9-]{36}$/u.test(identity.generation ?? ""))) {
|
|
113
|
+
throw new Error("Invalid Pipa instance lock.");
|
|
114
|
+
}
|
|
115
|
+
return identity;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function removeInstanceLock(file, identity) {
|
|
119
|
+
try {
|
|
120
|
+
// No await between checking ownership and unlinking; repeated old releases are harmless.
|
|
121
|
+
const current = parseInstanceLock(readFileSync(file, "utf8"));
|
|
122
|
+
if (current.pid === identity?.pid && current.generation === identity?.generation) unlinkSync(file);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error?.code !== "ENOENT") throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
95
128
|
export function createManifest(botName) {
|
|
96
129
|
const name = validateBotName(botName);
|
|
97
130
|
const manifest = structuredClone(MANIFEST);
|
|
@@ -130,7 +163,7 @@ export async function loadConfig(file = pipaPaths().config) {
|
|
|
130
163
|
if (slackMode === "managed" && (!Number.isInteger(config.openCodePort) || config.openCodePort < 1 || config.openCodePort > 65535)) {
|
|
131
164
|
throw new Error("Invalid Pipa config: openCodePort must be an integer from 1 to 65535.");
|
|
132
165
|
}
|
|
133
|
-
for (const key of ["allowedSlackChannelIds", "allowedSlackUserIds"]) {
|
|
166
|
+
for (const key of ["allowedSlackChannelIds", "allowedSlackUserIds", "allowedSlackBotIds"]) {
|
|
134
167
|
const value = config[key];
|
|
135
168
|
if (value !== undefined && (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim()))) {
|
|
136
169
|
throw new Error(`Invalid Pipa config: ${key} must be a list of non-empty Slack IDs.`);
|
|
@@ -203,7 +236,7 @@ function validateBotName(value) {
|
|
|
203
236
|
return name;
|
|
204
237
|
}
|
|
205
238
|
|
|
206
|
-
function isRunning(pid) {
|
|
239
|
+
export function isRunning(pid) {
|
|
207
240
|
try {
|
|
208
241
|
process.kill(pid, 0);
|
|
209
242
|
return true;
|