pi-mom-slack 0.1.2 → 0.1.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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4
4
+
5
+ - Works with pi 1.6.1.
6
+
7
+ ## 0.1.3
8
+
9
+ - Works with pi 1.6.0.
10
+
11
+ ## Unreleased
12
+
13
+ - Show provider errors and empty model responses as failed runs in Slack instead of empty successful replies.
14
+
15
+ - Add `configsFromEnv()` and multi-bot CLI profiles via `PI_SLACK_WORKSPACES`, with isolated data directories and separate Slack apps.
16
+ - Allow all users with `PI_SLACK_ALLOWED_USERS=*`, including restart recovery, without sending DMs to the wildcard.
17
+ - Add opt-in Git branch auto-updates with pre-deployment checks, a systemd timer and process-health rollback.
18
+
3
19
  ## 0.1.2
4
20
 
5
21
  - Works with pi 1.5.2.
package/README.md CHANGED
@@ -117,12 +117,33 @@ The bot sends you a direct message when it is up. In a channel, invite it with `
117
117
  |---|---|---|
118
118
  | `SLACK_APP_TOKEN` | required | app-level token, `xapp-…` |
119
119
  | `SLACK_BOT_TOKEN` | required | bot token, `xoxb-…` |
120
- | `PI_SLACK_ALLOWED_USERS` | required | Slack member IDs, comma separated |
120
+ | `PI_SLACK_ALLOWED_USERS` | required | Slack member IDs, comma separated, or `*` for everyone who can reach the bot |
121
121
  | `PI_SLACK_DATA_DIR` | `~/.pi/slack` | thread working directories, run markers, state |
122
122
  | `PI_SLACK_ENV_FILE` | `./.env` | file read for the variables above |
123
123
  | `PI_SLACK_DEBUG` | | logs the type of each Slack event |
124
124
  | `PI_SLACK_SOCKET_DOWN_LIMIT_MS` | `180000` | if the Slack connection stays down this long, the process exits so a supervisor restarts it |
125
125
 
126
+ ### Multiple bots
127
+
128
+ `configsFromEnv()` returns the base config (if either base token is set), plus profiles listed in `PI_SLACK_WORKSPACES=demo,other`. Without profiles, the existing three required variables are unchanged.
129
+
130
+ Each profile requires `SLACK_APP_TOKEN_DEMO` and `SLACK_BOT_TOKEN_DEMO`. `PI_SLACK_ALLOWED_USERS_DEMO` overrides the global allowed-users list; otherwise it falls back to `PI_SLACK_ALLOWED_USERS`. An empty list is rejected. Use an explicit `*` to allow all users (this grants shell access).
131
+
132
+ For example, keep the existing base tokens and add a second app:
133
+
134
+ ```dotenv
135
+ PI_SLACK_ALLOWED_USERS=*
136
+ PI_SLACK_WORKSPACES=second
137
+ SLACK_APP_TOKEN_SECOND=xapp-…
138
+ SLACK_BOT_TOKEN_SECOND=xoxb-…
139
+ ```
140
+
141
+ The wildcard also covers resumed runs. It never receives startup DMs; add explicit user IDs alongside it to notify administrators (for example `*,U012ABCDEF`). Separate folders are not a security sandbox: these bots share the same host account and pi credentials. Do not expose this setup as a public untrusted demo.
142
+
143
+ Names contain letters, digits, underscores or hyphens and start with a letter or digit. Variable suffixes are uppercase with hyphens replaced by underscores; duplicate or ambiguous names are rejected. Each bot requires a separate Slack app: duplicate app tokens are rejected.
144
+
145
+ The base bot keeps `PI_SLACK_DATA_DIR` (default `~/.pi/slack`); profiles use `<base>/workspaces/<name>`. The CLI starts and stops all bots together and records process crashes in every data directory.
146
+
126
147
  Variables already set in the environment win over the file. Everything read from the file, plus any variable whose name looks like a credential (`TOKEN`, `SECRET`, `API_KEY`, `PASSWORD`…), is removed from the environment of the agent's shell. pi itself still reads your provider keys.
127
148
 
128
149
  The model, thinking level, skills and context files (`AGENTS.md`) come from pi's own configuration. pi extensions are not loaded, since many expect a terminal.
@@ -164,6 +185,31 @@ sudo loginctl enable-linger $USER # keep it running after logout
164
185
 
165
186
  Pin the version and update it on purpose: the startup message lists what changed. `pi-mom-slack@latest` also works, but then every restart may run a release you have not read, including the automatic pi updates. Under systemd, `npx` must be on the unit's `PATH` (with nvm, set `Environment=PATH=…` to nvm's `bin` folder), or use `scripts/deploy-ssh.sh`, which does it for you.
166
187
 
188
+ ### Automatic Git updates (archive deployments)
189
+
190
+ For an existing **user** `pi-mom-slack.service` installed by `deploy-ssh.sh`, the server does not need a `.git` directory. Run the installer **on the server as the service user**, with Git, Node/npm and `flock` available:
191
+
192
+ ```sh
193
+ # us2, logged in as tota; copy both scripts to the server first
194
+ bash scripts/install-auto-update.sh https://github.com/tsua0002/pi-mom-slack.git main /home/tota/pi-mom-slack
195
+ ```
196
+
197
+ `main` is this repository's current branch (the local clone has no origin/HEAD default-branch reference). For another repository, supply its intended branch explicitly. The installer checks the running service and expects `ExecStart=<node> dist/cli.js`. It captures your current PATH for builds, so select Node 22.19+ before installing. Keep user linger enabled.
198
+
199
+ The timer polls two minutes after boot/installation and two minutes after each completed check. A nonblocking lock prevents overlapping runs. A bare cache and commit-named releases live under `~/.local/share/pi-mom-slack-updates`. Each new commit must pass `npm ci`, build, type checks and tests before an atomic service drop-in changes `WorkingDirectory`. The existing ExecStart and service environment remain unchanged. Successfully activated commits are not restarted again.
200
+
201
+ The drop-in sets `PI_SLACK_ENV_FILE` to the absolute existing app `.env` (for the example, `/home/tota/pi-mom-slack/.env`). Neither that file nor existing data is copied or deleted. Default data stays in `~/.pi/slack`; custom `PI_SLACK_DATA_DIR` must be absolute, including in the service environment. Convert relative paths to their **existing** absolute location first. Services with systemd `EnvironmentFile` directives require manual review and are rejected.
202
+
203
+ If restart fails or the process exits/restarts during the 15-second observation window, the previous drop-in is restored and the previous service restarted. Health means only **the same process remains active**, not Slack connectivity or functional readiness. Failed commits are retried; releases/cache are not pruned. A power loss during switching requires operator review. Rollback does not undo data migrations. Updates execute trusted branch code and npm lifecycle scripts as your user; only enable this for repositories you trust. Restarts can interrupt in-flight work.
204
+
205
+ ```sh
206
+ systemctl --user start pi-mom-slack-update.service # check now
207
+ journalctl --user -u pi-mom-slack-update -f
208
+ systemctl --user disable --now pi-mom-slack-update.timer # stop polling
209
+ ```
210
+
211
+ Disabling the timer leaves the current release running. To return to the archive deployment, also stop any running update service, remove `~/.config/systemd/user/pi-mom-slack.service.d/90-auto-update.conf`, run `systemctl --user daemon-reload`, then restart `pi-mom-slack`. Keep the original app directory for rollback. Do not run archive deployment and automatic updates concurrently. The updater scripts themselves are installed snapshots; rerun the installer to upgrade them.
212
+
167
213
  ## Compared with mom
168
214
 
169
215
  pi-mom-slack is not a port of mom. It keeps the idea (pi in Slack, one command) and builds on the current pi SDK.
package/dist/agent.js CHANGED
@@ -91,12 +91,23 @@ export class ThreadAgents {
91
91
  const images = opts.images ?? [];
92
92
  const readsImages = session.model?.input?.includes("image") ?? false;
93
93
  const imageNote = images.length && !readsImages ? "\n\n(The current model does not read images: they are only saved in files/.)" : "";
94
+ const checkModelError = () => {
95
+ const last = session.messages.at(-1);
96
+ if (last?.role === "assistant" && last.stopReason === "error") {
97
+ throw new Error(last.errorMessage || "The model failed without an error message.");
98
+ }
99
+ };
94
100
  await session.prompt(prompt + imageNote, readsImages && images.length ? { images } : undefined);
101
+ checkModelError();
95
102
  // Models sometimes end the turn on "I will now…": push the work through instead of leaving an announcement.
96
103
  for (let i = 0; i < MAX_CONTINUES && !aborted && looksLikeAnnouncement(session.getLastAssistantText() ?? ""); i++) {
97
104
  await session.prompt(CONTINUE_PROMPT);
105
+ checkModelError();
98
106
  }
99
- return { text: session.getLastAssistantText() ?? "", aborted, tools };
107
+ const reply = session.getLastAssistantText() ?? "";
108
+ if (!aborted && !reply.trim())
109
+ throw new Error("The model returned an empty reply. Please try again later or choose another model with !model.");
110
+ return { text: reply, aborted, tools };
100
111
  }
101
112
  finally {
102
113
  this.processes.get(thread.key)?.cleanup();
package/dist/bot.d.ts CHANGED
@@ -31,7 +31,7 @@ export interface SlackBotHooks {
31
31
  export interface SlackBotOptions {
32
32
  appToken: string;
33
33
  botToken: string;
34
- /** Slack member IDs allowed to talk to the bot. Required, never empty. */
34
+ /** Slack member IDs allowed to talk to the bot. Use "*" for everyone. Required, never empty. */
35
35
  allowedUsers: string[];
36
36
  /** Root of thread workspaces, run markers and the state file. */
37
37
  dataDir: string;
package/dist/bot.js CHANGED
@@ -21,6 +21,8 @@ export function createSlackBot(options) {
21
21
  const allowed = new Set(options.allowedUsers.map((u) => u.trim()).filter(Boolean));
22
22
  if (allowed.size === 0)
23
23
  throw new Error("allowedUsers is empty: list the Slack member IDs allowed to use the bot");
24
+ const isAllowed = (user) => allowed.has("*") || allowed.has(user);
25
+ const notifyUsers = [...allowed].filter((user) => user !== "*");
24
26
  const { dataDir } = options;
25
27
  const agents = new ThreadAgents({ dataDir, systemNote: options.systemNote, customTools: options.customTools, secretNames: options.secretNames });
26
28
  const markers = new RunMarkers(dataDir);
@@ -144,7 +146,7 @@ export function createSlackBot(options) {
144
146
  }
145
147
  async function handle(msg) {
146
148
  const t = thread(msg.channel, msg.threadTs);
147
- if (!allowed.has(msg.user)) {
149
+ if (!isAllowed(msg.user)) {
148
150
  // Colleagues talking in a thread the bot follows are not addressing it: only answer a mention or a DM.
149
151
  if (msg.isDirect || msg.mentioned)
150
152
  await t.post("_Not authorized. Ask the bot's owner to add your Slack member ID to PI_SLACK_ALLOWED_USERS._");
@@ -174,7 +176,7 @@ export function createSlackBot(options) {
174
176
  void (async () => {
175
177
  try {
176
178
  bot.trackThread(marker.channel, marker.threadTs);
177
- if (!allowed.has(marker.user)) {
179
+ if (!isAllowed(marker.user)) {
178
180
  await t.post("_Cannot resume: the user who started the run is no longer allowed._");
179
181
  markers.finish(marker);
180
182
  return;
@@ -219,14 +221,14 @@ export function createSlackBot(options) {
219
221
  if (warnedConnections)
220
222
  return;
221
223
  warnedConnections = true;
222
- for (const user of allowed)
224
+ for (const user of notifyUsers)
223
225
  void slack.dm(user, `:warning: ${text}`).catch(() => { });
224
226
  };
225
227
  await bot.start();
226
- console.log(`[pi-mom-slack] ${VERSION} (pi ${PI_VERSION}) connected · bot ${bot.botUserId} · data in ${dataDir} · ${allowed.size} allowed user(s)`);
228
+ console.log(`[pi-mom-slack] ${VERSION} (pi ${PI_VERSION}) connected · bot ${bot.botUserId} · data in ${dataDir} · ${allowed.has("*") ? "all users allowed" : `${allowed.size} allowed user(s)`}`);
227
229
  await resumeInterrupted().catch((e) => console.error("[pi-mom-slack] reading run markers failed", e));
228
230
  if (options.notifyOnStart !== false) {
229
- for (const user of allowed)
231
+ for (const user of notifyUsers)
230
232
  void slack.dm(user, `pi-mom-slack is up.\n${reason}`).catch((e) => console.warn(`[pi-mom-slack] startup message not sent to ${user}: ${errText(e)}`));
231
233
  }
232
234
  await options.hooks?.onStart?.({ reason, botUserId: bot.botUserId });
package/dist/cli.js CHANGED
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import { resolve } from "node:path";
8
8
  import { createSlackBot, recordCrash } from "./bot.js";
9
- import { configFromEnv, loadEnvFile } from "./config.js";
9
+ import { configsFromEnv, loadEnvFile } from "./config.js";
10
10
  import { PI_VERSION, VERSION } from "./version.js";
11
11
  const HELP = `pi-mom-slack ${VERSION} (pi ${PI_VERSION})
12
12
 
@@ -17,7 +17,10 @@ Usage: npx pi-mom-slack
17
17
  Environment (or a .env file in the current directory):
18
18
  SLACK_APP_TOKEN app-level token, xapp-… (scope connections:write)
19
19
  SLACK_BOT_TOKEN bot token, xoxb-…
20
- PI_SLACK_ALLOWED_USERS Slack member IDs allowed to use the bot, comma separated
20
+ PI_SLACK_ALLOWED_USERS Slack member IDs, comma separated, or explicit *
21
+ PI_SLACK_WORKSPACES named profiles, comma separated (e.g. demo,other)
22
+ use SLACK_APP_TOKEN_DEMO, SLACK_BOT_TOKEN_DEMO,
23
+ PI_SLACK_ALLOWED_USERS_DEMO (falls back to global)
21
24
  PI_SLACK_DATA_DIR thread workspaces and state (default ~/.pi/slack)
22
25
  PI_SLACK_ENV_FILE env file to read (default ./.env)
23
26
 
@@ -33,20 +36,21 @@ if (arg === "--version" || arg === "-v") {
33
36
  process.exit(0);
34
37
  }
35
38
  const secretNames = loadEnvFile(resolve(process.env.PI_SLACK_ENV_FILE ?? ".env"));
36
- let config;
39
+ let configs;
37
40
  try {
38
- config = configFromEnv(process.env, secretNames);
41
+ configs = configsFromEnv(process.env, secretNames);
39
42
  }
40
43
  catch (e) {
41
44
  console.error(`pi-mom-slack: configuration incomplete\n${e instanceof Error ? e.message : e}\n\nRun \`npx pi-mom-slack --help\` or see https://github.com/tsua0002/pi-mom-slack#readme`);
42
45
  process.exit(1);
43
46
  }
44
- const bot = createSlackBot({ ...config });
47
+ const bots = configs.map((config) => createSlackBot({ ...config }));
45
48
  const crash = (kind) => (err) => {
46
49
  console.error(`[pi-mom-slack] ${kind}: ${err instanceof Error ? err.message : err}`);
47
50
  if (process.env.PI_SLACK_DEBUG)
48
51
  console.error(err);
49
- recordCrash(config.dataDir, err);
52
+ for (const config of configs)
53
+ recordCrash(config.dataDir, err);
50
54
  process.exit(1);
51
55
  };
52
56
  process.on("uncaughtException", crash("uncaughtException"));
@@ -54,7 +58,7 @@ process.on("unhandledRejection", crash("unhandledRejection"));
54
58
  for (const signal of ["SIGINT", "SIGTERM"]) {
55
59
  process.on(signal, () => {
56
60
  console.log(`[pi-mom-slack] ${signal}, stopping…`);
57
- void bot.stop(signal).finally(() => process.exit(0));
61
+ void Promise.allSettled(bots.map((bot) => bot.stop(signal))).finally(() => process.exit(0));
58
62
  });
59
63
  }
60
- await bot.start().catch(crash("Slack connection failed"));
64
+ await Promise.all(bots.map((bot) => bot.start())).catch(crash("Slack connection failed"));
package/dist/config.d.ts CHANGED
@@ -11,3 +11,5 @@ export declare function loadEnvFile(path: string, env?: NodeJS.ProcessEnv): stri
11
11
  export declare function parseUsers(value: string | undefined): string[];
12
12
  /** Validates the three required values. Errors name the variable, never its value. */
13
13
  export declare function configFromEnv(env?: NodeJS.ProcessEnv, secretNames?: string[]): CliConfig;
14
+ /** Base bot (when configured), followed by isolated named Slack app profiles. */
15
+ export declare function configsFromEnv(env?: NodeJS.ProcessEnv, secretNames?: string[]): CliConfig[];
package/dist/config.js CHANGED
@@ -54,3 +54,41 @@ export function configFromEnv(env = process.env, secretNames = []) {
54
54
  secretNames,
55
55
  };
56
56
  }
57
+ /** Base bot (when configured), followed by isolated named Slack app profiles. */
58
+ export function configsFromEnv(env = process.env, secretNames = []) {
59
+ const names = (env.PI_SLACK_WORKSPACES ?? "").split(",").map((name) => name.trim()).filter(Boolean);
60
+ const suffixes = new Set();
61
+ for (const name of names) {
62
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) {
63
+ throw new Error("PI_SLACK_WORKSPACES names must contain only letters, digits, underscores or hyphens and start with a letter or digit");
64
+ }
65
+ const suffix = name.toUpperCase().replaceAll("-", "_");
66
+ if (suffixes.has(suffix))
67
+ throw new Error("PI_SLACK_WORKSPACES contains duplicate or ambiguous profile names");
68
+ suffixes.add(suffix);
69
+ }
70
+ const configs = [];
71
+ if (!names.length || env.SLACK_APP_TOKEN?.trim() || env.SLACK_BOT_TOKEN?.trim()) {
72
+ configs.push(configFromEnv(env, secretNames));
73
+ }
74
+ const baseDir = resolve(env.PI_SLACK_DATA_DIR?.trim() || join(homedir(), ".pi", "slack"));
75
+ for (const name of names) {
76
+ const suffix = name.toUpperCase().replaceAll("-", "_");
77
+ try {
78
+ configs.push(configFromEnv({
79
+ SLACK_APP_TOKEN: env[`SLACK_APP_TOKEN_${suffix}`],
80
+ SLACK_BOT_TOKEN: env[`SLACK_BOT_TOKEN_${suffix}`],
81
+ PI_SLACK_ALLOWED_USERS: env[`PI_SLACK_ALLOWED_USERS_${suffix}`] ?? env.PI_SLACK_ALLOWED_USERS,
82
+ PI_SLACK_DATA_DIR: join(baseDir, "workspaces", name),
83
+ }, secretNames));
84
+ }
85
+ catch (error) {
86
+ // Validation messages contain variable names only, never token values.
87
+ throw new Error(error.message.replace(/SLACK_APP_TOKEN|SLACK_BOT_TOKEN|PI_SLACK_ALLOWED_USERS/g, (key) => `${key}_${suffix}`));
88
+ }
89
+ }
90
+ if (new Set(configs.map((config) => config.appToken)).size !== configs.length) {
91
+ throw new Error("Duplicate Slack app tokens: each bot requires a separate Slack app");
92
+ }
93
+ return configs;
94
+ }
package/dist/index.d.ts CHANGED
@@ -2,5 +2,5 @@ export { createSlackBot, recordCrash, RESUME_PROMPT } from "./bot.ts";
2
2
  export type { Command, CommandContext, RunContext, SlackBotHandle, SlackBotHooks, SlackBotOptions } from "./bot.ts";
3
3
  export { DEFAULT_SYSTEM_NOTE } from "./agent.ts";
4
4
  export type { RunResult, ThreadInfo } from "./agent.ts";
5
- export { configFromEnv, loadEnvFile } from "./config.ts";
5
+ export { configFromEnv, configsFromEnv, loadEnvFile } from "./config.ts";
6
6
  export { VERSION } from "./version.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { createSlackBot, recordCrash, RESUME_PROMPT } from "./bot.js";
2
2
  export { DEFAULT_SYSTEM_NOTE } from "./agent.js";
3
- export { configFromEnv, loadEnvFile } from "./config.js";
3
+ export { configFromEnv, configsFromEnv, loadEnvFile } from "./config.js";
4
4
  export { VERSION } from "./version.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mom-slack",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Run the pi coding agent in Slack: one pi session per thread, in one command.",
5
5
  "license": "MIT",
6
6
  "author": "tsua0002",
@@ -49,8 +49,8 @@
49
49
  "prepack": "npm run build"
50
50
  },
51
51
  "dependencies": {
52
- "@earendil-works/pi-ai": "1.5.2",
53
- "@earendil-works/pi-coding-agent": "1.5.2",
52
+ "@earendil-works/pi-ai": "1.6.1",
53
+ "@earendil-works/pi-coding-agent": "1.6.1",
54
54
  "@slack/socket-mode": "3.1.1",
55
55
  "@slack/web-api": "8.3.0",
56
56
  "typebox": "1.3.27"