omni-notify-mcp 1.3.460 → 1.3.463

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.
@@ -15,7 +15,7 @@ import { homedir } from "os";
15
15
  import { join } from "path";
16
16
  import { splitForNotify } from "./chunk.js";
17
17
  import { choicesOf, StreamedReply } from "./messaging/messenger.js";
18
- import { appendEvent, archiveConversation, conversationRefusal, openConversation, readConversation, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, rootFolder, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversationOwner.js";
18
+ import { appendEvent, archiveConversation, conversationRefusal, openConversation, readConversation, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, rootFolder, routeAsk, stopTargetOf, sendToConversation, startConversation, turnInFlight, updateConversation, } from "./gateway/conversationOwner.js";
19
19
  import { conversationOwner } from "./gateway/conversationOwner.js";
20
20
  import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
21
21
  import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
@@ -29,7 +29,7 @@ async function endNewest(key, _platform, end) {
29
29
  const stay = this.allOf(key).length;
30
30
  return stay === 0 ? "🆕 New conversation. Your next ! message starts it." : `🆕 Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`;
31
31
  }
32
- const stoppedOfMany = (stopped, others) => others === 0 ? "⏹ Conversation ended. Your next ! message opens a new one." : `⏹ Conversation ${stopped.id.slice(0, 8)} ended. ${others} other conversation${others === 1 ? " stays" : "s stay"} open.`;
32
+ const stoppedOfMany = ([stopped], others) => others === 0 ? "⏹ Conversation ended. Your next ! message opens a new one." : `⏹ Conversation ${stopped.id.slice(0, 8)} ended. ${others} other conversation${others === 1 ? " stays" : "s stay"} open.`;
33
33
  /** Each carried event of a turn sent as its parts. */
34
34
  function partsRelay(reply, carriage) {
35
35
  return {
@@ -45,32 +45,55 @@ function partsRelay(reply, carriage) {
45
45
  const CHAT = {
46
46
  conversationOf: openConversationOf,
47
47
  routeOf: routeAsk,
48
- stopOf: stopTargetOf,
48
+ stopOf: (key) => [stopTargetOf(key)].filter((c) => c !== undefined),
49
49
  allOf: openConversationsOf,
50
50
  carries: (kind) => kind !== "returned",
51
51
  parts: (event) => (event.kind === "answer" ? splitForNotify(event.text) : [event.text]),
52
52
  stopped: stoppedOfMany,
53
53
  renew: endNewest,
54
54
  folderOf: (text) => resolveProject(undefined, text),
55
+ forkOf: () => undefined,
55
56
  };
56
- /** Meni's one private chat with the bot (#4453): its newest conversation not deleted — an idle archive keeps it bound, only /new replaces it. */
57
- const boundOf = (key) => listConversations().find((c) => c.chat === key && c.shelf !== "deleted");
58
- /** The bound chat: ONE conversation at the workspace root, every message goes on with it, a stop pauses it, /new opens the next one at once. */
57
+ /** Meni's one private chat with the bot (#4453): its main conversation, the newest not deleted and not forked beside another — an idle archive keeps it bound, only /new replaces it. */
58
+ const boundOf = (key) => listConversations().find((c) => c.chat === key && c.shelf !== "deleted" && c.forkOf === undefined);
59
+ /** The conversations forked beside the bound chat's main one while it was busy (#4584), newest first; a stopped or put-away one is done. */
60
+ const sidesOf = (key) => listConversations().filter((c) => c.chat === key && c.forkOf !== undefined && c.state !== "closed" && c.shelf === undefined);
61
+ /** A conversation in the middle of a turn, or holding a message stored for its next one. */
62
+ const busy = (c) => turnInFlight(readEvents(c.id), c) !== undefined;
63
+ /** The bound chat's main conversation while it is free (#4584); while it is busy undefined, so the message runs at once in a new conversation forked from it and never waits behind the reply under way. */
64
+ const freeBound = (key) => {
65
+ const main = boundOf(key);
66
+ // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
67
+ return main === undefined || !busy(main) ? main : undefined;
68
+ };
69
+ /** The bound chat: ONE main conversation at the workspace root, every message goes on with it, or beside it in a fork while it is busy (#4584); a stop pauses the one at work, /new opens the next one at once. */
59
70
  const ONE = {
60
71
  conversationOf: boundOf,
61
- routeOf: boundOf,
62
- stopOf: boundOf,
63
- allOf: (key) => [boundOf(key)].filter((c) => c !== undefined),
72
+ routeOf: freeBound,
73
+ stopOf: (key) => {
74
+ const working = ONE.allOf(key).filter(busy);
75
+ return working.length > 0 ? working : [boundOf(key)].filter((c) => c !== undefined);
76
+ },
77
+ allOf: (key) => [boundOf(key), ...sidesOf(key)].filter((c) => c !== undefined),
64
78
  carries: CHAT.carries,
65
79
  parts: CHAT.parts,
66
- stopped: () => "⏹ Stopped. Your next message picks the conversation up where it stopped.",
80
+ stopped: (stopped) => {
81
+ const forks = stopped.filter((c) => c.forkOf !== undefined).length;
82
+ const parallel = `${forks} parallel conversation${forks === 1 ? "" : "s"}`;
83
+ if (forks === stopped.length)
84
+ return `⏹ Stopped ${parallel}.`;
85
+ return `⏹ Stopped${forks === 0 ? "" : `, with ${parallel}`}. Your next message picks the conversation up where it stopped.`;
86
+ },
67
87
  folderOf: () => rootFolder(),
88
+ forkOf: (key) => {
89
+ const main = boundOf(key);
90
+ // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
91
+ return main !== undefined && busy(main) ? main.sessionId : undefined;
92
+ },
68
93
  async renew(key, platform, end) {
69
- const bound = boundOf(key);
70
- // NULL-OK: field bound is OPTIONAL and therefore it is ok to check for NULL
71
- if (bound !== undefined) {
72
- end(bound.id);
73
- archiveConversation(bound.id);
94
+ for (const c of ONE.allOf(key)) {
95
+ end(c.id);
96
+ archiveConversation(c.id);
74
97
  }
75
98
  const { notice } = await createdIn(rootFolder(), undefined, () => key, (on) => openConversation({ platform, chat: key, ...on }));
76
99
  // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
@@ -83,13 +106,14 @@ const THREADS_ONE = (key) => listConversations().find((c) => c.chat === key);
83
106
  const MAIL = {
84
107
  conversationOf: THREADS_ONE,
85
108
  routeOf: THREADS_ONE,
86
- stopOf: THREADS_ONE,
109
+ stopOf: (key) => [THREADS_ONE(key)].filter((c) => c !== undefined),
87
110
  allOf: (key) => listConversations().filter((c) => c.chat === key),
88
111
  carries: (kind) => MAILED_KINDS.has(kind),
89
112
  parts: (event) => [event.text],
90
113
  stopped: stoppedOfMany,
91
114
  renew: endNewest,
92
115
  folderOf: (text) => resolveProject(undefined, text),
116
+ forkOf: () => undefined,
93
117
  };
94
118
  const CARRIAGE = { telegram: ONE, slack: CHAT, discord: CHAT, teams: CHAT, ntfy: CHAT, sms: CHAT, email: MAIL };
95
119
  /** The key of Meni's direct-message chat with the bot on Slack (#4453): one conversation, as his Telegram chat is; a Slack channel thread keeps its own. */
@@ -146,9 +170,9 @@ export class AgentGateway {
146
170
  void this.awaitTurn(c.id, Number(turn), partsRelay((part) => door(c, part), carriageOf(c.platform, c.chat ?? "")), pending).catch((err) => appendEvent(c.id, { role: "system", kind: "status", text: `❌ The answer could not be sent to this ${c.platform} thread after the BN restart: ${err instanceof Error ? err.message : String(err)}` }));
147
171
  }
148
172
  }
149
- /** No turn running or queued, no chat message waiting on its conversation's creation, and no chat waiting on an answer: the gateway can pass to another process without losing one. */
173
+ /** No chat message waiting on its conversation's creation: the gateway can pass to another process without losing one. A turn under way never holds it — the next build takes a cut turn up again on its session and sends its answer to its chat (#2116, #4584). */
150
174
  quiet() {
151
- return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
175
+ return !creationsPending();
152
176
  }
153
177
  /** Gives the store back when this process hands the gateway over. */
154
178
  async shutdown() {
@@ -227,18 +251,20 @@ export class AgentGateway {
227
251
  await pending;
228
252
  const open = carriage.conversationOf(key);
229
253
  if (act.kind === "stop") {
230
- const stopped = carriage.stopOf(key);
231
- // NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
232
- if (stopped === undefined)
254
+ const pressed = carriage.allOf(key).filter((c) => c.id === act.conversation);
255
+ const stopped = pressed.length > 0 ? pressed : carriage.stopOf(key);
256
+ if (stopped.length === 0)
233
257
  return reply("Nothing to stop here — no conversation is open.");
234
- this.end(stopped.id);
235
- return reply(carriage.stopped(stopped, carriage.allOf(key).filter((c) => c.id !== stopped.id).length));
258
+ for (const c of stopped)
259
+ this.end(c.id);
260
+ return reply(carriage.stopped(stopped, carriage.allOf(key).filter((c) => !stopped.includes(c)).length));
236
261
  }
237
262
  if (act.kind === "new")
238
263
  return reply(await carriage.renew(key, platform, (id) => this.end(id)));
239
264
  if (act.text === "")
240
265
  return reply("Send `! <your message>` to talk to the agent.");
241
266
  const target = carriage.routeOf(key, act.text);
267
+ const forkOf = carriage.forkOf(key);
242
268
  // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
243
269
  if (target === undefined) {
244
270
  let project;
@@ -256,7 +282,7 @@ export class AgentGateway {
256
282
  const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
257
283
  const turn = {};
258
284
  const [creation] = await Promise.allSettled([createdIn(project, undefined, () => key, (on) => {
259
- const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, text: act.text, receivedMs: monotonicMs() - arrived });
285
+ const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: act.text, receivedMs: monotonicMs() - arrived });
260
286
  // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
261
287
  const told = open === undefined ? [] : [this.told(created.id, 1, `🆕 An independent ask: it runs in its own conversation ${created.id.slice(0, 8)} while ${open.id.slice(0, 8)} keeps working.`)];
262
288
  turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false), told);
@@ -362,12 +388,27 @@ const chatBrief = (messenger) => `You are BN's agent in Meni's one ${messenger}
362
388
  Start every reply with a short bracketed label for the work it is about — the story id ([#4453]), the project ([AlphaWave]) or a few words — so he never has to pick a thread: you decide which work each message is about.
363
389
  The chat shows bold, italic, code, links, bullets and emojis, never tables; keep replies short. Your reply already reaches the chat — never also send it with the notify tool.
364
390
  Never use the AskUserQuestion tool here: its question stays on a screen he cannot see. To ask him, end the reply with the question and one line per choice starting with 🔘 — each becomes a choice he taps, and he may answer in his own words instead.`;
365
- /** The text one message of the bound chat is sent as: the brief on the conversation's first turn, then what the chat knows around it, then his own words, last. */
391
+ /** What a message forked beside the busy main conversation is told (#4584), about 70 tokens. */
392
+ const BESIDE = "(BN: the main conversation of this chat is still busy on an earlier message of his, so this one runs at once beside it, in a parallel conversation. Answer this message only, under its own label, and leave the work under way to the main conversation.)";
393
+ /** The answers his chat got from the forked conversations since the main one last heard from him (#4584): the main one, and each new fork of it, reads them as part of the chat. */
394
+ function answeredBeside(key, main) {
395
+ const heard = readEvents(main.id).filter((e) => e.role === "user").at(-1)?.ts ?? main.createdAt;
396
+ const answers = listConversations()
397
+ .filter((c) => c.chat === key && c.forkOf !== undefined && c.shelf !== "deleted")
398
+ .flatMap((c) => readEvents(c.id).filter((e) => e.kind === "answer" && e.ts > heard))
399
+ .sort((x, y) => x.ts.localeCompare(y.ts));
400
+ return answers.length === 0 ? [] : [`(BN: while the main conversation worked, these answers reached his chat from conversations running beside it — read them as part of this chat:\n${answers.map((e) => `• «${e.text}»`).join("\n")})`];
401
+ }
402
+ /** The text one message of the bound chat is sent as: the brief on the conversation's first turn, what the chat was answered beside it and whether this one runs beside it, then what the chat knows around it, then his own words, last. */
366
403
  export function chatTurnText(key, text, context) {
404
+ const brief = chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram");
367
405
  const bound = boundOf(key);
368
406
  // NULL-OK: field bound is OPTIONAL and therefore it is ok to check for NULL
369
- const first = bound === undefined || !readEvents(bound.id).some((e) => e.role === "user");
370
- return [...(first ? [chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram")] : []), ...context, text].join("\n\n");
407
+ if (bound === undefined)
408
+ return [brief, ...context, text].join("\n\n");
409
+ // A message beside a main conversation whose session is not written yet runs in a session of its own, which has not had the brief.
410
+ const first = !readEvents(bound.id).some((e) => e.role === "user") || (busy(bound) && !bound.started);
411
+ return [...(first ? [brief] : []), ...answeredBeside(key, bound), ...(busy(bound) ? [BESIDE] : []), ...context, text].join("\n\n");
371
412
  }
372
413
  /** The Claude CLI's own folder of session transcripts. */
373
414
  function claudeProjects() {
@@ -505,18 +546,30 @@ class TranscriptTail {
505
546
  }
506
547
  /** The draft of each streamed turn this process shows, one id per turn so no turn's preview lands on another's. */
507
548
  let draftIds = 0;
549
+ /** The conversation each draft still streaming belongs to, so his stop on one of the parallel replies stops that reply's conversation (#4584). */
550
+ const drafts = new Map();
551
+ /** The conversation whose reply streams in this draft, or undefined once its turn ended or when an earlier BN process drew it. */
552
+ export function conversationOfDraft(draft) {
553
+ return drafts.get(draft);
554
+ }
508
555
  /** The bound chat's turns as they happen (#4453): the working state at once, the agent's text and steps as a paced preview, the answer with its choices as buttons. */
509
556
  export function streamedChat(messenger, log) {
510
557
  return {
511
558
  say: (text) => messenger.send(text),
512
559
  turn(id, _n, queued) {
513
- const reply = new StreamedReply(messenger, ++draftIds, log);
560
+ const draft = ++draftIds;
561
+ drafts.set(draft, id);
562
+ const reply = new StreamedReply(messenger, draft, log);
514
563
  let tail;
515
564
  if (!queued)
516
565
  reply.begin();
517
- const close = () => {
566
+ const ended = () => {
567
+ drafts.delete(draft);
518
568
  // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
519
569
  tail?.stop();
570
+ };
571
+ const close = () => {
572
+ ended();
520
573
  reply.close();
521
574
  };
522
575
  return {
@@ -529,8 +582,7 @@ export function streamedChat(messenger, log) {
529
582
  tail ??= TranscriptTail.of(id, reply, log);
530
583
  return;
531
584
  case "answer": {
532
- // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
533
- tail?.stop();
585
+ ended();
534
586
  const { text, choices } = choicesOf(event.text);
535
587
  return reply.finish(text, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
536
588
  }
@@ -538,8 +590,7 @@ export function streamedChat(messenger, log) {
538
590
  case "stopped":
539
591
  case "archived":
540
592
  case "deleted":
541
- // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
542
- tail?.stop();
593
+ ended();
543
594
  return reply.finish(event.text);
544
595
  case "returned":
545
596
  case "resumed":
@@ -34,6 +34,7 @@ export const SETTINGS = [
34
34
  { path: ["slack", "enabled"], label: "Enabled", kind: "toggle" },
35
35
  { path: ["slack", "botToken"], label: "Bot token", kind: "secret", hint: "Starts with xoxb-. api.slack.com/apps, your app, OAuth & Permissions, Bot User OAuth Token. Needs the chat:write scope. Use this with Channels, or use the Webhook URL instead." },
36
36
  { path: ["slack", "configToken"], label: "Configuration token", kind: "secret", hint: "Lets BN repair its own Slack app (scopes, the Messages tab). api.slack.com/apps, Your App Configuration Tokens, Generate Token." },
37
+ { path: ["slack", "configRefreshToken"], label: "Configuration refresh token", kind: "secret", hint: "Generated with the configuration token. BN renews the 12-hour token with it, so setup keeps working." },
37
38
  { path: ["slack", "channels"], label: "Channels (comma-separated)", kind: "list", hint: "Channel ids like C0123ABCD (Slack: channel name, View channel details, bottom of the About tab). Invite the bot to each channel first." },
38
39
  { path: ["slack", "webhookUrl"], label: "Webhook URL", kind: "secret", hint: "Simplest option: https://hooks.slack.com/services/... from your app, Incoming Webhooks, Add New Webhook to Workspace." },
39
40
  ] },
@@ -203,18 +203,30 @@ function control(row) {
203
203
  }
204
204
  return wrap;
205
205
  }
206
- function setupText(r) { return ["Intent:"].concat(r.intent.map(function (x) { return "• " + x; }), ["Installed:"], r.installed.length ? r.installed.map(function (x) { return "• " + x; }) : ["• nothing yet"], r.repaired.length ? ["Repaired just now:"].concat(r.repaired.map(function (x) { return "• " + x; })) : [], r.gaps.length ? ["Still missing:"].concat(r.gaps.map(function (x) { return "• " + x; })) : []).join("\n"); }
206
+ var busy = {};
207
+ function factRows(table, label, items) { items.forEach(function (x, i) { var tr = el("tr"); tr.append(el("td", "name", i === 0 ? label : ""), el("td", "", x)); table.append(tr); }); }
207
208
  function setupRow(g) {
208
- var row = el("tr"), cell = el("td"), button = el("button", "", "🔁 Reinstall"), detail = el("pre", "hint");
209
+ var row = el("tr"), cell = el("td"), button = el("button", "", "🔁 Reinstall"), working = el("span", "hint", ""), facts = el("table"), last = g.setup && g.setup.last;
209
210
  button.title = "Makes what is installed match what is set above, and shows both";
210
- detail.textContent = g.setup && g.setup.last ? setupText({ intent: g.setup.intent, installed: g.setup.last.installed, repaired: g.setup.last.repaired, gaps: g.setup.last.gaps }) : "Intent:\n" + (g.setup ? g.setup.intent.map(function (x) { return "• " + x; }).join("\n") : "");
211
+ facts.setAttribute("aria-label", g.title + " setup");
212
+ factRows(facts, "Intent", g.setup ? g.setup.intent : []);
213
+ factRows(facts, "Installed", last ? (last.installed.length ? last.installed : ["nothing yet"]) : ["not checked yet"]);
214
+ if (last && last.repaired.length) factRows(facts, "Repaired", last.repaired);
215
+ if (last) factRows(facts, "Missing", last.gaps.length ? last.gaps : ["nothing"]);
216
+ var inFlight = !!busy[g.messenger] || !!(g.setup && g.setup.running);
217
+ button.disabled = inFlight;
218
+ working.textContent = inFlight ? "⏳ Working" : "";
211
219
  button.onclick = async function () {
212
- button.disabled = true;
213
- try { var r = await call("POST", "/v1/messenger-setup", { messenger: g.messenger }); detail.textContent = setupText(r); say(r.gaps.length ? "error" : "good", r.gaps.length ? "⚠️ " + g.title + " still lacks " + r.gaps.length + " thing(s) — see the list" : "✅ " + g.title + " installed to match your settings"); }
214
- catch (e) { say("error", "❌ " + g.title + " reinstall failed — " + plainWhy(e)); }
215
- button.disabled = false;
220
+ busy[g.messenger] = true; button.disabled = true; working.textContent = "⏳ Working";
221
+ try {
222
+ var r = await call("POST", "/v1/messenger-setup", { messenger: g.messenger });
223
+ button.title = r.gaps.length ? r.gaps.join("\n") : "Everything this messenger needs is in place";
224
+ say(r.gaps.length ? "error" : "good", r.gaps.length ? "⚠️ " + g.messenger.toUpperCase() + " " + r.gaps.length + " MISSING" : "✅ " + g.messenger.toUpperCase() + " INSTALLED");
225
+ } catch (e) { button.title = plainWhy(e); say("error", "❌ " + g.messenger.toUpperCase() + " FAILED"); }
226
+ busy[g.messenger] = false;
227
+ await load();
216
228
  };
217
- cell.colSpan = 2; cell.append(button, detail); row.append(cell); return row;
229
+ cell.colSpan = 2; cell.append(button, working, facts); row.append(cell); return row;
218
230
  }
219
231
  function shownOf(s) { return JSON.stringify([s.state, s.conversation, s.groups, s.configPath]); }
220
232
  function draw(s) {
@@ -1,59 +1,59 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const { spawn } = require("child_process");
6
-
7
- const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
8
-
9
- function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
10
- return [
11
- deploy,
12
- "--domain", domain,
13
- ...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
14
- // NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
15
- "--project-root", projectRoot ?? home,
16
- "--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
17
- "--notify-dir", doorsDir,
18
- ];
19
- }
20
-
21
- function runDeploy({ node, args, cwd, env, onOutput }) {
22
- return new Promise((resolve, reject) => {
23
- const child = spawn(node, args, { windowsHide: true, cwd, env });
24
- child.stdout.on("data", (chunk) => onOutput(String(chunk)));
25
- child.stderr.on("data", (chunk) => onOutput(String(chunk)));
26
- child.on("error", reject);
27
- child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
28
- });
29
- }
30
-
31
- const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
32
-
33
- function writeRecord(file, record) {
34
- const staged = `${file}.${process.pid}.tmp`;
35
- fs.writeFileSync(staged, JSON.stringify(record, null, 2));
36
- try {
37
- fs.renameSync(staged, file);
38
- } catch (err) {
39
- fs.rmSync(staged, { force: true });
40
- throw err;
41
- }
42
- }
43
-
44
- async function runRecorded(recordFile, recordText) {
45
- const record = { ...JSON.parse(recordText), pid: process.pid };
46
- const log = recordFile.replace(/\.json$/, ".log");
47
- const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
48
- try {
49
- const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
50
- write({ endedAt: new Date().toISOString(), ...ended });
51
- } catch (err) {
52
- // OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
53
- write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
54
- }
55
- }
56
-
57
- if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
58
-
59
- module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { spawn } = require("child_process");
6
+
7
+ const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
8
+
9
+ function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
10
+ return [
11
+ deploy,
12
+ "--domain", domain,
13
+ ...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
14
+ // NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
15
+ "--project-root", projectRoot ?? home,
16
+ "--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
17
+ "--notify-dir", doorsDir,
18
+ ];
19
+ }
20
+
21
+ function runDeploy({ node, args, cwd, env, onOutput }) {
22
+ return new Promise((resolve, reject) => {
23
+ const child = spawn(node, args, { windowsHide: true, cwd, env });
24
+ child.stdout.on("data", (chunk) => onOutput(String(chunk)));
25
+ child.stderr.on("data", (chunk) => onOutput(String(chunk)));
26
+ child.on("error", reject);
27
+ child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
28
+ });
29
+ }
30
+
31
+ const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
32
+
33
+ function writeRecord(file, record) {
34
+ const staged = `${file}.${process.pid}.tmp`;
35
+ fs.writeFileSync(staged, JSON.stringify(record, null, 2));
36
+ try {
37
+ fs.renameSync(staged, file);
38
+ } catch (err) {
39
+ fs.rmSync(staged, { force: true });
40
+ throw err;
41
+ }
42
+ }
43
+
44
+ async function runRecorded(recordFile, recordText) {
45
+ const record = { ...JSON.parse(recordText), pid: process.pid };
46
+ const log = recordFile.replace(/\.json$/, ".log");
47
+ const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
48
+ try {
49
+ const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
50
+ write({ endedAt: new Date().toISOString(), ...ended });
51
+ } catch (err) {
52
+ // OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
53
+ write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
54
+ }
55
+ }
56
+
57
+ if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
58
+
59
+ module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
@@ -106,6 +106,19 @@ export class PollCursors {
106
106
  writeFileSync(staged, JSON.stringify(all));
107
107
  renameSync(staged, this.path);
108
108
  }
109
+ keys() {
110
+ return Object.keys(this.read());
111
+ }
112
+ delete(key) {
113
+ const all = this.read();
114
+ if (!(key in all))
115
+ return;
116
+ delete all[key];
117
+ mkdirSync(dirname(this.path), { recursive: true });
118
+ const staged = `${this.path}.tmp`;
119
+ writeFileSync(staged, JSON.stringify(all));
120
+ renameSync(staged, this.path);
121
+ }
109
122
  getNumber(key) {
110
123
  const stored = this.get(key);
111
124
  if (stored === undefined)
@@ -263,9 +263,11 @@ export class EmailAgentInbox {
263
263
  return this.answer({ messageId: thread.messageIds.at(-1), references: thread.messageIds.slice(0, -1) }, thread.subject, text);
264
264
  }
265
265
  /** One answer, mailed to his own account as a reply in the thread of the mail it answers; replying to it reaches the agent again. */
266
- answer(mail, subject, text) {
267
- const { user } = this.account();
268
- return this.mail({
266
+ async answer(mail, subject, text) {
267
+ const { user, pass } = this.account();
268
+ const server = this.smtpServer();
269
+ const transport = createTransport({ ...server, auth: { user: user, pass: pass } });
270
+ const message = {
269
271
  from: { name: "BN agent", address: user },
270
272
  to: user,
271
273
  replyTo: agentAddress(user),
@@ -274,23 +276,7 @@ export class EmailAgentInbox {
274
276
  references: [...mail.references, mail.messageId],
275
277
  headers: { [AGENT_HEADER]: "answer" },
276
278
  text,
277
- });
278
- }
279
- /** #4581 — the `email` priority's one channel: a notification mailed whole to his own account, its first line the subject. */
280
- notifyOwner(text) {
281
- const { user } = this.account();
282
- return this.mail({ from: { name: "BullseyeNotify", address: user }, to: user, subject: text.split("\n", 1)[0].replace(/\*/g, "").trim() || "BullseyeNotify", text });
283
- }
284
- /** #4581 — logs in to the account's SMTP server and sends nothing; throws why the login failed. */
285
- async verify() {
286
- const { user, pass } = this.account();
287
- await createTransport({ ...this.smtpServer(), auth: { user: user, pass: pass } }).verify();
288
- }
289
- /** Sends one mail through the account's SMTP server, retrying a transient refusal; throws why it did not go. */
290
- async mail(message) {
291
- const { user, pass } = this.account();
292
- const server = this.smtpServer();
293
- const transport = createTransport({ ...server, auth: { user: user, pass: pass } });
279
+ };
294
280
  for (let attempt = 1;; attempt++) {
295
281
  try {
296
282
  await transport.sendMail(message);
@@ -298,7 +284,7 @@ export class EmailAgentInbox {
298
284
  }
299
285
  catch (err) {
300
286
  if (attempt >= SMTP_ATTEMPTS || !transientSmtp(err))
301
- throw new Error(`${server.host} did not take the mail after ${attempt} attempt(s): ${err instanceof Error ? err.message : String(err)}`);
287
+ throw new Error(`${server.host} did not take the answer after ${attempt} attempt(s): ${err instanceof Error ? err.message : String(err)}`);
302
288
  await new Promise((resolve) => setTimeout(resolve, 2000 * 2 ** (attempt - 1)));
303
289
  }
304
290
  }
@@ -337,18 +337,25 @@ const SLACK_HINTS = {
337
337
  token_revoked: "the bot token was revoked — reinstall the BN Slack app and paste its new token",
338
338
  account_inactive: "the bot's Slack account is deactivated — reinstall the BN Slack app",
339
339
  missing_scope: "the BN Slack app lacks a permission this needs (im:history, im:write, chat:write, users:read) — add it and reinstall the app",
340
+ token_expired: "the configuration token expired — paste a new configuration token and its refresh token into BN settings, Slack",
341
+ invalid_refresh_token: "Slack refused the configuration refresh token — paste a new configuration token and its refresh token into BN settings, Slack",
342
+ messages_tab_disabled: "the app's App Home Messages tab does not let people message it — BN setup turns it on once it holds a configuration token",
340
343
  fatal_error: "Slack failed on its side and part of the call may have gone through, so it is not sent again — nothing shows twice",
341
344
  };
342
345
  // GATE: the errors Slack's method pages document as passing — rate limited, a transient issue on its end, unavailable for now, mid-migration, or
343
346
  // the POST data missing or cut short on the way — the same call is tried again after a wait. fatal_error is not among them: Slack says part of the
344
347
  // call may have gone through, so a post tried again could show twice.
348
+ // GATE: Slack says an internal_error on these methods may have gone through, so a post or an opening tried again could show twice — it is refused here, never re-sent.
349
+ const SLACK_NOT_RESENT = new Set(["chat.postMessage", "conversations.open", "conversations.join"]);
345
350
  const SLACK_PASSING = new Set(["ratelimited", "rate_limited", "internal_error", "service_unavailable", "team_added_to_org", "request_timeout"]);
346
- // GATE: the errors Slack documents as refusals on the methods this bridge calls (chat.postMessage, chat.update, conversations.open, conversations.history) — terminal, never re-sent.
351
+ // GATE: the errors Slack documents as refusals on the methods this bridge calls (chat.postMessage, chat.update, conversations.open, conversations.join, conversations.history, apps.manifest.export, apps.manifest.update, tooling.tokens.rotate) — terminal, never re-sent.
347
352
  const SLACK_REFUSALS = new Set([
348
353
  "access_denied", "account_inactive", "fatal_error", "channel_not_found", "cannot_dm_bot", "cant_update_message", "deprecated_endpoint", "edit_window_closed", "ekm_access_denied",
349
354
  "enterprise_is_restricted", "invalid_arguments", "invalid_auth", "invalid_blocks", "invalid_charset", "invalid_cursor", "invalid_form_data", "invalid_ts_latest", "invalid_ts_oldest",
350
355
  "is_archived", "message_not_found", "method_deprecated", "missing_scope", "msg_too_long", "no_permission", "no_text", "not_allowed_token_type", "not_authed", "not_in_channel",
351
- "org_login_required", "restricted_action", "team_access_not_granted", "token_expired", "token_revoked", "too_many_users", "two_factor_setup_required", "user_not_found", "user_not_visible", "users_list_not_supplied",
356
+ "org_login_required", "restricted_action", "method_not_supported_for_channel_type", "invalid_refresh_token", "invalid_manifest", "invalid_app_id", "app_not_found",
357
+ "messages_tab_disabled", "restricted_action_read_only_channel", "posting_to_channel_denied", "message_limit_exceeded", "missing_argument", "user_disabled", "app_cannot_join_channel", "not_enough_users",
358
+ "channel_is_limited_access", "not_workspace_member", "too_many_members", "failed_export", "app_not_eligible", "app_edit_disabled", "invalid_app", "accesslimited", "team_access_not_granted", "token_expired", "token_revoked", "too_many_users", "two_factor_setup_required", "user_not_found", "user_not_visible", "users_list_not_supplied",
352
359
  ]);
353
360
  /** One Slack Web API call, a form POST (the one body every method takes, read methods included): retried on a network failure, a 5xx, a 429 (after its Retry-After) or a documented passing error, refused on a documented error, thrown whole on anything else. */
354
361
  export async function slackCall(base, token, method, body, tries = TELEGRAM_TRIES) {
@@ -388,17 +395,53 @@ export async function slackCall(base, token, method, body, tries = TELEGRAM_TRIE
388
395
  if (response.status === 200 && json.ok === true)
389
396
  return json;
390
397
  const error = String(json.error ?? "");
391
- if (response.status === 200 && SLACK_PASSING.has(error)) {
398
+ const named = method.split("?")[0];
399
+ const resendable = SLACK_PASSING.has(error) && !(error === "internal_error" && SLACK_NOT_RESENT.has(named));
400
+ if (response.status === 200 && resendable) {
392
401
  if (last)
393
402
  throw new SlackUnreachable(`Slack kept answering ${method} with ${error} through ${attempt} tries`);
394
403
  await sleep(backoff);
395
404
  continue;
396
405
  }
397
- if (response.status === 200 && SLACK_REFUSALS.has(error))
406
+ if (response.status === 200 && (SLACK_REFUSALS.has(error) || (error === "internal_error" && SLACK_NOT_RESENT.has(named))))
398
407
  throw new SlackRefused(method, error);
399
408
  throw new SlackUnknown(method, response.status, raw, response.headers);
400
409
  }
401
410
  }
411
+ // GATE: the bodies Slack's incoming-webhook documentation lists as refusals of a post — terminal, never re-sent. A 429 or 5xx is passing and is tried again.
412
+ const SLACK_WEBHOOK_REFUSALS = new Set(["invalid_payload", "user_not_found", "channel_not_found", "channel_is_archived", "action_prohibited", "posting_to_general_channel_denied", "no_service", "no_service_id", "no_team", "team_disabled", "invalid_token", "no_active_hooks", "no_text", "too_many_attachments"]);
413
+ /** One post to an incoming webhook: retried on a network failure, a 5xx or a 429; refused on a documented body; thrown whole on anything else. */
414
+ export async function slackWebhookPost(url, payload, tries = TELEGRAM_TRIES) {
415
+ for (let attempt = 1;; attempt++) {
416
+ const last = attempt >= tries;
417
+ const backoff = 1000 * 2 ** (attempt - 1);
418
+ let response;
419
+ try {
420
+ response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000) });
421
+ }
422
+ catch (err) {
423
+ if (!(err instanceof TypeError) && !(err instanceof DOMException))
424
+ throw err;
425
+ if (last)
426
+ throw new SlackUnreachable(`the Slack webhook could not be reached after ${attempt} tries: ${err.message}`);
427
+ await sleep(backoff);
428
+ continue;
429
+ }
430
+ const body = (await response.text()).trim();
431
+ if (response.ok)
432
+ return;
433
+ if (response.status === 429 || response.status >= 500) {
434
+ if (last)
435
+ throw new SlackUnreachable(`the Slack webhook kept answering ${response.status} through ${attempt} tries`);
436
+ const after = Number(response.headers.get("retry-after"));
437
+ await sleep(Number.isFinite(after) && after > 0 ? after * 1000 : backoff);
438
+ continue;
439
+ }
440
+ if (SLACK_WEBHOOK_REFUSALS.has(body))
441
+ throw new SlackRefused("the incoming webhook", body);
442
+ throw new SlackUnknown("the incoming webhook", response.status, body, response.headers);
443
+ }
444
+ }
402
445
  /** The agent's markdown in Slack's mrkdwn, built on the one Telegram converter: the same headings, bullets, tables-as-bullets and escapes (Slack escapes &, < and > as HTML does). */
403
446
  export function markdownToSlackMrkdwn(text) {
404
447
  return markdownToTelegramHtml(text)
@@ -15,8 +15,6 @@ export function formatIdleReading(reading) {
15
15
  : `idle: could not measure — ${reading.why} — user activity unknown, so activity gating is skipped`;
16
16
  }
17
17
  const EVERY_PRIORITY = ["low", "normal", "high"];
18
- /** #4581 — every priority a caller may name: the three that fan out, and `email`, which reaches the one email channel and nothing else. */
19
- export const PRIORITIES = [...EVERY_PRIORITY, "email"];
20
18
  // GATE: which priorities reach each channel, in send order, and what an at-keyboard user holds back — a channel is never attempted for a priority outside its list
21
19
  const CHANNEL_ROUTES = [
22
20
  { channel: "desktop", priorities: ["normal", "high"], atKeyboard: "desktopSignal" },
@@ -26,10 +24,9 @@ const CHANNEL_ROUTES = [
26
24
  { channel: "slack", priorities: EVERY_PRIORITY, atKeyboard: "channelLog" },
27
25
  { channel: "teams", priorities: EVERY_PRIORITY, atKeyboard: "heldBack" },
28
26
  { channel: "sms", priorities: ["high"], atKeyboard: "heldBack" },
29
- { channel: "email", priorities: ["email"], atKeyboard: "heldBack" },
30
27
  ];
31
28
  export function describePriorityRouting() {
32
- return PRIORITIES
29
+ return EVERY_PRIORITY
33
30
  .map((priority) => `${priority}=${CHANNEL_ROUTES.filter((route) => route.priorities.includes(priority)).map((route) => route.channel).join("+")}`)
34
31
  .join("; ");
35
32
  }
@@ -45,12 +42,12 @@ export function computeDesktopOnlyMode(priority, policy, ctx) {
45
42
  reason: "DND active — every priority is held, no channel was attempted",
46
43
  };
47
44
  }
48
- if (priority === "high" || priority === "email") {
45
+ if (priority === "high") {
49
46
  return {
50
47
  desktopOnly: false,
51
48
  idle: ctx.idle,
52
49
  idleKnown,
53
- reason: `priority=${priority} — every enabled channel of that priority is used and activity gating is waived`,
50
+ reason: "priority=high — every enabled channel is used and activity gating is waived",
54
51
  };
55
52
  }
56
53
  // The measurement FAILED: a deliberate fail-open. Stated as its own branch so
@@ -111,7 +108,6 @@ export async function sendWithRouting(options) {
111
108
  slack: options.enableSlack,
112
109
  teams: options.enableTeams,
113
110
  sms: options.enableSms,
114
- email: options.enableEmail,
115
111
  };
116
112
  const decision = computeDesktopOnlyMode(priority, policy, ctx);
117
113
  if (decision.suppressedReason === "dnd") {