pi-mom-slack 0.1.6 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,25 +1,20 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.6
3
+ ## 0.2.1
4
4
 
5
- - Works with pi 1.8.0.
5
+ - Run `prepare` → `build` so GitHub installs ship a usable `dist/` (desk API for mom-wizard).
6
6
 
7
- ## 0.1.5
7
+ ## 0.2.0
8
8
 
9
- - Works with pi 1.7.0.
10
-
11
- ## 0.1.4
12
-
13
- - Works with pi 1.6.1.
9
+ - Desk mode (`npx pi-mom-desk` / `createDeskBot`): named agent (`PI_SLACK_AGENT_NAME`), shared `AGENT.md` + MEMORY with lexical **smart_insert** (hard size cap), `memory_search` / `memory_update`.
10
+ - Cross-desk in one Slack thread: accept peer bot mentions, `thread_read`, `ask_peer` with an anti-loop guard (`PI_SLACK_PEER_BOT_USER_ID`).
11
+ - Prune inactive `threads/` workspaces at desk startup (`PI_SLACK_PRUNE_THREAD_DAYS`, default 14).
12
+ - PoA wizard deploy lives in the separate **mom-wizard** app repo.
14
13
 
15
14
  ## 0.1.3
16
15
 
17
- - Works with pi 1.6.0.
18
-
19
- ## Unreleased
20
-
16
+ - Resolve ID-only Slack file metadata with `files.info`, support file-only messages, prefer download URLs, and report unresolved attachments to the user and pi instead of silently dropping them.
21
17
  - Show provider errors and empty model responses as failed runs in Slack instead of empty successful replies.
22
-
23
18
  - Add `configsFromEnv()` and multi-bot CLI profiles via `PI_SLACK_WORKSPACES`, with isolated data directories and separate Slack apps.
24
19
  - Allow all users with `PI_SLACK_ALLOWED_USERS=*`, including restart recovery, without sending DMs to the wildcard.
25
20
  - Add opt-in Git branch auto-updates with pre-deployment checks, a systemd timer and process-health rollback.
package/README.md CHANGED
@@ -111,6 +111,10 @@ The bot sends you a direct message when it is up. In a channel, invite it with `
111
111
  <img src="docs/screenshots/12-server-report.jpg" alt="Running on a server: the agent writes a system report, uploads it to the thread and sums it up" width="40%">
112
112
  <img src="docs/screenshots/11-model.jpg" alt="!model lists the models pi has credentials for" width="40%">
113
113
 
114
+ ### Files shared in a thread
115
+
116
+ Files attached to an incoming message are downloaded into that thread's working directory and their paths are passed to pi. File-only messages and Slack snippet files are supported. When Slack sends only a file ID, the bot resolves its metadata with `files.info` (`files:read` required). Lookup or download failures are shown in the thread and passed to pi, rather than silently dropping the file. This does not import older attachments from thread history.
117
+
114
118
  ## Configuration
115
119
 
116
120
  | Variable | Default | |
@@ -229,6 +233,27 @@ pi-mom-slack is not a port of mom. It keeps the idea (pi in Slack, one command)
229
233
 
230
234
  The agent runs pi's tools, `bash` included, as the user running the bot, on that machine. Treat access to the bot like shell access: list only people you would give a shell to, and run it under a dedicated user or in a container if the machine holds anything sensitive. Removing credentials from the agent's shell prevents mistakes, not a determined agent.
231
235
 
236
+ ## Desk mode
237
+
238
+ Same package, ops desks with a **named identity**, shared **AGENT.md** + **MEMORY** (smart_insert, never a full dump), and optional **peer** talk in the same Slack thread.
239
+
240
+ ```sh
241
+ npx pi-mom-desk
242
+ ```
243
+
244
+ | Variable | Role |
245
+ |---|---|
246
+ | `PI_SLACK_AGENT_NAME` | Identity, e.g. `wizard-central` or `wizard-workers` |
247
+ | `PI_SLACK_PEER_BOT_USER_ID` | Slack user id (`U…`) of the other desk bot |
248
+ | `PI_SLACK_DATA_DIR` | Holds `AGENT.md`, `memory/`, `threads/` |
249
+ | `PI_SLACK_PRUNE_THREAD_DAYS` | Drop inactive thread workspaces older than N days (default `14`, `0` = off) |
250
+
251
+ PoA wizards (`wizard-central` / `wizard-workers`) live in the separate app repo **mom-wizard** (deploy, AGENT.md, systemd, auto-update). This package exposes the library API: `createDeskBot`, `deskConfigFromEnv`, `smartInsert`, peer tools. CLI: `npx pi-mom-desk`.
252
+
253
+ **Session model:** one pi session per Slack thread; AGENT.md + MEMORY are shared across threads of that bot, with lexical smart_insert (hard size cap).
254
+
255
+ **Cross-desk:** peer bot mentions, `thread_read`, `ask_peer` (rate-limited).
256
+
232
257
  ## Extending it
233
258
 
234
259
  The package is also a library. `createSlackBot` takes the same settings as the CLI, plus extension points:
@@ -19,6 +19,8 @@ export async function saveAttachments(files, workspace, download, stamp = Date.n
19
19
  mkdirSync(join(workspace, rel), { recursive: true });
20
20
  for (const [i, f] of files.entries()) {
21
21
  try {
22
+ if (f.error)
23
+ throw new Error(f.error);
22
24
  const buf = await download(f.url, MAX_FILE);
23
25
  const path = join(rel, safeName(f.name, i));
24
26
  writeFileSync(join(workspace, path), buf);
package/dist/bot.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
2
2
  import { type RunResult, type ThreadInfo } from "./agent.ts";
3
+ import { type SlackApi } from "./slack.ts";
3
4
  export interface CommandContext {
4
5
  thread: ThreadInfo;
5
6
  /** Text after the command name, trimmed. */
@@ -26,6 +27,7 @@ export interface SlackBotHooks {
26
27
  onStart?: (info: {
27
28
  reason: string;
28
29
  botUserId: string;
30
+ api: SlackApi;
29
31
  }) => Promise<void> | void;
30
32
  }
31
33
  export interface SlackBotOptions {
@@ -46,6 +48,11 @@ export interface SlackBotOptions {
46
48
  secretNames?: string[];
47
49
  /** Direct message to allowed users at startup (reason of the restart). Default true. */
48
50
  notifyOnStart?: boolean;
51
+ /**
52
+ * Slack user IDs of peer bots allowed to wake this bot with a mention (desk cross-talk).
53
+ * Peer messages still require an @mention of this bot.
54
+ */
55
+ peerBotUserIds?: string[];
49
56
  }
50
57
  export interface SlackBotHandle {
51
58
  start(): Promise<void>;
package/dist/bot.js CHANGED
@@ -21,7 +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);
24
+ const peers = new Set((options.peerBotUserIds ?? []).map((u) => u.trim()).filter(Boolean));
25
+ const isAllowed = (user) => allowed.has("*") || allowed.has(user) || peers.has(user);
25
26
  const notifyUsers = [...allowed].filter((user) => user !== "*");
26
27
  const { dataDir } = options;
27
28
  const agents = new ThreadAgents({ dataDir, systemNote: options.systemNote, customTools: options.customTools, secretNames: options.secretNames });
@@ -146,6 +147,9 @@ export function createSlackBot(options) {
146
147
  }
147
148
  async function handle(msg) {
148
149
  const t = thread(msg.channel, msg.threadTs);
150
+ // Peer bots may wake us with a mention; other bots stay ignored at dispatch.
151
+ if (msg.fromBot && msg.mentioned && !peers.has(msg.user))
152
+ return;
149
153
  if (!isAllowed(msg.user)) {
150
154
  // Colleagues talking in a thread the bot follows are not addressing it: only answer a mention or a DM.
151
155
  if (msg.isDirect || msg.mentioned)
@@ -165,7 +169,8 @@ export function createSlackBot(options) {
165
169
  await t.post(`_File(s) not retrieved:\n${att.errors.join("\n")}_`);
166
170
  const name = await slack.userName(msg.user);
167
171
  const body = await slack.resolveMentions(msg.text);
168
- const files = att.saved.length ? `\n\nAttached files (in the working directory):\n${att.saved.map((p) => `- ${p}`).join("\n")}` : "";
172
+ const files = (att.saved.length ? `\n\nAttached files (in the working directory):\n${att.saved.map((p) => `- ${p}`).join("\n")}` : "")
173
+ + (att.errors.length ? `\n\nSome attached files could not be retrieved. Do not claim to have read them:\n${att.errors.join("\n")}` : "");
169
174
  await runInThread(t, msg.user, `[${name}] ${body}${files}`, { ts: msg.ts, images: att.images, resumed: false });
170
175
  }
171
176
  async function resumeInterrupted() {
@@ -231,7 +236,7 @@ export function createSlackBot(options) {
231
236
  for (const user of notifyUsers)
232
237
  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)}`));
233
238
  }
234
- await options.hooks?.onStart?.({ reason, botUserId: bot.botUserId });
239
+ await options.hooks?.onStart?.({ reason, botUserId: bot.botUserId, api: slack });
235
240
  },
236
241
  async stop(signal = "stop") {
237
242
  if (stopping)
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * npx pi-mom-desk — same package as pi-mom-slack, desk mode (AGENT.md + MEMORY + peer).
4
+ */
5
+ import { resolve } from "node:path";
6
+ import { recordCrash } from "./bot.js";
7
+ import { loadEnvFile } from "./config.js";
8
+ import { createDeskBot } from "./desk.js";
9
+ import { deskConfigFromEnv } from "./desk-config.js";
10
+ import { PI_VERSION, VERSION } from "./version.js";
11
+ const HELP = `pi-mom-desk ${VERSION} (pi ${PI_VERSION})
12
+
13
+ Desk mode of pi-mom-slack: one session per Slack thread, shared AGENT.md + MEMORY,
14
+ named identity (wizard-central / wizard-workers), optional peer bot in the same thread.
15
+
16
+ Usage: npx pi-mom-desk
17
+
18
+ Environment (or a .env file):
19
+ SLACK_APP_TOKEN app-level token, xapp-…
20
+ SLACK_BOT_TOKEN bot token, xoxb-…
21
+ PI_SLACK_ALLOWED_USERS Slack member IDs, or *
22
+ PI_SLACK_AGENT_NAME identity, e.g. wizard-central or wizard-workers
23
+ PI_SLACK_PEER_BOT_USER_ID Slack user id of the other desk bot (U…)
24
+ PI_SLACK_DATA_DIR data root (AGENT.md, memory/, threads/)
25
+ PI_SLACK_PRUNE_THREAD_DAYS prune inactive threads older than N days (default 14, 0=off)
26
+ PI_SLACK_ENV_FILE env file (default ./.env)
27
+
28
+ Put AGENT.md under PI_SLACK_DATA_DIR. MEMORY notes go in memory/ via memory_update.
29
+
30
+ Setup: https://github.com/tsua0002/pi-mom-slack#desk-mode`;
31
+ const arg = process.argv[2];
32
+ if (arg === "--help" || arg === "-h") {
33
+ console.log(HELP);
34
+ process.exit(0);
35
+ }
36
+ if (arg === "--version" || arg === "-v") {
37
+ console.log(VERSION);
38
+ process.exit(0);
39
+ }
40
+ const secretNames = loadEnvFile(resolve(process.env.PI_SLACK_ENV_FILE ?? ".env"));
41
+ let config;
42
+ try {
43
+ config = deskConfigFromEnv(process.env, secretNames);
44
+ }
45
+ catch (e) {
46
+ console.error(`pi-mom-desk: configuration incomplete\n${e instanceof Error ? e.message : e}\n\nRun \`npx pi-mom-desk --help\``);
47
+ process.exit(1);
48
+ }
49
+ const bot = createDeskBot({
50
+ appToken: config.appToken,
51
+ botToken: config.botToken,
52
+ allowedUsers: config.allowedUsers,
53
+ dataDir: config.dataDir,
54
+ secretNames: config.secretNames,
55
+ agentName: config.agentName,
56
+ peerBotUserId: config.peerBotUserId,
57
+ pruneThreadDays: config.pruneThreadDays,
58
+ });
59
+ const crash = (kind) => (err) => {
60
+ console.error(`[pi-mom-desk] ${kind}: ${err instanceof Error ? err.message : err}`);
61
+ if (process.env.PI_SLACK_DEBUG)
62
+ console.error(err);
63
+ recordCrash(config.dataDir, err);
64
+ process.exit(1);
65
+ };
66
+ process.on("uncaughtException", crash("uncaughtException"));
67
+ process.on("unhandledRejection", crash("unhandledRejection"));
68
+ for (const signal of ["SIGINT", "SIGTERM"]) {
69
+ process.on(signal, () => {
70
+ console.log(`[pi-mom-desk] ${signal}, stopping…`);
71
+ void bot.stop(signal).finally(() => process.exit(0));
72
+ });
73
+ }
74
+ await bot.start().catch(crash("Slack connection failed"));
75
+ console.log(`[pi-mom-desk] ${config.agentName} ready · data ${config.dataDir}`);
@@ -0,0 +1,8 @@
1
+ import { type CliConfig } from "./config.ts";
2
+ export interface DeskCliConfig extends CliConfig {
3
+ agentName: string;
4
+ peerBotUserId?: string;
5
+ pruneThreadDays: number;
6
+ }
7
+ /** Reads desk identity and peer from the environment. */
8
+ export declare function deskConfigFromEnv(env?: NodeJS.ProcessEnv, secretNames?: string[]): DeskCliConfig;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Desk CLI configuration on top of the base Slack env.
3
+ */
4
+ import { resolve } from "node:path";
5
+ import { configFromEnv } from "./config.js";
6
+ /** Reads desk identity and peer from the environment. */
7
+ export function deskConfigFromEnv(env = process.env, secretNames = []) {
8
+ const base = configFromEnv(env, secretNames);
9
+ const agentName = env.PI_SLACK_AGENT_NAME?.trim() ?? "";
10
+ if (!agentName)
11
+ throw new Error("PI_SLACK_AGENT_NAME is required (e.g. wizard-central or wizard-workers)");
12
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(agentName)) {
13
+ throw new Error("PI_SLACK_AGENT_NAME must start with a letter or digit and contain only letters, digits, underscores or hyphens");
14
+ }
15
+ const peerBotUserId = env.PI_SLACK_PEER_BOT_USER_ID?.trim() || undefined;
16
+ if (peerBotUserId && !/^U[A-Z0-9]+$/i.test(peerBotUserId)) {
17
+ throw new Error("PI_SLACK_PEER_BOT_USER_ID must be a Slack user id (U…)");
18
+ }
19
+ const rawPrune = env.PI_SLACK_PRUNE_THREAD_DAYS?.trim();
20
+ const pruneThreadDays = rawPrune === undefined || rawPrune === "" ? 14 : Number(rawPrune);
21
+ if (!Number.isFinite(pruneThreadDays) || pruneThreadDays < 0) {
22
+ throw new Error("PI_SLACK_PRUNE_THREAD_DAYS must be a number >= 0 (0 disables prune)");
23
+ }
24
+ return {
25
+ ...base,
26
+ dataDir: resolve(base.dataDir),
27
+ agentName,
28
+ peerBotUserId,
29
+ pruneThreadDays,
30
+ };
31
+ }
package/dist/desk.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Desk mode: named agent (wizard-central / wizard-workers), AGENT.md + smart MEMORY, peer tools.
3
+ * Same package for every host; identity and peer come from the environment.
4
+ */
5
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
6
+ import { type ThreadInfo } from "./agent.ts";
7
+ import { type Command, type SlackBotHandle, type SlackBotHooks, type SlackBotOptions } from "./bot.ts";
8
+ export interface DeskOptions {
9
+ appToken: string;
10
+ botToken: string;
11
+ allowedUsers: string[];
12
+ dataDir: string;
13
+ /** Display / prompt identity, e.g. wizard-central. */
14
+ agentName: string;
15
+ /** Slack user id of the peer desk bot (the other wizard). */
16
+ peerBotUserId?: string;
17
+ /** Extra system note after the desk contract. */
18
+ systemNote?: string;
19
+ /** Extra tools on top of memory + peer tools. */
20
+ customTools?: (thread: ThreadInfo) => ToolDefinition[] | Promise<ToolDefinition[]>;
21
+ commands?: Record<string, Command>;
22
+ hooks?: SlackBotHooks;
23
+ secretNames?: string[];
24
+ notifyOnStart?: boolean;
25
+ /** Prune thread workspaces older than this many days at startup. 0 disables. Default 14. */
26
+ pruneThreadDays?: number;
27
+ }
28
+ export declare const DESK_SYSTEM_NOTE: string;
29
+ /** Build createSlackBot options for a desk agent. */
30
+ export declare function deskBotOptions(options: DeskOptions): SlackBotOptions;
31
+ /** Start a desk bot (wizard-central / wizard-workers share this entry). */
32
+ export declare function createDeskBot(options: DeskOptions): SlackBotHandle;
package/dist/desk.js ADDED
@@ -0,0 +1,75 @@
1
+ import { DEFAULT_SYSTEM_NOTE } from "./agent.js";
2
+ import { createSlackBot } from "./bot.js";
3
+ import { memorySearchTools, smartInsert } from "./memory.js";
4
+ import { createPeerAskGuard, peerTools } from "./peer.js";
5
+ import { pruneOldThreads } from "./prune.js";
6
+ export const DESK_SYSTEM_NOTE = [
7
+ DEFAULT_SYSTEM_NOTE,
8
+ "You are a desk ops agent: diagnose, fix, and report. Your shell is the OS user of this service: act on everything that user can access. Do not invent access you do not have.",
9
+ "Shared knowledge: AGENT.md (role and scope) and MEMORY (durable notes). Only a small relevant MEMORY slice is injected each turn; use memory_search / memory_update when needed. Never paste secrets into Slack or MEMORY.",
10
+ "When another desk bot is in the same thread, use thread_read to see its replies and ask_peer to mention it with a complete question. Do not loop ask_peer.",
11
+ ].join("\n");
12
+ /** Build createSlackBot options for a desk agent. */
13
+ export function deskBotOptions(options) {
14
+ const agentName = options.agentName.trim();
15
+ if (!agentName)
16
+ throw new Error("agentName is required");
17
+ const peerBotUserId = options.peerBotUserId?.trim() || undefined;
18
+ const pruneDays = options.pruneThreadDays ?? 14;
19
+ const guard = createPeerAskGuard();
20
+ const runtime = { botUserId: "" };
21
+ const userTools = options.customTools;
22
+ const userHooks = options.hooks;
23
+ return {
24
+ appToken: options.appToken,
25
+ botToken: options.botToken,
26
+ allowedUsers: options.allowedUsers,
27
+ dataDir: options.dataDir,
28
+ secretNames: options.secretNames,
29
+ notifyOnStart: options.notifyOnStart,
30
+ peerBotUserIds: peerBotUserId ? [peerBotUserId] : [],
31
+ commands: options.commands,
32
+ systemNote: [DESK_SYSTEM_NOTE, `You are ${agentName}.`, options.systemNote?.trim()].filter(Boolean).join("\n"),
33
+ customTools: async (thread) => {
34
+ const tools = [...memorySearchTools(options.dataDir)];
35
+ if (runtime.api && runtime.botUserId) {
36
+ tools.push(...peerTools({
37
+ api: runtime.api,
38
+ channel: thread.channel,
39
+ threadTs: thread.threadTs,
40
+ threadKey: thread.key,
41
+ botUserId: runtime.botUserId,
42
+ peerBotUserId,
43
+ guard,
44
+ }));
45
+ }
46
+ if (userTools)
47
+ tools.push(...(await userTools(thread)));
48
+ return tools;
49
+ },
50
+ hooks: {
51
+ beforeRun: async (ctx) => {
52
+ const injected = smartInsert({ dataDir: options.dataDir, agentName, query: ctx.text });
53
+ const withMemory = injected ? `${injected}\n\n---\n\n${ctx.text}` : ctx.text;
54
+ const replaced = await userHooks?.beforeRun?.({ ...ctx, text: withMemory });
55
+ return typeof replaced === "string" ? replaced : withMemory;
56
+ },
57
+ afterRun: userHooks?.afterRun,
58
+ onStart: async (info) => {
59
+ runtime.api = info.api;
60
+ runtime.botUserId = info.botUserId;
61
+ if (pruneDays > 0) {
62
+ const result = pruneOldThreads(options.dataDir, pruneDays);
63
+ if (result.removed.length) {
64
+ console.log(`[pi-mom-desk] pruned ${result.removed.length} old thread workspace(s), kept ${result.kept}`);
65
+ }
66
+ }
67
+ await userHooks?.onStart?.(info);
68
+ },
69
+ },
70
+ };
71
+ }
72
+ /** Start a desk bot (wizard-central / wizard-workers share this entry). */
73
+ export function createDeskBot(options) {
74
+ return createSlackBot(deskBotOptions(options));
75
+ }
package/dist/index.d.ts CHANGED
@@ -3,4 +3,12 @@ export type { Command, CommandContext, RunContext, SlackBotHandle, SlackBotHooks
3
3
  export { DEFAULT_SYSTEM_NOTE } from "./agent.ts";
4
4
  export type { RunResult, ThreadInfo } from "./agent.ts";
5
5
  export { configFromEnv, configsFromEnv, loadEnvFile } from "./config.ts";
6
+ export { createDeskBot, deskBotOptions, DESK_SYSTEM_NOTE } from "./desk.ts";
7
+ export type { DeskOptions } from "./desk.ts";
8
+ export { deskConfigFromEnv } from "./desk-config.ts";
9
+ export type { DeskCliConfig } from "./desk-config.ts";
10
+ export { loadMemoryChunks, memorySearchTools, readAgentMd, smartInsert, updateMemory, MAX_MEMORY_INSERT_CHARS, MAX_AGENT_CHARS, } from "./memory.ts";
11
+ export type { MemoryChunk, SmartInsertOptions } from "./memory.ts";
12
+ export { createPeerAskGuard, peerTools, fetchThreadReplies } from "./peer.ts";
13
+ export { pruneOldThreads } from "./prune.ts";
6
14
  export { VERSION } from "./version.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
1
  export { createSlackBot, recordCrash, RESUME_PROMPT } from "./bot.js";
2
2
  export { DEFAULT_SYSTEM_NOTE } from "./agent.js";
3
3
  export { configFromEnv, configsFromEnv, loadEnvFile } from "./config.js";
4
+ export { createDeskBot, deskBotOptions, DESK_SYSTEM_NOTE } from "./desk.js";
5
+ export { deskConfigFromEnv } from "./desk-config.js";
6
+ export { loadMemoryChunks, memorySearchTools, readAgentMd, smartInsert, updateMemory, MAX_MEMORY_INSERT_CHARS, MAX_AGENT_CHARS, } from "./memory.js";
7
+ export { createPeerAskGuard, peerTools, fetchThreadReplies } from "./peer.js";
8
+ export { pruneOldThreads } from "./prune.js";
4
9
  export { VERSION } from "./version.js";
@@ -0,0 +1,58 @@
1
+ import { Type } from "typebox";
2
+ /** Soft cap for AGENT.md injected into a run (~2k tokens). */
3
+ export declare const MAX_AGENT_CHARS = 8000;
4
+ /** Hard cap for MEMORY chunks injected into a run (~1.5k tokens). */
5
+ export declare const MAX_MEMORY_INSERT_CHARS = 6000;
6
+ /** Max chunks returned by smart_insert. */
7
+ export declare const SMART_INSERT_TOP_K = 5;
8
+ /** Max chunks returned by memory_search. */
9
+ export declare const SEARCH_TOP_K = 8;
10
+ /** Max characters per memory note written by memory_update. */
11
+ export declare const MAX_NOTE_CHARS = 2000;
12
+ export interface MemoryChunk {
13
+ id: string;
14
+ title: string;
15
+ text: string;
16
+ source: string;
17
+ }
18
+ export interface SmartInsertOptions {
19
+ dataDir: string;
20
+ agentName?: string;
21
+ /** User / thread text used to retrieve MEMORY chunks. */
22
+ query: string;
23
+ maxAgentChars?: number;
24
+ maxMemoryChars?: number;
25
+ topK?: number;
26
+ }
27
+ export declare function agentMdPath(dataDir: string): string;
28
+ export declare function memoryDir(dataDir: string): string;
29
+ export declare function memoryMdPath(dataDir: string): string;
30
+ /** Split markdown into chunks on ## headings (or the whole file if none). */
31
+ export declare function chunkMarkdown(source: string, text: string): MemoryChunk[];
32
+ /** Load all MEMORY chunks from MEMORY.md and memory/*.md. */
33
+ export declare function loadMemoryChunks(dataDir: string): MemoryChunk[];
34
+ /** Read AGENT.md, truncated to maxChars. */
35
+ export declare function readAgentMd(dataDir: string, maxChars?: number): string;
36
+ /** Lowercase alphanumeric tokens, stopwords removed. */
37
+ export declare function tokenize(text: string): string[];
38
+ /** Lexical overlap score: sum of query-term hits (with light title boost). */
39
+ export declare function scoreChunk(queryTokens: string[], chunk: MemoryChunk): number;
40
+ export declare function rankChunks(query: string, chunks: MemoryChunk[], topK: number): MemoryChunk[];
41
+ /** Pack chunks under a character budget, preserving rank order. */
42
+ export declare function packChunks(chunks: MemoryChunk[], maxChars: number): MemoryChunk[];
43
+ /**
44
+ * Build the shared context block for a run: identity + AGENT.md (bounded) + relevant MEMORY only.
45
+ */
46
+ export declare function smartInsert(options: SmartInsertOptions): string;
47
+ /** Append a short dated note under memory/. Returns the file path relative to dataDir. */
48
+ export declare function updateMemory(dataDir: string, note: string, title?: string): string;
49
+ export declare function memorySearchTools(dataDir: string): ((import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
50
+ query: Type.TString;
51
+ }>, {
52
+ hits: number;
53
+ }, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>) | (import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
54
+ note: Type.TString;
55
+ title: Type.TOptional<Type.TString>;
56
+ }>, {
57
+ path: string;
58
+ }, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>))[];
package/dist/memory.js ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Shared agent memory: AGENT.md + a light MEMORY store with lexical smart_insert.
3
+ * Never dumps the whole store into the prompt; only top-k chunks under a hard size cap.
4
+ */
5
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { defineTool } from "@earendil-works/pi-coding-agent";
8
+ import { Type } from "typebox";
9
+ /** Soft cap for AGENT.md injected into a run (~2k tokens). */
10
+ export const MAX_AGENT_CHARS = 8_000;
11
+ /** Hard cap for MEMORY chunks injected into a run (~1.5k tokens). */
12
+ export const MAX_MEMORY_INSERT_CHARS = 6_000;
13
+ /** Max chunks returned by smart_insert. */
14
+ export const SMART_INSERT_TOP_K = 5;
15
+ /** Max chunks returned by memory_search. */
16
+ export const SEARCH_TOP_K = 8;
17
+ /** Max characters per memory note written by memory_update. */
18
+ export const MAX_NOTE_CHARS = 2_000;
19
+ export function agentMdPath(dataDir) {
20
+ return join(dataDir, "AGENT.md");
21
+ }
22
+ export function memoryDir(dataDir) {
23
+ return join(dataDir, "memory");
24
+ }
25
+ export function memoryMdPath(dataDir) {
26
+ return join(dataDir, "MEMORY.md");
27
+ }
28
+ /** Split markdown into chunks on ## headings (or the whole file if none). */
29
+ export function chunkMarkdown(source, text) {
30
+ const trimmed = text.replace(/\r\n/g, "\n").trim();
31
+ if (!trimmed)
32
+ return [];
33
+ let parts = trimmed.split(/(?=^## )/m).map((p) => p.trim()).filter(Boolean);
34
+ // Drop a leading H1-only preamble when real ## sections follow.
35
+ if (parts.length > 1 && !parts[0].startsWith("## ")) {
36
+ const body = parts[0].replace(/^#\s[^\n]*\n?/, "").trim();
37
+ if (!body)
38
+ parts = parts.slice(1);
39
+ }
40
+ return parts.map((part, i) => {
41
+ const first = part.split("\n")[0] ?? "";
42
+ const title = first.startsWith("## ") ? first.slice(3).trim() : (parts.length === 1 ? source : `section-${i + 1}`);
43
+ const id = `${source}#${slug(title) || String(i + 1)}`;
44
+ return { id, title, text: part, source };
45
+ });
46
+ }
47
+ function slug(s) {
48
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 80);
49
+ }
50
+ /** Load all MEMORY chunks from MEMORY.md and memory/*.md. */
51
+ export function loadMemoryChunks(dataDir) {
52
+ const out = [];
53
+ const monolith = memoryMdPath(dataDir);
54
+ if (existsSync(monolith)) {
55
+ out.push(...chunkMarkdown("MEMORY.md", readFileSync(monolith, "utf8")));
56
+ }
57
+ const dir = memoryDir(dataDir);
58
+ if (existsSync(dir)) {
59
+ for (const name of readdirSync(dir).filter((n) => n.endsWith(".md")).sort()) {
60
+ out.push(...chunkMarkdown(`memory/${name}`, readFileSync(join(dir, name), "utf8")));
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ /** Read AGENT.md, truncated to maxChars. */
66
+ export function readAgentMd(dataDir, maxChars = MAX_AGENT_CHARS) {
67
+ const path = agentMdPath(dataDir);
68
+ if (!existsSync(path))
69
+ return "";
70
+ const text = readFileSync(path, "utf8").trim();
71
+ if (text.length <= maxChars)
72
+ return text;
73
+ return `${text.slice(0, maxChars)}\n\n…[AGENT.md truncated]`;
74
+ }
75
+ const STOP = new Set([
76
+ "a", "an", "the", "and", "or", "to", "of", "in", "on", "for", "is", "are", "was", "were", "be", "with", "at", "by",
77
+ "it", "this", "that", "from", "as", "if", "not", "but", "so", "do", "does", "did", "have", "has", "had", "will",
78
+ "can", "could", "would", "should", "i", "you", "we", "they", "he", "she", "my", "your", "our", "me", "us",
79
+ "le", "la", "les", "un", "une", "des", "du", "de", "et", "ou", "pour", "dans", "sur", "avec", "pas", "qui", "que",
80
+ "est", "sont", "une", "ce", "cette", "ces", "il", "elle", "nous", "vous", "je", "tu", "mon", "ton", "son",
81
+ ]);
82
+ /** Lowercase alphanumeric tokens, stopwords removed. */
83
+ export function tokenize(text) {
84
+ return text
85
+ .toLowerCase()
86
+ .split(/[^a-z0-9àâäéèêëïîôùûüç_+.-]+/i)
87
+ .map((t) => t.trim())
88
+ .filter((t) => t.length >= 2 && !STOP.has(t));
89
+ }
90
+ /** Lexical overlap score: sum of query-term hits (with light title boost). */
91
+ export function scoreChunk(queryTokens, chunk) {
92
+ if (!queryTokens.length)
93
+ return 0;
94
+ const titleToks = new Set(tokenize(chunk.title));
95
+ const bodyToks = tokenize(chunk.text);
96
+ const bodyCount = new Map();
97
+ for (const t of bodyToks)
98
+ bodyCount.set(t, (bodyCount.get(t) ?? 0) + 1);
99
+ let score = 0;
100
+ for (const t of queryTokens) {
101
+ if (titleToks.has(t))
102
+ score += 3;
103
+ const n = bodyCount.get(t) ?? 0;
104
+ if (n)
105
+ score += Math.min(2, 1 + Math.log2(n));
106
+ }
107
+ return score;
108
+ }
109
+ export function rankChunks(query, chunks, topK) {
110
+ const q = tokenize(query);
111
+ if (!q.length || !chunks.length)
112
+ return [];
113
+ return chunks
114
+ .map((chunk) => ({ chunk, score: scoreChunk(q, chunk) }))
115
+ .filter((x) => x.score > 0)
116
+ .sort((a, b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id))
117
+ .slice(0, topK)
118
+ .map((x) => x.chunk);
119
+ }
120
+ /** Pack chunks under a character budget, preserving rank order. */
121
+ export function packChunks(chunks, maxChars) {
122
+ const out = [];
123
+ let used = 0;
124
+ for (const chunk of chunks) {
125
+ const cost = chunk.text.length + 24;
126
+ if (out.length && used + cost > maxChars)
127
+ break;
128
+ if (!out.length && cost > maxChars) {
129
+ out.push({ ...chunk, text: `${chunk.text.slice(0, Math.max(0, maxChars - 40))}\n…[truncated]` });
130
+ break;
131
+ }
132
+ out.push(chunk);
133
+ used += cost;
134
+ }
135
+ return out;
136
+ }
137
+ /**
138
+ * Build the shared context block for a run: identity + AGENT.md (bounded) + relevant MEMORY only.
139
+ */
140
+ export function smartInsert(options) {
141
+ const { dataDir, agentName, query, maxAgentChars = MAX_AGENT_CHARS, maxMemoryChars = MAX_MEMORY_INSERT_CHARS, topK = SMART_INSERT_TOP_K, } = options;
142
+ const parts = [];
143
+ if (agentName?.trim())
144
+ parts.push(`You are ${agentName.trim()}.`);
145
+ const agent = readAgentMd(dataDir, maxAgentChars);
146
+ if (agent)
147
+ parts.push(`AGENT.md:\n${agent}`);
148
+ const ranked = rankChunks(query, loadMemoryChunks(dataDir), topK);
149
+ const packed = packChunks(ranked, maxMemoryChars);
150
+ if (packed.length) {
151
+ parts.push(`Relevant memory (smart_insert, ${packed.length} chunk(s); use memory_search if you need more):\n`
152
+ + packed.map((c) => `### ${c.title}\n${c.text}`).join("\n\n"));
153
+ }
154
+ return parts.join("\n\n");
155
+ }
156
+ /** Append a short dated note under memory/. Returns the file path relative to dataDir. */
157
+ export function updateMemory(dataDir, note, title) {
158
+ const text = note.trim();
159
+ if (!text)
160
+ throw new Error("note is empty");
161
+ if (text.length > MAX_NOTE_CHARS)
162
+ throw new Error(`note too long (max ${MAX_NOTE_CHARS} chars)`);
163
+ const dir = memoryDir(dataDir);
164
+ mkdirSync(dir, { recursive: true });
165
+ const day = new Date().toISOString().slice(0, 10);
166
+ const heading = (title?.trim() || "note").slice(0, 80);
167
+ const file = join(dir, `${day}.md`);
168
+ const block = `\n## ${heading}\n${text}\n`;
169
+ if (existsSync(file))
170
+ appendFileSync(file, block);
171
+ else
172
+ writeFileSync(file, `# Memory ${day}\n${block}`);
173
+ return `memory/${day}.md`;
174
+ }
175
+ export function memorySearchTools(dataDir) {
176
+ return [
177
+ defineTool({
178
+ name: "memory_search",
179
+ label: "Search shared memory",
180
+ description: "Search the agent's shared MEMORY store (not the Slack thread). Returns only the most relevant short chunks. Use when smart_insert was not enough.",
181
+ promptSnippet: "memory_search: find relevant notes in shared MEMORY",
182
+ parameters: Type.Object({
183
+ query: Type.String({ description: "Keywords or short question" }),
184
+ }),
185
+ execute: async (_id, { query }) => {
186
+ const packed = packChunks(rankChunks(query, loadMemoryChunks(dataDir), SEARCH_TOP_K), MAX_MEMORY_INSERT_CHARS);
187
+ const text = packed.length
188
+ ? packed.map((c) => `### ${c.title} (${c.source})\n${c.text}`).join("\n\n")
189
+ : "No matching memory.";
190
+ return { content: [{ type: "text", text }], details: { hits: packed.length } };
191
+ },
192
+ }),
193
+ defineTool({
194
+ name: "memory_update",
195
+ label: "Update shared memory",
196
+ description: "Append a short durable note to shared MEMORY (facts, access details, decisions). Keep it brief. Do not dump logs or secrets.",
197
+ promptSnippet: "memory_update: append a short note to shared MEMORY",
198
+ parameters: Type.Object({
199
+ note: Type.String({ description: "Short fact to remember" }),
200
+ title: Type.Optional(Type.String({ description: "Short heading for the note" })),
201
+ }),
202
+ execute: async (_id, { note, title }) => {
203
+ const rel = updateMemory(dataDir, note, title);
204
+ return { content: [{ type: "text", text: `Saved to ${rel}.` }], details: { path: rel } };
205
+ },
206
+ }),
207
+ ];
208
+ }
package/dist/peer.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { Type } from "typebox";
2
+ import type { SlackApi } from "./slack.ts";
3
+ /** Max ask_peer calls per thread within the window. */
4
+ export declare const MAX_PEER_ASKS = 3;
5
+ /** Sliding window for the anti-loop guard (ms). */
6
+ export declare const PEER_ASK_WINDOW_MS: number;
7
+ /** Default wait when ask_peer waits for a reply. */
8
+ export declare const DEFAULT_PEER_WAIT_MS = 120000;
9
+ /** Poll interval while waiting for a peer reply. */
10
+ export declare const PEER_POLL_MS = 2500;
11
+ /** Max messages returned by thread_read. */
12
+ export declare const MAX_THREAD_MESSAGES = 50;
13
+ export interface ThreadMessage {
14
+ ts: string;
15
+ user: string;
16
+ text: string;
17
+ bot: boolean;
18
+ }
19
+ export interface PeerAskGuard {
20
+ /** Returns false when the thread has hit the ask_peer limit. */
21
+ allow(threadKey: string): boolean;
22
+ /** Record a successful ask_peer post. */
23
+ record(threadKey: string): void;
24
+ }
25
+ /** In-memory anti-loop guard for ask_peer. */
26
+ export declare function createPeerAskGuard(maxAsks?: number, windowMs?: number): PeerAskGuard;
27
+ export declare function fetchThreadReplies(api: SlackApi, channel: string, threadTs: string, opts?: {
28
+ limit?: number;
29
+ oldest?: string;
30
+ }): Promise<ThreadMessage[]>;
31
+ export declare function formatThreadMessages(messages: ThreadMessage[]): string;
32
+ export declare function peerTools(options: {
33
+ api: SlackApi;
34
+ channel: string;
35
+ threadTs: string;
36
+ threadKey: string;
37
+ botUserId: string;
38
+ peerBotUserId?: string;
39
+ guard: PeerAskGuard;
40
+ waitMs?: number;
41
+ sleep?: (ms: number) => Promise<void>;
42
+ now?: () => number;
43
+ }): ((import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
44
+ limit: Type.TOptional<Type.TNumber>;
45
+ oldest: Type.TOptional<Type.TString>;
46
+ }>, {
47
+ count: number;
48
+ }, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>) | (import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
49
+ question: Type.TString;
50
+ wait_seconds: Type.TOptional<Type.TNumber>;
51
+ }>, {
52
+ ok: boolean;
53
+ limited: boolean;
54
+ count: number;
55
+ timeout: boolean;
56
+ }, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>))[];
package/dist/peer.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Cross-agent helpers: read a Slack thread (including other bots) and ask a peer bot in the same thread.
3
+ */
4
+ import { defineTool } from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
6
+ /** Max ask_peer calls per thread within the window. */
7
+ export const MAX_PEER_ASKS = 3;
8
+ /** Sliding window for the anti-loop guard (ms). */
9
+ export const PEER_ASK_WINDOW_MS = 15 * 60_000;
10
+ /** Default wait when ask_peer waits for a reply. */
11
+ export const DEFAULT_PEER_WAIT_MS = 120_000;
12
+ /** Poll interval while waiting for a peer reply. */
13
+ export const PEER_POLL_MS = 2_500;
14
+ /** Max messages returned by thread_read. */
15
+ export const MAX_THREAD_MESSAGES = 50;
16
+ /** In-memory anti-loop guard for ask_peer. */
17
+ export function createPeerAskGuard(maxAsks = MAX_PEER_ASKS, windowMs = PEER_ASK_WINDOW_MS) {
18
+ const hits = new Map();
19
+ const prune = (key, now) => {
20
+ const list = (hits.get(key) ?? []).filter((t) => now - t < windowMs);
21
+ hits.set(key, list);
22
+ return list;
23
+ };
24
+ return {
25
+ allow(threadKey) {
26
+ return prune(threadKey, Date.now()).length < maxAsks;
27
+ },
28
+ record(threadKey) {
29
+ const now = Date.now();
30
+ const list = prune(threadKey, now);
31
+ list.push(now);
32
+ hits.set(threadKey, list);
33
+ },
34
+ };
35
+ }
36
+ export async function fetchThreadReplies(api, channel, threadTs, opts = {}) {
37
+ const limit = Math.min(Math.max(opts.limit ?? 30, 1), MAX_THREAD_MESSAGES);
38
+ const messages = [];
39
+ let cursor;
40
+ do {
41
+ const r = await api.web.conversations.replies({
42
+ channel,
43
+ ts: threadTs,
44
+ limit,
45
+ cursor,
46
+ oldest: opts.oldest,
47
+ inclusive: true,
48
+ });
49
+ for (const m of r.messages ?? []) {
50
+ const raw = m;
51
+ const text = typeof raw.text === "string" ? raw.text : "";
52
+ const user = typeof raw.user === "string" ? raw.user : typeof raw.bot_id === "string" ? raw.bot_id : "?";
53
+ messages.push({
54
+ ts: String(raw.ts ?? ""),
55
+ user,
56
+ text,
57
+ bot: Boolean(raw.bot_id) || raw.subtype === "bot_message",
58
+ });
59
+ }
60
+ cursor = r.response_metadata?.next_cursor || undefined;
61
+ if (messages.length >= limit)
62
+ break;
63
+ } while (cursor);
64
+ return messages.slice(-limit);
65
+ }
66
+ export function formatThreadMessages(messages) {
67
+ if (!messages.length)
68
+ return "No messages in this thread.";
69
+ return messages
70
+ .map((m) => {
71
+ const who = m.bot ? `bot:${m.user}` : m.user;
72
+ return `[${m.ts}] ${who}: ${m.text || "(empty)"}`;
73
+ })
74
+ .join("\n");
75
+ }
76
+ export function peerTools(options) {
77
+ const sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
78
+ const now = options.now ?? Date.now;
79
+ const waitMs = options.waitMs ?? DEFAULT_PEER_WAIT_MS;
80
+ return [
81
+ defineTool({
82
+ name: "thread_read",
83
+ label: "Read Slack thread",
84
+ description: "Read recent messages in this Slack thread, including other bots. Use after a peer replies, or to catch up without asking the human to paste.",
85
+ promptSnippet: "thread_read: read this Slack thread including peer bots",
86
+ parameters: Type.Object({
87
+ limit: Type.Optional(Type.Number({ description: `Max messages (1-${MAX_THREAD_MESSAGES})` })),
88
+ oldest: Type.Optional(Type.String({ description: "Only messages at or after this Slack ts" })),
89
+ }),
90
+ execute: async (_id, { limit, oldest }) => {
91
+ const messages = await fetchThreadReplies(options.api, options.channel, options.threadTs, { limit, oldest });
92
+ return { content: [{ type: "text", text: formatThreadMessages(messages) }], details: { count: messages.length } };
93
+ },
94
+ }),
95
+ defineTool({
96
+ name: "ask_peer",
97
+ label: "Ask peer bot",
98
+ description: "Mention the peer desk bot in this thread with a clear question, then wait briefly for its reply. Use when you need information or action only the peer can do. Do not loop: ask once with a complete question.",
99
+ promptSnippet: "ask_peer: mention the peer bot in this thread and wait for its reply",
100
+ parameters: Type.Object({
101
+ question: Type.String({ description: "Question for the peer, complete and self-contained" }),
102
+ wait_seconds: Type.Optional(Type.Number({ description: "Seconds to wait for a reply (default 120, max 300)" })),
103
+ }),
104
+ execute: async (_id, { question, wait_seconds }) => {
105
+ const empty = { ok: false, limited: false, count: 0, timeout: false };
106
+ const peer = options.peerBotUserId?.trim();
107
+ if (!peer) {
108
+ return {
109
+ content: [{ type: "text", text: "No peer bot configured (PI_SLACK_PEER_BOT_USER_ID)." }],
110
+ details: empty,
111
+ };
112
+ }
113
+ const q = question.trim();
114
+ if (!q)
115
+ throw new Error("question is empty");
116
+ if (!options.guard.allow(options.threadKey)) {
117
+ return {
118
+ content: [{ type: "text", text: `ask_peer limit reached (${MAX_PEER_ASKS} per ${Math.round(PEER_ASK_WINDOW_MS / 60_000)} min). Read the thread or wait.` }],
119
+ details: { ...empty, limited: true },
120
+ };
121
+ }
122
+ const before = await fetchThreadReplies(options.api, options.channel, options.threadTs, { limit: 5 });
123
+ const afterTs = before.at(-1)?.ts ?? options.threadTs;
124
+ await options.api.post(options.channel, options.threadTs, `<@${peer}> ${q}`);
125
+ options.guard.record(options.threadKey);
126
+ const budget = Math.min(Math.max((wait_seconds ?? waitMs / 1000) * 1000, 5_000), 300_000);
127
+ const deadline = now() + budget;
128
+ while (now() < deadline) {
129
+ await sleep(PEER_POLL_MS);
130
+ const all = await fetchThreadReplies(options.api, options.channel, options.threadTs, {
131
+ limit: MAX_THREAD_MESSAGES,
132
+ oldest: afterTs,
133
+ });
134
+ // Peer's chat.postMessage shows up with user = peer bot user id.
135
+ const chosen = all.filter((m) => m.ts > afterTs && m.user === peer && m.user !== options.botUserId);
136
+ if (chosen.length) {
137
+ return {
138
+ content: [{ type: "text", text: `Peer replied:\n${formatThreadMessages(chosen)}` }],
139
+ details: { ok: true, limited: false, count: chosen.length, timeout: false },
140
+ };
141
+ }
142
+ }
143
+ return {
144
+ content: [{
145
+ type: "text",
146
+ text: "No peer reply within the wait window. Use thread_read later, or ask the human to mention the peer again.",
147
+ }],
148
+ details: { ...empty, timeout: true },
149
+ };
150
+ },
151
+ }),
152
+ ];
153
+ }
@@ -0,0 +1,9 @@
1
+ export interface PruneResult {
2
+ removed: string[];
3
+ kept: number;
4
+ }
5
+ /**
6
+ * Remove `dataDir/threads/<key>` directories whose mtime is older than `maxAgeDays`.
7
+ * Never touches AGENT.md, MEMORY, or other top-level data.
8
+ */
9
+ export declare function pruneOldThreads(dataDir: string, maxAgeDays: number, now?: number): PruneResult;
package/dist/prune.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Delete inactive thread workspaces under dataDir/threads to avoid unbounded disk growth.
3
+ */
4
+ import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ /**
7
+ * Remove `dataDir/threads/<key>` directories whose mtime is older than `maxAgeDays`.
8
+ * Never touches AGENT.md, MEMORY, or other top-level data.
9
+ */
10
+ export function pruneOldThreads(dataDir, maxAgeDays, now = Date.now()) {
11
+ if (!Number.isFinite(maxAgeDays) || maxAgeDays <= 0)
12
+ throw new Error("maxAgeDays must be a positive number");
13
+ const root = join(dataDir, "threads");
14
+ if (!existsSync(root))
15
+ return { removed: [], kept: 0 };
16
+ const cutoff = now - maxAgeDays * 86_400_000;
17
+ const removed = [];
18
+ let kept = 0;
19
+ for (const name of readdirSync(root)) {
20
+ const path = join(root, name);
21
+ let st;
22
+ try {
23
+ st = statSync(path);
24
+ }
25
+ catch {
26
+ continue;
27
+ }
28
+ if (!st.isDirectory()) {
29
+ kept += 1;
30
+ continue;
31
+ }
32
+ if (st.mtimeMs < cutoff) {
33
+ rmSync(path, { recursive: true, force: true });
34
+ removed.push(name);
35
+ }
36
+ else {
37
+ kept += 1;
38
+ }
39
+ }
40
+ return { removed, kept };
41
+ }
package/dist/slack.d.ts CHANGED
@@ -4,6 +4,8 @@ export interface SlackFile {
4
4
  mimetype: string;
5
5
  size: number;
6
6
  url: string;
7
+ /** Metadata lookup failed; report the attachment instead of silently dropping it. */
8
+ error?: string;
7
9
  }
8
10
  export interface IncomingMessage {
9
11
  channel: string;
@@ -16,6 +18,8 @@ export interface IncomingMessage {
16
18
  isDirect: boolean;
17
19
  /** The bot was mentioned (always false in a direct message). */
18
20
  mentioned?: boolean;
21
+ /** Message came from another Slack app/bot (peer desk wake-up). */
22
+ fromBot?: boolean;
19
23
  files: SlackFile[];
20
24
  }
21
25
  export type Handler = (msg: IncomingMessage) => Promise<void>;
@@ -38,6 +42,8 @@ export declare class SlackApi {
38
42
  unreact(channel: string, ts: string, name: string): Promise<void>;
39
43
  /** Uploads a file into a thread (files:write). */
40
44
  upload(channel: string, threadTs: string, file: Buffer, filename: string, comment?: string): Promise<void>;
45
+ /** Socket Mode may provide only a file ID (file_access=check_file_info). Resolve it before downloading. */
46
+ resolveFiles(files: unknown): Promise<SlackFile[]>;
41
47
  /** Downloads a private Slack file with the bot token (files:read). */
42
48
  download(url: string, maxBytes: number): Promise<Buffer>;
43
49
  /** Display name of a user (users:read), cached. Falls back to the ID. */
package/dist/slack.js CHANGED
@@ -89,6 +89,35 @@ export class SlackApi {
89
89
  async upload(channel, threadTs, file, filename, comment) {
90
90
  await this.web.filesUploadV2({ channel_id: channel, thread_ts: threadTs, file, filename, ...(comment ? { initial_comment: comment } : {}) });
91
91
  }
92
+ /** Socket Mode may provide only a file ID (file_access=check_file_info). Resolve it before downloading. */
93
+ async resolveFiles(files) {
94
+ if (!Array.isArray(files))
95
+ return [];
96
+ const downloadUrl = (file) => [file.url_private_download, file.url_private]
97
+ .find((url) => typeof url === "string" && Boolean(url.trim()));
98
+ return Promise.all(files.map(async (raw) => {
99
+ const f = raw && typeof raw === "object" ? raw : {};
100
+ let info = f;
101
+ try {
102
+ if (!downloadUrl(f)) {
103
+ if (typeof f.id !== "string")
104
+ throw new Error("Slack supplied no file ID or download URL");
105
+ const response = await this.web.files.info({ file: f.id });
106
+ if (!response.file)
107
+ throw new Error("Slack returned no file metadata");
108
+ info = response.file;
109
+ }
110
+ const url = downloadUrl(info);
111
+ if (!url)
112
+ throw new Error("Slack returned no download URL; check file access and files:read");
113
+ return { name: String(info.name ?? f.name ?? "file"), mimetype: String(info.mimetype ?? ""), size: Number(info.size ?? 0), url };
114
+ }
115
+ catch (e) {
116
+ const code = slackError(e);
117
+ return { name: String(f.name ?? f.id ?? "file"), mimetype: "", size: 0, url: "", error: code ? `Slack file lookup failed (${code}); check file access and files:read` : "Slack file metadata could not be resolved; check file access and files:read" };
118
+ }
119
+ }));
120
+ }
92
121
  /** Downloads a private Slack file with the bot token (files:read). */
93
122
  async download(url, maxBytes) {
94
123
  if (!isSlackFileUrl(url))
@@ -196,31 +225,51 @@ export class SlackBot {
196
225
  const e = body?.event;
197
226
  if (process.env.PI_SLACK_DEBUG)
198
227
  console.log(`[slack] event type=${e?.type} channel_type=${e?.channel_type} subtype=${e?.subtype ?? "-"}`);
199
- // file_share is a normal message with attachments; every other subtype (edits, joins, bots) is ignored.
200
- if (!e || e.bot_id || (e.subtype && e.subtype !== "file_share") || !e.user || e.user === this.botUserId || typeof e.text !== "string")
228
+ if (!e || e.user === this.botUserId)
229
+ return;
230
+ const rawText = typeof e.text === "string" ? e.text : "";
231
+ const hasFiles = Array.isArray(e.files);
232
+ if (typeof e.text !== "string" && !hasFiles)
233
+ return;
234
+ const mention = `<@${this.botUserId}>`;
235
+ const mentioned = e.type === "app_mention" || (Boolean(this.botUserId) && rawText.includes(mention));
236
+ const fromBot = Boolean(e.bot_id) || e.subtype === "bot_message";
237
+ // Other bots are ignored unless they mention us (desk peer wake-up). Humans: file_share ok; other subtypes ignored.
238
+ if (fromBot) {
239
+ if (!mentioned || !e.user)
240
+ return;
241
+ }
242
+ else if ((e.subtype && e.subtype !== "file_share") || !e.user) {
201
243
  return;
244
+ }
202
245
  const isDirect = e.channel_type === "im";
203
246
  const threadTs = e.thread_ts ?? e.ts;
204
- const mention = `<@${this.botUserId}>`;
205
- const mentioned = e.type === "app_mention" || e.text.includes(mention);
206
247
  const inActiveThread = Boolean(e.thread_ts) && this.activeThreads.has(`${e.channel}:${e.thread_ts}`);
207
248
  // In channels, a mention arrives twice (app_mention and message): only app_mention counts, unless the thread
208
- // is already active, where a plain reply is enough.
209
- if (e.type === "message" && !isDirect && !inActiveThread)
249
+ // is already active, where a plain reply is enough. Peer bot wake-ups are mention-only.
250
+ if (e.type === "message" && !isDirect && !inActiveThread && !fromBot)
210
251
  return;
211
- if (!(mentioned || isDirect || inActiveThread))
252
+ if (fromBot && e.type === "message" && mentioned) {
253
+ // Prefer app_mention when Slack sends both; still accept message if only that arrives.
254
+ }
255
+ else if (!(mentioned || isDirect || inActiveThread)) {
212
256
  return;
257
+ }
213
258
  if (!this.claim(e.channel, e.ts))
214
259
  return;
215
- const text = decodeEntities(e.text.split(mention).join("")).trim();
216
- const files = Array.isArray(e.files)
217
- ? e.files
218
- // biome-ignore lint/suspicious/noExplicitAny: untyped Slack payload
219
- .filter((f) => f && typeof f.url_private === "string")
220
- // biome-ignore lint/suspicious/noExplicitAny: untyped Slack payload
221
- .map((f) => ({ name: String(f.name ?? "file"), mimetype: String(f.mimetype ?? ""), size: Number(f.size ?? 0), url: f.url_private }))
222
- : [];
223
- await this.handler({ channel: e.channel, threadTs, ts: e.ts, user: e.user, text, isDirect, mentioned, files }).catch((err) => console.error("[slack] handler error", err));
260
+ const text = decodeEntities(rawText.split(mention).join("")).trim();
261
+ const files = fromBot ? [] : await this.api.resolveFiles(e.files);
262
+ await this.handler({
263
+ channel: e.channel,
264
+ threadTs,
265
+ ts: e.ts,
266
+ user: e.user,
267
+ text,
268
+ isDirect,
269
+ mentioned,
270
+ ...(fromBot ? { fromBot: true } : {}),
271
+ files,
272
+ }).catch((err) => console.error("[slack] handler error", err));
224
273
  }
225
274
  /**
226
275
  * Slack closes Socket Mode connections regularly (about once an hour, and on network hiccups); the client reconnects
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-mom-slack",
3
- "version": "0.1.6",
4
- "description": "Run the pi coding agent in Slack: one pi session per thread, in one command.",
3
+ "version": "0.2.1",
4
+ "description": "Run the pi coding agent in Slack: one pi session per thread, in one command. Desk mode for named ops agents with shared MEMORY.",
5
5
  "license": "MIT",
6
6
  "author": "tsua0002",
7
7
  "type": "module",
@@ -20,7 +20,8 @@
20
20
  "mom"
21
21
  ],
22
22
  "bin": {
23
- "pi-mom-slack": "dist/cli.js"
23
+ "pi-mom-slack": "dist/cli.js",
24
+ "pi-mom-desk": "dist/desk-cli.js"
24
25
  },
25
26
  "main": "./dist/index.js",
26
27
  "types": "./dist/index.d.ts",
@@ -46,11 +47,12 @@
46
47
  "check": "tsc --noEmit",
47
48
  "test": "vitest run",
48
49
  "start": "node --experimental-strip-types src/cli.ts",
50
+ "prepare": "npm run build",
49
51
  "prepack": "npm run build"
50
52
  },
51
53
  "dependencies": {
52
- "@earendil-works/pi-ai": "1.8.0",
53
- "@earendil-works/pi-coding-agent": "1.8.0",
54
+ "@earendil-works/pi-ai": "1.5.2",
55
+ "@earendil-works/pi-coding-agent": "1.5.2",
54
56
  "@slack/socket-mode": "3.1.1",
55
57
  "@slack/web-api": "8.3.0",
56
58
  "typebox": "1.3.27"