@usepipa/pipa 0.4.3 → 0.5.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 CHANGED
@@ -77,11 +77,52 @@ export PIPA_OPENCODE_ATTACH_URL=http://localhost:5555
77
77
  pipa start
78
78
  ```
79
79
 
80
+ ### Routines
81
+
82
+ Local Pipa can save timezone-aware work that runs through the same OpenCode agent and delivers to one exact Slack channel or existing thread. Replies to a routine result continue the OpenCode session that produced it. Routines use the configured working directory, tools, permissions, channel allowlist, and responder allowlist.
83
+
84
+ Preview agent-assisted changes first, inspect the normalized JSON, then create only after confirmation:
85
+
86
+ ```sh
87
+ pipa routine create \
88
+ --prompt "Send the daily brief" \
89
+ --timezone America/New_York \
90
+ --channel C0BSE2JTYPR \
91
+ --every 1d \
92
+ --times 05:00 \
93
+ --preview \
94
+ --json
95
+ ```
96
+
97
+ Remove `--preview` to save the routine. Use `--prompt-file` when exact multiline text or shell-like characters must be preserved. Timezones must be IANA names such as `America/New_York` or `UTC`; aliases such as `EST` are not accepted.
98
+
99
+ Supported schedules:
100
+
101
+ ```sh
102
+ # Every 30 minutes
103
+ pipa routine create --prompt "Check the queue" --timezone UTC --channel C0BSE2JTYPR --every 30m
104
+
105
+ # Once, five minutes from the CLI clock
106
+ pipa routine create --prompt "Follow up" --timezone UTC --channel C0BSE2JTYPR --in 5m
107
+
108
+ # Tuesday, Thursday, and Saturday at three local times
109
+ pipa routine create --prompt "Post status" --timezone America/New_York --channel C0BSE2JTYPR --every 1w --weekdays 2,4,6 --times 09:00,15:00,18:00
110
+
111
+ # Daily through the inclusive local date September 5
112
+ pipa routine create --prompt "Evening close" --timezone America/New_York --channel C0BSE2JTYPR --every 1d --times 19:00 --until 2030-09-05
113
+ ```
114
+
115
+ Use `pipa routine list`, `show`, `edit`, `run`, and `delete` for the lifecycle. Deactivate or reactivate with `edit --status inactive|active`. Completed one-time and final recurring routines remain inspectable until deleted. `routine run` requests one execution without changing the saved schedule or status.
116
+
117
+ 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
+
80
119
  ## Commands
81
120
 
82
121
  ```text
83
122
  pipa init Configure Slack and the local working directory
84
123
  pipa start Start the configured Slack runtime
124
+ pipa stop Stop the running local Pipa process
125
+ pipa routine Create and manage local scheduled routines
85
126
  pipa --version Print the installed version
86
127
  ```
87
128
 
@@ -93,6 +134,8 @@ npm test
93
134
  npm run test:pack
94
135
  ```
95
136
 
137
+ `npm run test:slack:routines` is a manual real-service smoke test. It requires a running local Socket Mode process plus `SLACK_USER_TOKEN`, `SLACK_TEST_CHANNEL_ID`, and `SLACK_PIPA_BOT_USER_ID`; it is not part of automatic CI.
138
+
96
139
  See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
97
140
 
98
141
  See the [repository overview](docs/repository-overview.md) for a file-by-file explanation of how Pipa works.
package/bin/pipa.mjs CHANGED
@@ -1,13 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import crossSpawn from "cross-spawn";
4
- import { readFile } from "node:fs/promises";
4
+ import { constants } from "node:fs";
5
+ import { lstat, open, readFile, realpath } from "node:fs/promises";
6
+ import { randomUUID } from "node:crypto";
7
+ import path from "node:path";
5
8
  import { createInterface } from "node:readline/promises";
6
9
  import { Writable } from "node:stream";
7
10
  import { stdin, stdout } from "node:process";
8
11
  import { acquireInstanceLock, createManifest, createManifestUrl, loadConfig, stopInstance } from "../src/state.mjs";
9
12
  import { initializePipa, startPipa } from "../src/app.mjs";
10
13
  import { startOpenCodeServer } from "../src/opencode.mjs";
14
+ import { createRoutine, deleteRoutine, editRoutine, loadRoutineState, requestRoutineRun } from "../src/routines.mjs";
11
15
 
12
16
  const packageJson = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
13
17
 
@@ -20,7 +24,252 @@ async function main(argv = process.argv.slice(2), io = { input: stdin, output: s
20
24
  if (command === "init") return init(io);
21
25
  if (command === "start") return start(io);
22
26
  if (command === "stop") return stop(io);
23
- throw new Error("Usage: pipa init | pipa start | pipa stop | pipa --version");
27
+ if (command === "routine") return routine(argv.slice(1), io);
28
+ throw new Error("Usage: pipa init | pipa start | pipa stop | pipa routine | pipa --version");
29
+ }
30
+
31
+ const ROUTINE_HELP = `Usage: pipa routine <command>
32
+
33
+ Commands:
34
+ create (--prompt <text> | --prompt-file <path>) --timezone <iana> --channel <id> [--thread <ts>] <schedule> [--preview] [--json]
35
+ list [--json]
36
+ show <id> [--json]
37
+ edit <id> [--prompt <text> | --prompt-file <path>] [--timezone <iana>] [--channel <id>] [--thread <ts|none>] [<schedule>] [--status active|inactive] [--json]
38
+ run <id> [--json]
39
+ delete <id> [--json]
40
+
41
+ Schedules: --at <iso> | --in <positive><m|h|d|w> | --every <positive><m|h|d|w>
42
+ Recurring options: --times <HH:MM,...> --weekdays <1,...,7> --until <YYYY-MM-DD>
43
+
44
+ Timezone must be an IANA name such as America/New_York or UTC. Pipa does not
45
+ interpret aliases such as EST. --until is an inclusive local date. Use
46
+ --prompt-file for exact multiline prompts or prompts containing shell syntax.
47
+
48
+ Examples:
49
+ pipa routine create --prompt "Daily brief" --timezone America/New_York --channel C123 --every 1d --times 05:00 --preview --json
50
+ pipa routine create --prompt "Check queue" --timezone UTC --channel C123 --every 30m --preview --json
51
+ pipa routine create --prompt "Follow up" --timezone UTC --channel C123 --in 5m --preview --json
52
+ pipa routine create --prompt "Status" --timezone America/New_York --channel C123 --every 1w --weekdays 2,4,6 --times 09:00,15:00,18:00 --preview --json
53
+ pipa routine create --prompt "Evening close" --timezone America/New_York --channel C123 --every 1d --times 19:00 --until 2030-09-05 --preview --json
54
+
55
+ --preview validates and normalizes without writing routines.json. Agents should
56
+ preview, show the normalized JSON, and create only after user confirmation.
57
+ JSON success output includes ok plus routine, routines, or deleted. JSON errors
58
+ include ok:false and a stable error object.
59
+
60
+ Routines use normal local OpenCode authority and run only while the Socket Mode
61
+ pipa start process is running and this machine is awake. Restart skips missed
62
+ scheduled work; an explicit run request remains pending and can repeat if the
63
+ process crashes after external side effects but before saving completion.
64
+ Completed routines remain visible until deleted. run never changes the saved
65
+ schedule or lifecycle status. Managed profiles do not execute routines.
66
+ `;
67
+
68
+ async function routine(argv, io) {
69
+ const command = argv[0];
70
+ if (!command || command === "--help" || command === "-h") {
71
+ io.output.write(ROUTINE_HELP);
72
+ return;
73
+ }
74
+ const { values, positionals } = parseRoutineArgs(argv.slice(1));
75
+ const json = values.json === true;
76
+
77
+ if (command === "list") {
78
+ requireNoOptions(values, ["json"]);
79
+ if (positionals.length) cliError("list does not accept an ID");
80
+ const routines = (await loadRoutineState()).routines;
81
+ return writeRoutineResult(io.output, json, { routines }, routines.length
82
+ ? routines.map((item) => `${item.id}\t${item.status}\t${item.nextRunAt ?? "-"}`).join("\n")
83
+ : "No routines.");
84
+ }
85
+ if (command === "show") {
86
+ requireNoOptions(values, ["json"]);
87
+ const id = requireId(positionals);
88
+ const found = (await loadRoutineState()).routines.find((item) => item.id === id);
89
+ if (!found) cliError(`Routine not found: ${id}`, "not_found");
90
+ return writeRoutineResult(io.output, json, { routine: found }, formatRoutine(found));
91
+ }
92
+ if (command === "run") {
93
+ requireNoOptions(values, ["json"]);
94
+ const id = requireId(positionals);
95
+ const requested = await requestRoutineRun(id);
96
+ return writeRoutineResult(io.output, json, { routine: requested }, `Run requested for ${id}.`);
97
+ }
98
+ if (command === "delete") {
99
+ requireNoOptions(values, ["json"]);
100
+ const id = requireId(positionals);
101
+ await deleteRoutine(id);
102
+ return writeRoutineResult(io.output, json, { deleted: id }, `Deleted routine ${id}.`);
103
+ }
104
+ if (command !== "create" && command !== "edit") cliError(`Unknown routine command: ${command}`);
105
+
106
+ const id = command === "edit" ? requireId(positionals) : positionals.length === 0 ? randomUUID() : cliError("create does not accept an ID");
107
+ const config = await loadConfig();
108
+ const now = new Date().toISOString();
109
+ const changes = await routineInput(values, command === "create", now, config.workingDirectory);
110
+ const options = { now, allowedChannelIds: config.allowedSlackChannelIds ?? [] };
111
+ const result = command === "create"
112
+ ? await createRoutine({ id, ...changes }, { ...options, preview: values.preview === true })
113
+ : await editRoutine(id, changes, options);
114
+ const preview = command === "create" && values.preview === true;
115
+ return writeRoutineResult(io.output, json, { routine: result, ...(preview ? { preview: true } : {}) }, preview
116
+ ? `Preview: ${formatRoutine(result)}`
117
+ : `${command === "create" ? "Created" : "Edited"} routine ${id}.`);
118
+ }
119
+
120
+ function parseRoutineArgs(argv) {
121
+ const booleanOptions = new Set(["json", "preview"]);
122
+ const values = {};
123
+ const positionals = [];
124
+ for (let index = 0; index < argv.length; index += 1) {
125
+ const argument = argv[index];
126
+ if (!argument.startsWith("--")) {
127
+ positionals.push(argument);
128
+ continue;
129
+ }
130
+ const name = argument.slice(2);
131
+ if (!name) cliError("invalid option");
132
+ if (Object.hasOwn(values, name)) cliError(`option --${name} may only be used once`);
133
+ if (booleanOptions.has(name)) values[name] = true;
134
+ else {
135
+ if (index + 1 >= argv.length) cliError(`option --${name} requires a value`);
136
+ values[name] = argv[index += 1];
137
+ }
138
+ }
139
+ return { values, positionals };
140
+ }
141
+
142
+ async function routineInput(values, creating, now, workingDirectory) {
143
+ const supported = ["prompt", "prompt-file", "timezone", "channel", "thread", "at", "in", "every", "times", "weekdays", "until", "status", "preview", "json"];
144
+ requireNoOptions(values, supported);
145
+ if (!creating && values.preview) cliError("--preview is only supported by create");
146
+ if (creating && values.status !== undefined) cliError("--status is only supported by edit");
147
+ if (values.prompt !== undefined && values["prompt-file"] !== undefined) cliError("use exactly one of --prompt or --prompt-file");
148
+ const changes = {};
149
+ if (values.prompt !== undefined) changes.prompt = values.prompt;
150
+ if (values["prompt-file"] !== undefined) changes.prompt = await readPromptFile(values["prompt-file"], workingDirectory);
151
+ if (creating && changes.prompt === undefined) cliError("create requires --prompt or --prompt-file");
152
+ if (values.timezone !== undefined) changes.timezone = values.timezone;
153
+ if (creating && changes.timezone === undefined) cliError("create requires --timezone");
154
+ if (values.channel !== undefined || values.thread !== undefined) {
155
+ if (creating && values.channel === undefined) cliError("create requires --channel");
156
+ changes.destination = {
157
+ ...(values.channel === undefined ? {} : { channelId: values.channel }),
158
+ ...(values.thread === undefined ? {} : { threadTs: values.thread === "none" ? null : values.thread }),
159
+ };
160
+ }
161
+ if (creating && changes.destination === undefined) cliError("create requires --channel");
162
+ const schedules = ["at", "in", "every"].filter((name) => values[name] !== undefined);
163
+ if (schedules.length > 1) cliError("use exactly one of --at, --in, or --every");
164
+ if (creating && schedules.length !== 1) cliError("create requires exactly one schedule");
165
+ if (schedules.length === 0 && (values.times !== undefined || values.weekdays !== undefined || values.until !== undefined)) {
166
+ cliError("--times, --weekdays, and --until require --every");
167
+ }
168
+ if (schedules.length === 1) changes.schedule = scheduleFromOptions(values, now);
169
+ if (values.status !== undefined) {
170
+ if (values.status !== "active" && values.status !== "inactive") cliError("--status must be active or inactive");
171
+ changes.status = values.status;
172
+ }
173
+ return changes;
174
+ }
175
+
176
+ async function readPromptFile(file, workingDirectory) {
177
+ const maxBytes = 1024 * 1024;
178
+ const root = await realpath(workingDirectory);
179
+ const requested = path.resolve(root, file);
180
+ const beforeOpen = await realpath(requested);
181
+ if (!isInside(root, beforeOpen)) cliError("--prompt-file must be inside the configured working directory");
182
+ const initial = await lstat(requested, { bigint: true });
183
+ if (initial.isSymbolicLink()) cliError("--prompt-file cannot be a symbolic link");
184
+ if (!initial.isFile()) cliError("--prompt-file must be a regular file");
185
+ const handle = await open(requested, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
186
+ try {
187
+ const opened = await handle.stat({ bigint: true });
188
+ const resolved = await realpath(requested);
189
+ if (!isInside(root, resolved)) cliError("--prompt-file must be inside the configured working directory");
190
+ const current = await lstat(requested, { bigint: true });
191
+ if (!opened.isFile() || current.isSymbolicLink()
192
+ || initial.dev !== opened.dev || initial.ino !== opened.ino
193
+ || current.dev !== opened.dev || current.ino !== opened.ino) cliError("--prompt-file must be an unchanged regular file");
194
+ if (opened.size > BigInt(maxBytes)) cliError("--prompt-file must be no larger than 1 MB");
195
+ const data = Buffer.alloc(maxBytes + 1);
196
+ let bytesRead = 0;
197
+ while (bytesRead < data.length) {
198
+ const read = await handle.read(data, bytesRead, data.length - bytesRead, bytesRead);
199
+ if (!read.bytesRead) break;
200
+ bytesRead += read.bytesRead;
201
+ }
202
+ if (bytesRead > maxBytes) cliError("--prompt-file must be no larger than 1 MB");
203
+ const after = await handle.stat({ bigint: true });
204
+ if (BigInt(bytesRead) !== opened.size || after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) {
205
+ cliError("--prompt-file changed while being read");
206
+ }
207
+ return data.subarray(0, bytesRead).toString("utf8");
208
+ } finally {
209
+ await handle.close();
210
+ }
211
+ }
212
+
213
+ function isInside(root, candidate) {
214
+ const relative = path.relative(root, candidate);
215
+ return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
216
+ }
217
+
218
+ function scheduleFromOptions(values, now) {
219
+ if (values.at !== undefined) {
220
+ rejectRecurringOptions(values);
221
+ return { type: "once", at: values.at };
222
+ }
223
+ if (values.in !== undefined) {
224
+ rejectRecurringOptions(values);
225
+ return { type: "once", at: new Date(Date.parse(now) + parseDuration(values.in)).toISOString() };
226
+ }
227
+ const match = /^(\d+)([mhdw])$/u.exec(values.every ?? "");
228
+ if (!match || Number(match[1]) <= 0) cliError("--every must be a positive duration such as 30m, 2h, 1d, or 1w");
229
+ const frequency = { m: "minutes", h: "hours", d: "daily", w: "weekly" }[match[2]];
230
+ return {
231
+ type: "recurring",
232
+ frequency,
233
+ interval: Number(match[1]),
234
+ times: values.times === undefined ? [] : values.times.split(","),
235
+ weekdays: values.weekdays === undefined ? [] : values.weekdays.split(",").map(Number),
236
+ until: values.until ?? null,
237
+ };
238
+ }
239
+
240
+ function parseDuration(value) {
241
+ const match = /^(\d+)([mhdw])$/u.exec(value);
242
+ if (!match || Number(match[1]) <= 0) cliError("--in must be a positive duration such as 5m");
243
+ const milliseconds = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[match[2]];
244
+ return Number(match[1]) * milliseconds;
245
+ }
246
+
247
+ function rejectRecurringOptions(values) {
248
+ if (values.times !== undefined || values.weekdays !== undefined || values.until !== undefined) cliError("--times, --weekdays, and --until require --every");
249
+ }
250
+
251
+ function requireNoOptions(values, supported) {
252
+ const unsupported = Object.keys(values).find((name) => !supported.includes(name));
253
+ if (unsupported) cliError(`unknown option --${unsupported}`);
254
+ }
255
+
256
+ function requireId(positionals) {
257
+ if (positionals.length !== 1) cliError("command requires exactly one routine ID");
258
+ return positionals[0];
259
+ }
260
+
261
+ function writeRoutineResult(output, json, value, human) {
262
+ output.write(json ? `${JSON.stringify({ ok: true, ...value })}\n` : `${human}\n`);
263
+ }
264
+
265
+ function formatRoutine(routine) {
266
+ return `${routine.id}\nStatus: ${routine.status}\nNext run: ${routine.nextRunAt ?? "-"}\nDestination: ${routine.destination.channelId}${routine.destination.threadTs ? ` thread ${routine.destination.threadTs}` : ""}`;
267
+ }
268
+
269
+ function cliError(message, code = "invalid_arguments") {
270
+ const error = new Error(message);
271
+ error.code = code;
272
+ throw error;
24
273
  }
25
274
 
26
275
  async function stop(io) {
@@ -156,6 +405,8 @@ async function start(io) {
156
405
  }
157
406
 
158
407
  main().catch((error) => {
159
- process.stderr.write(`Pipa failed: ${error instanceof Error ? error.message : String(error)}\n`);
408
+ const message = error instanceof Error ? error.message : String(error);
409
+ if (process.argv.includes("--json")) process.stdout.write(`${JSON.stringify({ ok: false, error: { code: error?.code ?? "routine_error", message } })}\n`);
410
+ else process.stderr.write(`Pipa failed: ${message}\n`);
160
411
  process.exitCode = 1;
161
412
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usepipa/pipa",
3
- "version": "0.4.3",
3
+ "version": "0.5.1",
4
4
  "description": "Run Pipa through Slack Socket Mode with OpenCode",
5
5
  "keywords": [
6
6
  "slack",
@@ -20,7 +20,8 @@
20
20
  ],
21
21
  "scripts": {
22
22
  "test": "node --test",
23
- "test:pack": "node scripts/pack-smoke.mjs"
23
+ "test:pack": "node scripts/pack-smoke.mjs",
24
+ "test:slack:routines": "node scripts/slack-routine-eval.mjs"
24
25
  },
25
26
  "engines": {
26
27
  "node": ">=22"
@@ -42,6 +43,7 @@
42
43
  "@chat-adapter/slack": "4.38.1",
43
44
  "@chat-adapter/state-memory": "4.38.1",
44
45
  "chat": "4.38.1",
45
- "cross-spawn": "7.0.6"
46
+ "cross-spawn": "7.0.6",
47
+ "luxon": "3.7.2"
46
48
  }
47
49
  }
package/src/app.mjs CHANGED
@@ -5,6 +5,9 @@ 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
7
  import { createOpenCodeExecutor, MAX_ATTACHMENT_BYTES, PipaStoppedError, runOpenCodeVersion, startSocketOpenCodeServer } from "./opencode.mjs";
8
+ import { assertRoutineDestinationAllowed, createRoutineScheduler, loadRoutineState } from "./routines.mjs";
9
+
10
+ class RoutineDeniedError extends Error {}
8
11
 
9
12
  export async function initializePipa(input, options = {}) {
10
13
  const paths = options.paths ?? pipaPaths();
@@ -65,8 +68,91 @@ export async function startPipa(options = {}) {
65
68
  }
66
69
  const runner = createConversationRunner({ sessionStore, runTurn: executor.runTurn, abortTurn: executor.abortTurn });
67
70
  let accepting = true;
68
- const interactions = createPendingInteractions();
71
+ const interactions = createPendingInteractions(config.allowedSlackUserIds);
69
72
  const pendingReactions = new Map();
73
+ const routinesEnabled = options.routinesEnabled !== false;
74
+ const routineScheduler = routinesEnabled ? (options.createRoutineScheduler ?? createRoutineScheduler)({
75
+ paths,
76
+ intervalMs: options.routineIntervalMs,
77
+ setInterval: options.setRoutineInterval,
78
+ clearInterval: options.clearRoutineInterval,
79
+ now: options.routineNow,
80
+ abortTurn: executor.abortTurn,
81
+ onError: () => process.stderr.write("Pipa routine reconciliation failed.\n"),
82
+ execute: async (snapshot, { signal, onSession, abort }) => {
83
+ const authorize = async () => {
84
+ const current = (await loadRoutineState(paths.routines)).routines.find((routine) => routine.id === snapshot.id);
85
+ if (!current || (snapshot.status === "active" && current.status !== "active")) throw new PipaStoppedError();
86
+ const latestConfig = await loadConfig(paths.config);
87
+ try {
88
+ assertRoutineDestinationAllowed(snapshot.destination, latestConfig.allowedSlackChannelIds ?? []);
89
+ } catch {
90
+ throw new RoutineDeniedError();
91
+ }
92
+ };
93
+ let denied = false;
94
+ try {
95
+ await authorize();
96
+ } catch (error) {
97
+ if (error instanceof PipaStoppedError) throw error;
98
+ if (error instanceof RoutineDeniedError) return { status: "denied", errorCode: "destination_denied", errorSummary: "Routine destination is no longer allowed." };
99
+ throw error;
100
+ }
101
+ const thread = chat.thread(slackDestinationId(snapshot.destination));
102
+ const authorizeInteraction = async () => {
103
+ try {
104
+ return await authorize();
105
+ } catch (error) {
106
+ denied = error instanceof RoutineDeniedError;
107
+ await abort(error);
108
+ throw error;
109
+ }
110
+ };
111
+ let result;
112
+ try {
113
+ result = await executor.runTurn({
114
+ prompt: snapshot.prompt,
115
+ sessionId: null,
116
+ workingDirectory: config.workingDirectory,
117
+ contextEnvironment: {
118
+ PIPA_MESSAGE_CHANNEL: "slack",
119
+ PIPA_CURRENT_SLACK_CHANNEL_ID: snapshot.destination.channelId,
120
+ PIPA_CURRENT_SLACK_THREAD_TS: snapshot.destination.threadTs ?? "",
121
+ PIPA_REQUESTER_SLACK_USER_ID: "",
122
+ },
123
+ signal,
124
+ onSession,
125
+ onInteraction: (interaction) => interactions.onInteraction({
126
+ thread,
127
+ authorize: authorizeInteraction,
128
+ loadAllowedUserIds: async () => (await loadConfig(paths.config)).allowedSlackUserIds ?? [],
129
+ }, interaction),
130
+ onPermissionReplied: interactions.onPermissionReplied,
131
+ onPermissionsReconciled: interactions.onPermissionsReconciled,
132
+ });
133
+ } catch (error) {
134
+ if (denied) return { status: "denied", errorCode: "destination_denied", errorSummary: "Routine destination is no longer allowed." };
135
+ if (signal.aborted) throw error;
136
+ return { status: "failed", errorCode: "executor_failed", errorSummary: "Routine execution failed." };
137
+ }
138
+ try {
139
+ await authorize();
140
+ if (signal.aborted) throw signal.reason;
141
+ const message = await postResult(thread, result, signal);
142
+ const threadTs = snapshot.destination.threadTs ?? message?.id;
143
+ if (threadTs && result.sessionId) {
144
+ const conversationKey = slackDestinationId({ channelId: snapshot.destination.channelId, threadTs });
145
+ await sessionStore.set(conversationKey, result.sessionId);
146
+ await chat.thread(conversationKey).subscribe();
147
+ }
148
+ } catch (error) {
149
+ if (signal.aborted || error instanceof PipaStoppedError) throw error;
150
+ if (error instanceof RoutineDeniedError) return { status: "denied", errorCode: "destination_denied", errorSummary: "Routine destination is no longer allowed." };
151
+ return { status: "failed", errorCode: "delivery_failed", errorSummary: "Routine result delivery failed." };
152
+ }
153
+ return { status: "succeeded" };
154
+ },
155
+ }) : null;
70
156
  chat.onAction?.(interactions.onAction);
71
157
  chat.onModalSubmit?.("pipa_custom", interactions.onCustomAnswer);
72
158
 
@@ -79,7 +165,10 @@ export async function startPipa(options = {}) {
79
165
 
80
166
  const handle = async (thread, message, subscribe) => {
81
167
  if (!accepting || !isAuthorized(thread, message, config) || shouldIgnore(thread, message)) return;
82
- const prompt = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
168
+ const messageText = subscribe || message.isMention ? stripMention(message.text) : message.text.trim();
169
+ const missingLinks = (message.links ?? []).map((link) => link.url)
170
+ .filter((url) => typeof url === "string" && !messageText.split(/\s+/u).includes(url));
171
+ const prompt = missingLinks.length ? `${messageText}\n\nFull links:\n${[...new Set(missingLinks)].join("\n")}` : messageText;
83
172
  if (!prompt) return;
84
173
  const attachments = message.attachments ?? [];
85
174
  if (subscribe) await thread.subscribe();
@@ -126,8 +215,11 @@ export async function startPipa(options = {}) {
126
215
  await chat.thread(conversationKey).subscribe();
127
216
  }
128
217
  await withTimeout(chat.initialize(), options.startupTimeoutMs ?? 30_000, "Slack Socket Mode startup timed out.");
218
+ await routineScheduler?.start();
129
219
  } catch (error) {
130
- await interactions.close();
220
+ routineScheduler?.stop(error);
221
+ await routineScheduler?.drain();
222
+ await withTimeout(interactions.close(), options.shutdownTimeoutMs ?? 15_000, "Interaction shutdown timed out.").catch(() => undefined);
131
223
  executor.stopAll();
132
224
  await withTimeout(chat.shutdown(), options.shutdownTimeoutMs ?? 15_000, "Slack shutdown timed out.").catch(() => undefined);
133
225
  server?.stop();
@@ -138,6 +230,7 @@ export async function startPipa(options = {}) {
138
230
  const stop = (reason = new PipaStoppedError()) => {
139
231
  if (!accepting) return;
140
232
  accepting = false;
233
+ routineScheduler?.stop(reason);
141
234
  runner.close(reason);
142
235
  executor.stopAll(reason);
143
236
  };
@@ -155,9 +248,10 @@ export async function startPipa(options = {}) {
155
248
  stop: () => stop(),
156
249
  async shutdown() {
157
250
  stop();
158
- await interactions.close();
159
251
  try {
160
252
  await withTimeout((async () => {
253
+ await interactions.close();
254
+ await routineScheduler?.drain();
161
255
  await runner.drain();
162
256
  await chat.shutdown();
163
257
  server?.stop();
@@ -170,7 +264,7 @@ export async function startPipa(options = {}) {
170
264
  };
171
265
  }
172
266
 
173
- function createPendingInteractions() {
267
+ export function createPendingInteractions(allowedUserIds = []) {
174
268
  const pending = new Map();
175
269
  const permissionRequests = new Map();
176
270
  const tails = new Map();
@@ -186,6 +280,9 @@ function createPendingInteractions() {
186
280
  questionIndex: 0,
187
281
  answers: [],
188
282
  resolve: null,
283
+ threadId: context.thread.id,
284
+ loadAllowedUserIds: context.loadAllowedUserIds,
285
+ authorize: context.authorize,
189
286
  };
190
287
  const decision = new Promise((resolve, reject) => {
191
288
  const abort = () => reject(interaction.signal.reason);
@@ -210,13 +307,19 @@ function createPendingInteractions() {
210
307
  try {
211
308
  await previous;
212
309
  if (entry.decision === undefined) {
310
+ await entry.authorize?.();
213
311
  entry.message = await postInteraction(context.thread, entry);
312
+ if (entry.threadId.endsWith(":")) entry.threadId += entry.message.id;
214
313
  if (interaction.signal.aborted) throw interaction.signal.reason;
215
314
  }
216
315
  const result = await decision;
217
316
  await submit(entry, result);
218
317
  return result;
219
318
  } finally {
319
+ if (entry.decision === undefined) {
320
+ entry.resolve?.({ type: "stopped" });
321
+ await submit(entry, { type: "stopped" }).catch(() => undefined);
322
+ }
220
323
  pending.delete(token);
221
324
  if (permissionKey) permissionRequests.delete(permissionKey);
222
325
  release();
@@ -245,6 +348,8 @@ function createPendingInteractions() {
245
348
  const token = interactionToken(event);
246
349
  const entry = pending.get(token);
247
350
  if (!entry) return;
351
+ if ((event.threadId ?? event.thread?.id) !== entry.threadId) return;
352
+ if (!await canRespond(entry, event.user)) return;
248
353
  if (event.actionId?.startsWith("pipa_dismiss_")) {
249
354
  entry.resolve?.({ type: "stop" });
250
355
  return;
@@ -277,6 +382,8 @@ function createPendingInteractions() {
277
382
  async function onCustomAnswer(event) {
278
383
  const entry = pending.get(event.privateMetadata);
279
384
  if (!entry) return;
385
+ if (event.relatedThread?.id !== entry.threadId) return;
386
+ if (!await canRespond(entry, event.user)) return;
280
387
  const answer = event.values?.answer?.trim();
281
388
  if (!answer) return { action: "errors", errors: { answer: "Enter an answer." } };
282
389
  entry.answers[entry.questionIndex] = [answer];
@@ -291,6 +398,19 @@ function createPendingInteractions() {
291
398
  else entry.message?.edit();
292
399
  }
293
400
 
401
+ async function canRespond(entry, user) {
402
+ let currentAllowedUserIds = allowedUserIds;
403
+ try {
404
+ await entry.authorize?.();
405
+ if (entry.loadAllowedUserIds) currentAllowedUserIds = await entry.loadAllowedUserIds();
406
+ } catch {
407
+ return false;
408
+ }
409
+ if (!Array.isArray(currentAllowedUserIds)) return false;
410
+ const userId = user?.userId ?? user?.id;
411
+ return !currentAllowedUserIds.length || currentAllowedUserIds.includes(userId);
412
+ }
413
+
294
414
  return { onInteraction, onPermissionReplied, onPermissionsReconciled, onAction, onCustomAnswer, close };
295
415
  }
296
416
 
@@ -319,14 +439,15 @@ function renderSubmitted(entry, decision) {
319
439
  async function postInteraction(thread, entry) {
320
440
  const [, channel, threadTs] = thread.id.split(":");
321
441
  const client = thread.adapter?.webClient;
322
- if (!client || !channel || !threadTs) throw new Error("Slack interaction context is unavailable.");
442
+ if (!client || !channel) throw new Error("Slack interaction context is unavailable.");
323
443
  const message = await client.chat.postMessage({
324
444
  channel,
325
- thread_ts: threadTs,
445
+ ...(threadTs ? { thread_ts: threadTs } : {}),
326
446
  text: interactionFallback(entry),
327
447
  blocks: renderSlackInteraction(entry),
328
448
  });
329
449
  return {
450
+ id: message.ts,
330
451
  edit: (decision) => client.chat.update({
331
452
  channel,
332
453
  ts: message.ts,
@@ -636,21 +757,28 @@ function slackContext(thread, message) {
636
757
  };
637
758
  }
638
759
 
639
- async function postResult(thread, { text, files = [] }, signal) {
760
+ export function slackDestinationId({ channelId, threadTs }) {
761
+ if (!channelId) throw new Error("A Slack channel ID is required.");
762
+ return `slack:${channelId}:${threadTs ?? ""}`;
763
+ }
764
+
765
+ export async function postResult(thread, { text, files = [] }, signal) {
640
766
  if (signal?.aborted) return;
641
767
  if (files.length) {
642
768
  try {
643
- await thread.post({ markdown: text, files });
644
- return;
769
+ return await thread.post({ markdown: text, files });
645
770
  } catch {
646
771
  // A failed adapter call may still have uploaded files, so retry text only.
647
772
  }
648
773
  }
649
774
  if (!text || signal?.aborted) return;
775
+ let firstMessage;
650
776
  for (const markdown of splitSlackMarkdown(text)) {
651
777
  if (signal?.aborted) return;
652
- await thread.post({ markdown });
778
+ const message = await thread.post({ markdown });
779
+ firstMessage ??= message;
653
780
  }
781
+ return firstMessage;
654
782
  }
655
783
 
656
784
  function splitSlackMarkdown(text, limit = 3500) {