omni-notify-mcp 1.3.459 → 1.3.461
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/dist/agentGateway.js +82 -31
- package/dist/gateway/panel.js +12 -2
- package/dist/gateway/panelPage.js +14 -0
- package/dist/gateway/restDoor.js +3 -1
- package/dist/messaging/setup.js +31 -0
- package/dist/messaging/slackSetup.js +61 -0
- package/dist/notify.js +153 -8
- package/dist/shared/agentSession.js +12 -5
- package/dist/shared/conversation/claudeProvider.js +1 -1
- package/dist/shared/conversation/conversations.js +2 -2
- package/dist/shared/conversation/sessionDriver.js +6 -5
- package/package.json +1 -1
package/dist/agentGateway.js
CHANGED
|
@@ -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
|
|
57
|
-
const boundOf = (key) => listConversations().find((c) => c.chat === key && c.shelf !== "deleted");
|
|
58
|
-
/** The
|
|
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:
|
|
62
|
-
stopOf:
|
|
63
|
-
|
|
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: () =>
|
|
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
|
|
70
|
-
|
|
71
|
-
|
|
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. */
|
|
@@ -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
|
|
231
|
-
|
|
232
|
-
if (stopped ===
|
|
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
|
-
|
|
235
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
370
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
542
|
-
tail?.stop();
|
|
593
|
+
ended();
|
|
543
594
|
return reply.finish(event.text);
|
|
544
595
|
case "returned":
|
|
545
596
|
case "resumed":
|
package/dist/gateway/panel.js
CHANGED
|
@@ -8,6 +8,7 @@ import { createHash } from "crypto";
|
|
|
8
8
|
import { existsSync, mkdirSync, readFileSync } from "fs";
|
|
9
9
|
import { dirname, join } from "path";
|
|
10
10
|
import { CONFIG_DIR, deliveryReport, isDndActive } from "../notify.js";
|
|
11
|
+
import { MESSENGER_SETUPS } from "../messaging/setup.js";
|
|
11
12
|
import { extensionModule } from "./extensionModule.js";
|
|
12
13
|
import { GatewayError, conversationEnabled, setConversationEnabled, writeRecordFile } from "./conversationOwner.js";
|
|
13
14
|
import { TELEGRAM_PARSE_MODES } from "../messaging/telegramFormat.js";
|
|
@@ -24,14 +25,15 @@ export const SETTINGS = [
|
|
|
24
25
|
{ path: ["desktop", "tts"], label: "Read aloud", kind: "toggle", hint: "On speaks each desktop notification out loud." },
|
|
25
26
|
{ path: ["desktop", "ttsVoice"], label: "Voice", kind: "text", hint: "Edge voice name, e.g. en-US-GuyNeural. Empty uses the default voice." },
|
|
26
27
|
] },
|
|
27
|
-
{ guide: { summary: "Create a bot (2 min)", steps: ["Open Telegram, search `@BotFather`.", "Send `/newbot` and follow the prompts; copy the token it gives you.", "Paste the token below — that switches Telegram on.", "Send your bot any message: BN binds that chat to you, and the chat is your BN agent from then on."], need: [["telegram.token"], ["telegram.chatIds"]] }, title: "✈️ Telegram", rows: [
|
|
28
|
+
{ guide: { summary: "Create a bot (2 min)", steps: ["Open Telegram, search `@BotFather`.", "Send `/newbot` and follow the prompts; copy the token it gives you.", "Paste the token below — that switches Telegram on.", "Send your bot any message: BN binds that chat to you, and the chat is your BN agent from then on."], need: [["telegram.token"], ["telegram.chatIds"]] }, messenger: "telegram", title: "✈️ Telegram", rows: [
|
|
28
29
|
{ path: ["telegram", "enabled"], label: "Enabled", kind: "toggle" },
|
|
29
30
|
{ path: ["telegram", "token"], label: "Bot token", kind: "secret", hint: "From @BotFather after /newbot, shaped like 123456:ABC-DEF... Pasting it switches Telegram on; the first message you send the bot binds your chat." },
|
|
30
31
|
{ path: ["telegram", "parseMode"], label: "Formatting", kind: "choice", choices: TELEGRAM_PARSE_MODES, fallback: "HTML", hint: "HTML (default) turns an agent's markdown bold, italics, code, links and bullets into Telegram formatting. MarkdownV2 sends the text as written for Telegram's own markdown. none sends plain text." },
|
|
31
32
|
] },
|
|
32
|
-
{ guide: { summary: "Connect Slack", steps: ["Go to api.slack.com/apps, open your app (or Create New App).", "Easiest: Incoming Webhooks, Add New Webhook to Workspace, pick the channel, copy the URL into Webhook URL.", "Or: OAuth & Permissions, add the chat:write scope, install the app, copy the Bot User OAuth Token (xoxb-), invite the bot to the channel, and list the channel id.", "Switch Enabled to On."], need: [["slack.botToken", "slack.webhookUrl"]] }, title: "💬 Slack", rows: [
|
|
33
|
+
{ guide: { summary: "Connect Slack", steps: ["Go to api.slack.com/apps, open your app (or Create New App).", "Easiest: Incoming Webhooks, Add New Webhook to Workspace, pick the channel, copy the URL into Webhook URL.", "Or: OAuth & Permissions, add the chat:write scope, install the app, copy the Bot User OAuth Token (xoxb-), invite the bot to the channel, and list the channel id.", "Switch Enabled to On."], need: [["slack.botToken", "slack.webhookUrl"]] }, messenger: "slack", title: "💬 Slack", rows: [
|
|
33
34
|
{ path: ["slack", "enabled"], label: "Enabled", kind: "toggle" },
|
|
34
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
|
+
{ 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." },
|
|
35
37
|
{ 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." },
|
|
36
38
|
{ 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." },
|
|
37
39
|
] },
|
|
@@ -277,6 +279,8 @@ export function panelState() {
|
|
|
277
279
|
conversation: conversationSwitchRead(),
|
|
278
280
|
groups: unreadable !== undefined ? [] : SETTINGS.map((g) => ({
|
|
279
281
|
title: g.title,
|
|
282
|
+
setup: g.messenger === undefined ? undefined : MESSENGER_SETUPS.view(g.messenger),
|
|
283
|
+
messenger: g.messenger,
|
|
280
284
|
guide: g.guide === undefined ? undefined : { summary: g.guide.summary, steps: g.guide.steps, next: nextStep(g, cfg) },
|
|
281
285
|
rows: g.rows.map((r) => ({ path: r.path, label: r.label, kind: r.kind, hint: r.hint, choices: r.choices, value: readAt(cfg, r.path) ?? r.fallback })),
|
|
282
286
|
})),
|
|
@@ -301,3 +305,9 @@ export function saveConversationSwitch(enabled) {
|
|
|
301
305
|
setConversationEnabled(enabled);
|
|
302
306
|
return { enabled };
|
|
303
307
|
}
|
|
308
|
+
/** The Reinstall press: the same reconcile BN runs at its start, run now for one messenger, answered with what is intended, installed, repaired and still missing. */
|
|
309
|
+
export async function reinstallMessenger(messenger) {
|
|
310
|
+
if (messenger !== "slack" && messenger !== "telegram")
|
|
311
|
+
throw new GatewayError(400, "expected slack or telegram");
|
|
312
|
+
return MESSENGER_SETUPS.reconcile(messenger);
|
|
313
|
+
}
|
|
@@ -203,6 +203,19 @@ 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"); }
|
|
207
|
+
function setupRow(g) {
|
|
208
|
+
var row = el("tr"), cell = el("td"), button = el("button", "", "🔁 Reinstall"), detail = el("pre", "hint");
|
|
209
|
+
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
|
+
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;
|
|
216
|
+
};
|
|
217
|
+
cell.colSpan = 2; cell.append(button, detail); row.append(cell); return row;
|
|
218
|
+
}
|
|
206
219
|
function shownOf(s) { return JSON.stringify([s.state, s.conversation, s.groups, s.configPath]); }
|
|
207
220
|
function draw(s) {
|
|
208
221
|
drawn = shownOf(s);
|
|
@@ -224,6 +237,7 @@ function draw(s) {
|
|
|
224
237
|
var d = el("details"); d.append(el("summary", "", g.guide.summary)); var ol = el("ol"); g.guide.steps.forEach(function (t) { ol.append(el("li", "", t.replace(/\`/g, ""))); }); d.append(ol);
|
|
225
238
|
td.append(d, el("div", "next", g.guide.next)); tr.append(td); table.append(tr);
|
|
226
239
|
}
|
|
240
|
+
if (g.messenger) table.append(setupRow(g));
|
|
227
241
|
g.rows.forEach(function (r) {
|
|
228
242
|
var row = el("tr"), name = el("td", "name", r.label), cell = el("td"); cell.append(control(r));
|
|
229
243
|
if (r.hint) cell.append(el("div", "hint", r.hint));
|
package/dist/gateway/restDoor.js
CHANGED
|
@@ -16,7 +16,7 @@ import { handleMcp } from "./mcpDoor.js";
|
|
|
16
16
|
import { MCP_PATH, accessGranted, challenge, handleOAuth, isOAuthPath, publicBase } from "./oauthDoor.js";
|
|
17
17
|
import { bearer, bearerAdmitted, fromThisMachine, handlePasskey, isPasskeyPath, localOnly, refusalOfRequest } from "./passkeyDoor.js";
|
|
18
18
|
import { terminalConsole, terminalFile, terminalRoute, terminalSockets } from "./terminalDoor.js";
|
|
19
|
-
import { configFile, conversationSwitchRead, panelState, saveConfigFile, saveConversationSwitch, saveSetting } from "./panel.js";
|
|
19
|
+
import { configFile, conversationSwitchRead, panelState, reinstallMessenger, saveConfigFile, saveConversationSwitch, saveSetting } from "./panel.js";
|
|
20
20
|
import { PANEL_PAGES, panelHtml } from "./panelPage.js";
|
|
21
21
|
import { configureMcpHosts } from "./mcpHosts.js";
|
|
22
22
|
import { readGatewayInstall, readNewestGatewayInstall, startGatewayInstall } from "./gatewayInstall.js";
|
|
@@ -117,6 +117,8 @@ async function route(req, url, arrivedAt) {
|
|
|
117
117
|
return { status: 200, body: parts.length === 3 ? saveConfigFile(body.text, body.opened) : saveSetting(body.path, body.value) };
|
|
118
118
|
}
|
|
119
119
|
}
|
|
120
|
+
if (resource === "messenger-setup" && parts.length === 2 && method === "POST")
|
|
121
|
+
return { status: 200, body: await reinstallMessenger((await readJson(req)).messenger) };
|
|
120
122
|
if (resource === "conversation-switch" && parts.length === 2) {
|
|
121
123
|
if (method === "GET")
|
|
122
124
|
return { status: 200, body: conversationSwitchRead() };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** The one setup path both messengers use: BN's start and the UI's Reinstall run the same reconcile. */
|
|
2
|
+
class MessengerSetups {
|
|
3
|
+
setups = new Map();
|
|
4
|
+
lastReports = new Map();
|
|
5
|
+
add(setup) {
|
|
6
|
+
this.setups.set(setup.name, setup);
|
|
7
|
+
}
|
|
8
|
+
of(name) {
|
|
9
|
+
const setup = this.setups.get(name);
|
|
10
|
+
if (setup === undefined)
|
|
11
|
+
throw new Error(`no messenger named ${name} has a setup; known: ${[...this.setups.keys()].join(", ")}`);
|
|
12
|
+
return setup;
|
|
13
|
+
}
|
|
14
|
+
/** The intent of one messenger beside its last report, for the page to draw. */
|
|
15
|
+
view(name) {
|
|
16
|
+
const setup = this.setups.get(name);
|
|
17
|
+
return setup === undefined ? undefined : { intent: setup.intent(), last: this.lastReports.get(name) };
|
|
18
|
+
}
|
|
19
|
+
async reconcile(name) {
|
|
20
|
+
const report = await this.of(name).reconcile();
|
|
21
|
+
this.lastReports.set(name, report);
|
|
22
|
+
return report;
|
|
23
|
+
}
|
|
24
|
+
async reconcileAll() {
|
|
25
|
+
const reports = [];
|
|
26
|
+
for (const name of this.setups.keys())
|
|
27
|
+
reports.push(await this.reconcile(name));
|
|
28
|
+
return reports;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export const MESSENGER_SETUPS = new MessengerSetups();
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { SlackRefused, slackCall } from "./messenger.js";
|
|
2
|
+
/** Every bot scope BN's Slack side uses: the DM chat (im:*, chat:write), the bus channel (channels:*, groups:*) and finding Meni (users:read). */
|
|
3
|
+
export const SLACK_BOT_SCOPES = ["chat:write", "channels:history", "channels:read", "channels:join", "groups:history", "groups:read", "im:history", "im:read", "im:write", "users:read", "incoming-webhook"];
|
|
4
|
+
/** The app BN needs, as Slack's manifest states it: a bot user people can message from the App Home Messages tab, with every scope above. */
|
|
5
|
+
export function slackAppManifest(name) {
|
|
6
|
+
return {
|
|
7
|
+
display_information: { name, description: "Talk to your agents from Slack" },
|
|
8
|
+
features: {
|
|
9
|
+
bot_user: { display_name: name, always_online: true },
|
|
10
|
+
app_home: { home_tab_enabled: false, messages_tab_enabled: true, messages_tab_read_only_enabled: false },
|
|
11
|
+
},
|
|
12
|
+
oauth_config: { scopes: { bot: [...SLACK_BOT_SCOPES.filter((s) => s !== "incoming-webhook")] } },
|
|
13
|
+
settings: { org_deploy_enabled: false, socket_mode_enabled: false, token_rotation_enabled: false },
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/** The things the Slack setup still lacks after every repair BN can make itself; each names the one act left. */
|
|
17
|
+
export class SlackSetupGaps extends Error {
|
|
18
|
+
gaps;
|
|
19
|
+
constructor(gaps) {
|
|
20
|
+
super(gaps.join("; "));
|
|
21
|
+
this.gaps = gaps;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Reads who the token is and what it may do: auth.test's granted scopes (a response header), then the app behind the bot. */
|
|
25
|
+
export async function slackStanding(base, token) {
|
|
26
|
+
const auth = await fetch(`${base}/auth.test`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15_000) });
|
|
27
|
+
const body = await auth.json();
|
|
28
|
+
if (body.ok !== true)
|
|
29
|
+
throw new SlackRefused("auth.test", String(body.error ?? "unknown"));
|
|
30
|
+
const granted = String(auth.headers.get("x-oauth-scopes") ?? "").split(",").map((s) => s.trim()).filter((s) => s !== "");
|
|
31
|
+
const bot = (await slackCall(base, token, "bots.info", { bot: String(body.bot_id) })).bot;
|
|
32
|
+
return { appId: bot.app_id, botName: bot.name, granted };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Brings the Slack app to the manifest above through Slack's own app-configuration API, which needs the configuration token of BN settings.
|
|
36
|
+
* Slack asks the workspace owner to approve changed scopes, so a repair that changed them names the one tap left: the reinstall.
|
|
37
|
+
*/
|
|
38
|
+
async function repairManifest(base, configToken, standing, wanted) {
|
|
39
|
+
const current = (await slackCall(base, configToken, "apps.manifest.export", { app_id: standing.appId })).manifest;
|
|
40
|
+
const declared = current.oauth_config?.scopes?.bot ?? [];
|
|
41
|
+
const scopesWhole = wanted.oauth_config.scopes.bot.every((s) => declared.includes(s));
|
|
42
|
+
const messagesOpen = current.features?.app_home?.messages_tab_enabled === true && current.features?.app_home?.messages_tab_read_only_enabled === false;
|
|
43
|
+
if (scopesWhole && messagesOpen && current.features?.bot_user !== undefined)
|
|
44
|
+
return [];
|
|
45
|
+
const merged = { ...current, features: { ...current.features, bot_user: current.features?.bot_user ?? wanted.features.bot_user, app_home: { ...current.features?.app_home, ...wanted.features.app_home } }, oauth_config: { ...current.oauth_config, scopes: { ...current.oauth_config?.scopes, bot: [...new Set([...declared, ...wanted.oauth_config.scopes.bot])] } } };
|
|
46
|
+
await slackCall(base, configToken, "apps.manifest.update", { app_id: standing.appId, manifest: JSON.stringify(merged) });
|
|
47
|
+
return [`the Slack app ${standing.botName} was updated to hold every scope and the Messages tab; Slack needs the workspace owner to approve it once: open https://api.slack.com/apps/${standing.appId}/install-on-team and tap Reinstall`];
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The check BN makes of its own Slack setup: the token's standing, then the repair of what is missing through the same code. Returns what is still
|
|
51
|
+
* missing, each item naming the one act left — empty when the setup is whole.
|
|
52
|
+
*/
|
|
53
|
+
export async function slackVerifyAndRepair(base, token, configToken, appName) {
|
|
54
|
+
const standing = await slackStanding(base, token);
|
|
55
|
+
const missing = SLACK_BOT_SCOPES.filter((s) => s !== "incoming-webhook" && !standing.granted.includes(s));
|
|
56
|
+
if (configToken === undefined) {
|
|
57
|
+
const gaps = missing.length === 0 ? [] : [`the Slack app ${standing.botName} lacks the scopes ${missing.join(", ")}, and BN cannot see or open its App Home Messages tab (without it Slack refuses a direct message to the bot with \"failed to send\"), because BN holds no Slack configuration token to repair it: create one at https://api.slack.com/apps (Your App Configuration Tokens) and paste it into BN settings, Slack, Configuration token`];
|
|
58
|
+
return { standing, gaps };
|
|
59
|
+
}
|
|
60
|
+
return { standing, gaps: await repairManifest(base, configToken, standing, slackAppManifest(appName)) };
|
|
61
|
+
}
|
package/dist/notify.js
CHANGED
|
@@ -24,7 +24,9 @@ import { telegramSendErrorHint } from "./messaging/telegramError.js";
|
|
|
24
24
|
import { postTelegramMessage, telegramParseMode } from "./messaging/telegramFormat.js";
|
|
25
25
|
import { splitForNotify, withLead } from "./chunk.js";
|
|
26
26
|
import { idleNow, playVoice, showBanner } from "./desk.js";
|
|
27
|
-
import { AgentGateway, AGENT_PREFIX, chatTurnText, SLACK_DM, streamedChat } from "./agentGateway.js";
|
|
27
|
+
import { AgentGateway, AGENT_PREFIX, chatTurnText, conversationOfDraft, SLACK_DM, streamedChat } from "./agentGateway.js";
|
|
28
|
+
import { slackVerifyAndRepair } from "./messaging/slackSetup.js";
|
|
29
|
+
import { MESSENGER_SETUPS } from "./messaging/setup.js";
|
|
28
30
|
import { SlackMessenger, SlackRefused, SlackUnknown, SlackUnreachable, slackCall, TelegramMessenger, TelegramRefused, TelegramUnknown, TelegramUnreachable, telegramCall } from "./messaging/messenger.js";
|
|
29
31
|
import { PollCursors, DiscordPlatform, TeamsPlatform, NtfyPlatform, SmsPlatform, listenForever, pollForever } from "./messaging/chatInbound.js";
|
|
30
32
|
import { EmailAgentInbox } from "./messaging/emailInbound.js";
|
|
@@ -1203,7 +1205,7 @@ async function takeTelegramUpdate(token, update) {
|
|
|
1203
1205
|
if (update.stopped_message_generation !== undefined) {
|
|
1204
1206
|
const chat = String(update.stopped_message_generation.chat?.id ?? chatIds[0]);
|
|
1205
1207
|
if (chatIds.includes(chat))
|
|
1206
|
-
toTelegramConversation(token, chat, { kind: "stop" });
|
|
1208
|
+
toTelegramConversation(token, chat, { kind: "stop", conversation: conversationOfDraft(Number(update.stopped_message_generation.draft_id)) });
|
|
1207
1209
|
return;
|
|
1208
1210
|
}
|
|
1209
1211
|
const msg = update.message;
|
|
@@ -1536,7 +1538,8 @@ function slackCreds(secrets = loadSecrets()) {
|
|
|
1536
1538
|
const token = (process.env.SLACK_BOT_TOKEN ?? s.botToken ?? cfgSlack.botToken ?? "").trim() || undefined;
|
|
1537
1539
|
const channel = (process.env.SLACK_CHANNEL_ID ?? s.channelId ?? "").trim() || undefined;
|
|
1538
1540
|
const webhook = (s.webhookUrl ?? cfgSlack.webhookUrl ?? "").trim() || undefined;
|
|
1539
|
-
|
|
1541
|
+
const configToken = (process.env.SLACK_CONFIG_TOKEN ?? s.configToken ?? cfgSlack.configToken ?? "").trim() || undefined;
|
|
1542
|
+
return { token, channel, webhook, configToken };
|
|
1540
1543
|
}
|
|
1541
1544
|
// Brainless config: on startup, copy any credentials already present in the
|
|
1542
1545
|
// secrets file (decoded) into config.json's EMPTY fields, so a user who has the
|
|
@@ -1817,11 +1820,15 @@ function warnIfNoChannelConfigured(cfg) {
|
|
|
1817
1820
|
// reply returned having sent nothing (#771).
|
|
1818
1821
|
async function slackSend(text) {
|
|
1819
1822
|
const { webhook, token, channel } = slackCreds();
|
|
1823
|
+
let webhookFailure = "";
|
|
1820
1824
|
if (webhook) {
|
|
1821
1825
|
const r = await fetch(webhook, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }) });
|
|
1822
|
-
if (
|
|
1823
|
-
|
|
1824
|
-
|
|
1826
|
+
if (r.ok)
|
|
1827
|
+
return;
|
|
1828
|
+
webhookFailure = `slack webhook answered HTTP ${r.status} ${(await r.text().catch(() => "")).slice(0, 200)}`;
|
|
1829
|
+
if (!token || !(channel ?? (loadConfig().slack?.channels ?? [])[0]))
|
|
1830
|
+
throw new Error(webhookFailure);
|
|
1831
|
+
log("·", "slack:error", `${webhookFailure} — the reply goes through the bot token instead`);
|
|
1825
1832
|
}
|
|
1826
1833
|
// The bot token the Connect button saves has no channel of its own, so the
|
|
1827
1834
|
// reply goes to the channel this config names for the app.
|
|
@@ -2115,14 +2122,44 @@ const slackSwitchedOn = () => loadConfig().slack?.enabled === true;
|
|
|
2115
2122
|
const slackDms = new Map();
|
|
2116
2123
|
/** Why the direct message cannot be read with this bot token; it is not tried again until the token changes or BN restarts. */
|
|
2117
2124
|
let slackDmOff;
|
|
2125
|
+
/** Slack's standing of each bot token as the setup check found it, read once per process; what the setup still lacks is logged once and kept for the status surface. */
|
|
2126
|
+
const slackSetupChecked = new Map();
|
|
2127
|
+
function slackSetupOf(token) {
|
|
2128
|
+
const known = slackSetupChecked.get(token);
|
|
2129
|
+
// NULL-OK: field known is OPTIONAL and therefore it is ok to check for NULL
|
|
2130
|
+
if (known !== undefined)
|
|
2131
|
+
return known;
|
|
2132
|
+
const checked = slackVerifyAndRepair(SLACK_API_BASE, token, slackCreds().configToken, "BN").then(({ standing, gaps }) => {
|
|
2133
|
+
log("·", "slack", `setup: app ${standing.botName} holds ${standing.granted.length} scopes${gaps.length === 0 ? ", nothing missing" : ""}`);
|
|
2134
|
+
for (const gap of gaps)
|
|
2135
|
+
log("·", "slack:error", `setup incomplete: ${gap}`);
|
|
2136
|
+
if (gaps.length > 0)
|
|
2137
|
+
slackLastError = gaps.join("; ");
|
|
2138
|
+
return standing;
|
|
2139
|
+
});
|
|
2140
|
+
slackSetupChecked.set(token, checked);
|
|
2141
|
+
// OWNER: the setup check is read once per token — a check that failed is forgotten so the next poll asks Slack again, and its failure reaches the poll loop that awaits it.
|
|
2142
|
+
checked.catch(() => slackSetupChecked.delete(token));
|
|
2143
|
+
return checked;
|
|
2144
|
+
}
|
|
2145
|
+
/** Opens the direct message with the owner: conversations.open when the app holds im:write, else Slack's own opening by a first post to his id, which needs only chat:write. */
|
|
2146
|
+
async function openSlackDm(token, owner, standing) {
|
|
2147
|
+
if (standing.granted.includes("im:write"))
|
|
2148
|
+
return String((await slackCall(SLACK_API_BASE, token, "conversations.open", { users: owner })).channel.id);
|
|
2149
|
+
const opened = await slackCall(SLACK_API_BASE, token, "chat.postMessage", { channel: owner, text: "Hi Meni, this is your BN chat. Type here to talk to your agents." });
|
|
2150
|
+
return String(opened.channel);
|
|
2151
|
+
}
|
|
2118
2152
|
/** Meni's direct-message chat with the bot: the workspace owner's, opened with conversations.open. */
|
|
2119
2153
|
async function slackDmOf(token, owner) {
|
|
2120
2154
|
const known = slackDms.get(token);
|
|
2121
2155
|
// NULL-OK: field known is OPTIONAL and therefore it is ok to check for NULL
|
|
2122
2156
|
if (known !== undefined)
|
|
2123
2157
|
return known;
|
|
2124
|
-
const
|
|
2125
|
-
const
|
|
2158
|
+
const standing = await slackSetupOf(token);
|
|
2159
|
+
const remembered = POLL_CURSORS.get(`slack-dm-channel:${owner}`);
|
|
2160
|
+
const channel = remembered ?? await openSlackDm(token, owner, standing);
|
|
2161
|
+
POLL_CURSORS.set(`slack-dm-channel:${owner}`, channel);
|
|
2162
|
+
const dm = new SlackMessenger(SLACK_API_BASE, token, channel, slackSwitchedOn);
|
|
2126
2163
|
slackDms.set(token, dm);
|
|
2127
2164
|
log("·", "slack", `direct message ${dm.channel} with the workspace owner is a BN conversation: every message he sends the bot there reaches it`);
|
|
2128
2165
|
return dm;
|
|
@@ -2250,6 +2287,113 @@ function smsPlatform() {
|
|
|
2250
2287
|
const queue = () => new SQSClient(awsCredentials(loadConfig()));
|
|
2251
2288
|
return new SmsPlatform(settings, queue, send, e164, log);
|
|
2252
2289
|
}
|
|
2290
|
+
// ── Messenger setup: what is installed reconciled against what Meni configured ─────────────────
|
|
2291
|
+
const freshReport = (messenger, intent) => ({ messenger, intent, installed: [], repaired: [], gaps: [], at: Date.now() });
|
|
2292
|
+
const slackSetup = {
|
|
2293
|
+
name: "slack",
|
|
2294
|
+
intent() {
|
|
2295
|
+
const c = loadConfig().slack ?? {};
|
|
2296
|
+
if (c.enabled !== true)
|
|
2297
|
+
return ["Slack is switched off"];
|
|
2298
|
+
return ["Slack is switched on", `the bus channel ${[...new Set([...(c.channels ?? []), slackCreds().channel].filter((x) => x))].join(", ") || "(none chosen)"}`, "a direct message between the bot and the workspace owner"];
|
|
2299
|
+
},
|
|
2300
|
+
async reconcile() {
|
|
2301
|
+
const report = freshReport("slack", this.intent());
|
|
2302
|
+
if (!slackSwitchedOn())
|
|
2303
|
+
return report;
|
|
2304
|
+
const { token, configToken } = slackCreds();
|
|
2305
|
+
if (token === undefined) {
|
|
2306
|
+
report.gaps.push("no Slack bot token is set in BN settings");
|
|
2307
|
+
return report;
|
|
2308
|
+
}
|
|
2309
|
+
slackSetupChecked.delete(token);
|
|
2310
|
+
slackDmOff = undefined;
|
|
2311
|
+
const { standing, gaps } = await slackVerifyAndRepair(SLACK_API_BASE, token, configToken, "BN");
|
|
2312
|
+
slackSetupChecked.set(token, Promise.resolve(standing));
|
|
2313
|
+
report.installed.push(`the Slack app ${standing.botName} holds ${standing.granted.length} scopes`);
|
|
2314
|
+
report.gaps.push(...gaps);
|
|
2315
|
+
try {
|
|
2316
|
+
const owner = await slackOwner(token);
|
|
2317
|
+
const had = POLL_CURSORS.get(`slack-dm-channel:${owner}`) !== undefined;
|
|
2318
|
+
const dm = await slackDmOf(token, owner);
|
|
2319
|
+
(had ? report.installed : report.repaired).push(`the direct message ${dm.channel} between the bot and the workspace owner is open`);
|
|
2320
|
+
}
|
|
2321
|
+
catch (err) {
|
|
2322
|
+
if (!(err instanceof SlackOwnerUnknown) && !(err instanceof SlackRefused))
|
|
2323
|
+
throw err;
|
|
2324
|
+
// OWNER: the setup pass is its own trigger root — a refusal Slack documents is a gap in the report, naming what Slack said.
|
|
2325
|
+
report.gaps.push(err.message);
|
|
2326
|
+
}
|
|
2327
|
+
for (const channel of [...new Set([...(loadConfig().slack?.channels ?? []), slackCreds().channel].filter((x) => !!x))]) {
|
|
2328
|
+
try {
|
|
2329
|
+
await slackCall(SLACK_API_BASE, token, "conversations.history", { channel, limit: 1 });
|
|
2330
|
+
report.installed.push(`the bot is in the bus channel ${channel}`);
|
|
2331
|
+
}
|
|
2332
|
+
catch (err) {
|
|
2333
|
+
if (!(err instanceof SlackRefused) || err.error !== "not_in_channel") {
|
|
2334
|
+
if (err instanceof SlackRefused) {
|
|
2335
|
+
report.gaps.push(err.message);
|
|
2336
|
+
continue;
|
|
2337
|
+
}
|
|
2338
|
+
throw err;
|
|
2339
|
+
}
|
|
2340
|
+
// OWNER: the setup pass is its own trigger root — a bot outside its bus channel joins it, or the gap names the scope or invitation that is missing.
|
|
2341
|
+
if (standing.granted.includes("channels:join")) {
|
|
2342
|
+
await slackCall(SLACK_API_BASE, token, "conversations.join", { channel });
|
|
2343
|
+
report.repaired.push(`the bot joined the bus channel ${channel}`);
|
|
2344
|
+
}
|
|
2345
|
+
else
|
|
2346
|
+
report.gaps.push(`the bot is not in the bus channel ${channel}: invite it there, or let BN add the channels:join scope`);
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
return report;
|
|
2350
|
+
},
|
|
2351
|
+
};
|
|
2352
|
+
const telegramSetup = {
|
|
2353
|
+
name: "telegram",
|
|
2354
|
+
intent() {
|
|
2355
|
+
const c = loadConfig().telegram ?? {};
|
|
2356
|
+
return c.enabled !== true ? ["Telegram is switched off"] : ["Telegram is switched on", `his chat with the bot (${(c.chatIds ?? []).length === 0 ? "the first chat that writes" : c.chatIds.join(", ")})`, "the bot reads by polling, so no webhook stands in its way"];
|
|
2357
|
+
},
|
|
2358
|
+
async reconcile() {
|
|
2359
|
+
const report = freshReport("telegram", this.intent());
|
|
2360
|
+
const c = loadConfig().telegram ?? {};
|
|
2361
|
+
if (c.enabled !== true)
|
|
2362
|
+
return report;
|
|
2363
|
+
const token = String(c.token ?? "").trim();
|
|
2364
|
+
if (token === "") {
|
|
2365
|
+
report.gaps.push("no Telegram bot token is set in BN settings");
|
|
2366
|
+
return report;
|
|
2367
|
+
}
|
|
2368
|
+
const me = await telegramCall(tgApi(token, "getMe"), "getMe");
|
|
2369
|
+
report.installed.push(`the bot @${me.username} answers`);
|
|
2370
|
+
const hook = await telegramCall(tgApi(token, "getWebhookInfo"), "getWebhookInfo");
|
|
2371
|
+
if (String(hook.url ?? "") === "")
|
|
2372
|
+
report.installed.push("no webhook stands in the way of polling");
|
|
2373
|
+
else {
|
|
2374
|
+
await telegramCall(tgApi(token, "deleteWebhook"), "deleteWebhook");
|
|
2375
|
+
report.repaired.push("a webhook that blocked polling was removed");
|
|
2376
|
+
}
|
|
2377
|
+
return report;
|
|
2378
|
+
},
|
|
2379
|
+
};
|
|
2380
|
+
MESSENGER_SETUPS.add(slackSetup);
|
|
2381
|
+
MESSENGER_SETUPS.add(telegramSetup);
|
|
2382
|
+
/** The one start-time pass: every messenger's setup reconciles once, each report logged; a refusal or an unreachable service is said and the daemon goes on. */
|
|
2383
|
+
async function reconcileMessengersAtStart() {
|
|
2384
|
+
for (const name of ["slack", "telegram"]) {
|
|
2385
|
+
try {
|
|
2386
|
+
const r = await MESSENGER_SETUPS.reconcile(name);
|
|
2387
|
+
log("·", name, `setup: ${r.installed.length} in place, ${r.repaired.length} repaired, ${r.gaps.length} missing${r.gaps.length > 0 ? ` — ${r.gaps.join("; ")}` : ""}`);
|
|
2388
|
+
if (name === "slack" && r.gaps.length > 0)
|
|
2389
|
+
slackRecordFailed(new Error(r.gaps.join("; ")));
|
|
2390
|
+
}
|
|
2391
|
+
catch (err) {
|
|
2392
|
+
// OWNER: the daemon's start is the trigger root of this pass — a messenger whose setup could not be read (Slack or Telegram out of reach, a revoked token) is logged with its reason and the others still reconcile.
|
|
2393
|
+
log("·", `${name}:error`, `setup could not be checked: ${err instanceof Error ? err.message : String(err)}`);
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2253
2397
|
// ── The channel pollers: run by the gateway owner, and stopped when it hands the gateway over ────────────────
|
|
2254
2398
|
let pollersWanted = false;
|
|
2255
2399
|
let pollerRuns = [];
|
|
@@ -2257,6 +2401,7 @@ let inboundPlatforms;
|
|
|
2257
2401
|
let mailInbox;
|
|
2258
2402
|
function startPollers() {
|
|
2259
2403
|
pollersWanted = true;
|
|
2404
|
+
void reconcileMessengersAtStart();
|
|
2260
2405
|
inboundPlatforms ??= [[discordPlatform(), 2000], [teamsPlatform(), 5000], [ntfyPlatform(), 2000], [smsPlatform(), 0]];
|
|
2261
2406
|
const inbox = (mailInbox ??= emailAgentInbox());
|
|
2262
2407
|
pollerRuns = [
|
|
@@ -3263,12 +3263,12 @@ export function readQueueStore(board) {
|
|
|
3263
3263
|
// NULL-OK: field stored is OPTIONAL and therefore it is ok to check for NULL
|
|
3264
3264
|
return stored === undefined ? { v: STORY_QUEUE_WIRE, nextSeq: 1, entries: [] } : withoutRepeatedSteps(stored);
|
|
3265
3265
|
}
|
|
3266
|
-
/** 🔴 #4581 — the two ways work stands still that ask FleetView's
|
|
3266
|
+
/** 🔴 #4581 — the two ways work stands still that ask FleetView's progress checker: Meni, 2026-11-27, *"fv for queue without agents and for bb stories without agents or queue"*. */
|
|
3267
3267
|
export const CLOG_TRIGGERS = ["queue without agents", "stories without agents or queue"];
|
|
3268
|
-
// GATE: how long a stuck set must stand before the
|
|
3268
|
+
// GATE: how long a stuck set must stand before the progress check is asked — a pass about to start it, or a hand-over in flight, is never checked
|
|
3269
3269
|
export const CLOG_SETTLE_MS = 5 * 60_000;
|
|
3270
3270
|
const clogFile = (board, trigger) => path.join(storyQueueDir(board), "clog", `${trigger === "queue without agents" ? "fleetview" : "backlog"}.json`);
|
|
3271
|
-
/** 🔴 #4581 — a trigger reports what stands still; its own file, its one writer. The set's `since` holds while the set is unchanged, so the
|
|
3271
|
+
/** 🔴 #4581 — a trigger reports what stands still; its own file, its one writer. The set's `since` holds while the set is unchanged, so the progress check sees how long it has stood; nothing is written when nothing changed. */
|
|
3272
3272
|
export function reportClog(board, trigger, stuck, now) {
|
|
3273
3273
|
const file = clogFile(board, trigger);
|
|
3274
3274
|
const ids = [...new Set(stuck)].sort((a, b) => a - b);
|
|
@@ -3292,6 +3292,12 @@ export function queueClog(store) {
|
|
|
3292
3292
|
return [];
|
|
3293
3293
|
return store.entries.filter((e) => e.state === "queued" || e.state === "retrying" || e.state === "failed").map((e) => e.storyId);
|
|
3294
3294
|
}
|
|
3295
|
+
/** 🔴 #4581 — the story's standing request is his Start press, still asking: a FleetView restart keeps its row in line, and AUTO START off still holds a row whose worker his press already started. */
|
|
3296
|
+
function inLineByHisPress(board, storyId) {
|
|
3297
|
+
const r = readableRequestView(board, storyId);
|
|
3298
|
+
// NULL-OK: field r is OPTIONAL and therefore it is ok to check for NULL
|
|
3299
|
+
return r !== undefined && r.origin === "press" && r.eligible;
|
|
3300
|
+
}
|
|
3295
3301
|
function withdrawUntilAsked(board, e, now, why) {
|
|
3296
3302
|
delete e.forced;
|
|
3297
3303
|
delete e.forcedBy;
|
|
@@ -3313,9 +3319,10 @@ export async function clearStoryQueue(board, since) {
|
|
|
3313
3319
|
// NULL-OK: field pressedAt is OPTIONAL and therefore it is ok to check for NULL
|
|
3314
3320
|
return r !== undefined && r.origin === "press" && r.eligible && r.pressedAt !== undefined && (r.forced ?? r.pressedAt) > priorAuthorityOf(store.entries.find((e) => e.storyId === id));
|
|
3315
3321
|
}));
|
|
3322
|
+
const pressedInLine = new Set(store.entries.filter((e) => IN_LINE.has(e.state) && inLineByHisPress(board, e.storyId)));
|
|
3316
3323
|
// NULL-OK: field worker/archivedSessions/lastSession/handStop is OPTIONAL and therefore it is ok to check for NULL
|
|
3317
|
-
const kept = store.entries.filter((e) => e.worker !== undefined || e.archivedSessions !== undefined || e.lastSession !== undefined || e.handStop !== undefined || (e.forceEventAt ?? 0) >= since || his.has(e));
|
|
3318
|
-
const working = new Set([...kept.filter((e) => e.state === "starting" || e.state === "running" || (e.forceEventAt ?? 0) >= since || his.has(e)).map((e) => e.storyId), ...untaken]);
|
|
3324
|
+
const kept = store.entries.filter((e) => e.worker !== undefined || e.archivedSessions !== undefined || e.lastSession !== undefined || e.handStop !== undefined || (e.forceEventAt ?? 0) >= since || his.has(e) || pressedInLine.has(e));
|
|
3325
|
+
const working = new Set([...kept.filter((e) => e.state === "starting" || e.state === "running" || (e.forceEventAt ?? 0) >= since || his.has(e)).map((e) => e.storyId), ...[...pressedInLine].map((e) => e.storyId), ...untaken]);
|
|
3319
3326
|
let removed = store.entries.length - kept.length;
|
|
3320
3327
|
const now = Date.now();
|
|
3321
3328
|
for (const e of kept) {
|
|
@@ -214,7 +214,7 @@ export function createClaudeDriver(runtime) {
|
|
|
214
214
|
...(atRoot ? runtime.store.listedFolders().flatMap((folder) => ["--add-dir", folder]) : []),
|
|
215
215
|
...(spec.model === undefined ? [] : ["--model", spec.model]),
|
|
216
216
|
...(spec.title === undefined || this.resumes ? [] : ["--name", spec.title]),
|
|
217
|
-
...(this.resumes ? ["--resume", spec.sessionId] : ["--session-id", spec.sessionId]),
|
|
217
|
+
...(this.resumes ? ["--resume", spec.sessionId] : spec.forkOf !== undefined && transcriptWritten(spec.forkOf) ? ["--resume", spec.forkOf, "--fork-session", "--session-id", spec.sessionId] : ["--session-id", spec.sessionId]),
|
|
218
218
|
"--permission-mode", "bypassPermissions", "--disallowedTools", BN_REACHES_HIM_ON_THE_PAGE, "--settings", settings,
|
|
219
219
|
], { CLAUDE_CODE_NO_FLICKER: "1", ...(atRoot ? { CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: "1" } : {}) });
|
|
220
220
|
let draw;
|
|
@@ -831,7 +831,7 @@ export function createConversationStore(host, registry) {
|
|
|
831
831
|
const beside = input.chat === undefined ? undefined : openConversationOf(input.chat)?.id;
|
|
832
832
|
const meta = {
|
|
833
833
|
id: randomUUID(), platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project: input.project, provider: input.provider, model: input.model,
|
|
834
|
-
state: input.state, createdAt: now, updatedAt: now, lastMessageAt: now, sessionId: randomUUID(), started: false, consumed: 0, beside,
|
|
834
|
+
state: input.state, createdAt: now, updatedAt: now, lastMessageAt: now, sessionId: randomUUID(), started: false, consumed: 0, beside, forkOf: input.forkOf,
|
|
835
835
|
};
|
|
836
836
|
writeMeta(meta);
|
|
837
837
|
return meta;
|
|
@@ -841,7 +841,7 @@ export function createConversationStore(host, registry) {
|
|
|
841
841
|
requireConversationEnabled();
|
|
842
842
|
const project = createdFolder(input.project);
|
|
843
843
|
const provider = namedProvider(input.provider);
|
|
844
|
-
const meta = newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project, provider, model: input.model, state: "queued" });
|
|
844
|
+
const meta = newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project, provider, model: input.model, forkOf: input.forkOf, state: "queued" });
|
|
845
845
|
appendEvent(meta.id, { role: "user", text: input.text, receivedMs: input.receivedMs, ...input.arrival });
|
|
846
846
|
return meta;
|
|
847
847
|
}
|
|
@@ -253,7 +253,7 @@ export function sessionDriverClass(runtime) {
|
|
|
253
253
|
};
|
|
254
254
|
let session;
|
|
255
255
|
try {
|
|
256
|
-
session = claude.open(this.specFor({ project, sessionId, started: false, name: "bn-warm", title: undefined, model: undefined, provider: claude, target }));
|
|
256
|
+
session = claude.open(this.specFor({ project, sessionId, started: false, forkOf: undefined, name: "bn-warm", title: undefined, model: undefined, provider: claude, target }));
|
|
257
257
|
}
|
|
258
258
|
catch (err) {
|
|
259
259
|
if (!(err instanceof AgentTurnFailed))
|
|
@@ -268,7 +268,7 @@ export function sessionDriverClass(runtime) {
|
|
|
268
268
|
/** The spare, if it fits this conversation's first turn in `project`; it is taken out of the pool and the record is given its session id. */
|
|
269
269
|
takeSpare(c, provider, project) {
|
|
270
270
|
const spare = this.spare;
|
|
271
|
-
if (spare === undefined || provider.name !== "claude" || c.started || this.resuming.has(c.id) || c.model !== undefined || project !== spare.project)
|
|
271
|
+
if (spare === undefined || provider.name !== "claude" || c.started || c.forkOf !== undefined || this.resuming.has(c.id) || c.model !== undefined || project !== spare.project)
|
|
272
272
|
return undefined;
|
|
273
273
|
this.spare = undefined;
|
|
274
274
|
updateConversation(c.id, { sessionId: spare.sessionId });
|
|
@@ -459,7 +459,7 @@ export function sessionDriverClass(runtime) {
|
|
|
459
459
|
if (c.providerArchived !== true || !c.started || unarchive === undefined)
|
|
460
460
|
return;
|
|
461
461
|
const target = { id: c.id, onGone: () => { }, isStarted: () => c.started };
|
|
462
|
-
const spec = this.specFor({ project, sessionId: c.sessionId, started: c.started, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
|
|
462
|
+
const spec = this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
|
|
463
463
|
await unarchive(spec, c.sessionId).then(() => { updateConversation(c.id, { providerArchived: undefined }); }, (error) => {
|
|
464
464
|
appendEvent(c.id, { role: "system", kind: "status", text: `${provider.label} history could not be restored from its archive: ${error.message}` });
|
|
465
465
|
});
|
|
@@ -482,7 +482,7 @@ export function sessionDriverClass(runtime) {
|
|
|
482
482
|
this.free(c.id, "idle");
|
|
483
483
|
const target = { id: c.id, onGone: () => { }, isStarted: () => c.started };
|
|
484
484
|
const archived = Promise.resolve().then(() => {
|
|
485
|
-
const spec = this.specFor({ project: allowedFolder(c.project), sessionId: c.sessionId, started: c.started, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
|
|
485
|
+
const spec = this.specFor({ project: allowedFolder(c.project), sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
|
|
486
486
|
return archive(spec, c.sessionId);
|
|
487
487
|
}).then(() => { updateConversation(c.id, { providerArchived: true }); shelve(); }, (error) => {
|
|
488
488
|
appendEvent(c.id, { role: "system", kind: "status", text: "Codex history could not be archived: " + error.message });
|
|
@@ -687,6 +687,7 @@ export function sessionDriverClass(runtime) {
|
|
|
687
687
|
project: o.project,
|
|
688
688
|
sessionId: o.sessionId,
|
|
689
689
|
started: o.started,
|
|
690
|
+
forkOf: o.forkOf,
|
|
690
691
|
isStarted: () => target.isStarted(),
|
|
691
692
|
name: o.name,
|
|
692
693
|
title: o.title,
|
|
@@ -710,7 +711,7 @@ export function sessionDriverClass(runtime) {
|
|
|
710
711
|
if (live !== undefined)
|
|
711
712
|
this.gone(c.id, live);
|
|
712
713
|
};
|
|
713
|
-
const session = spare?.session ?? provider.open(this.specFor({ project, sessionId: c.sessionId, started: c.started, name: c.chat ?? c.id, title: titleOf({ ...c, project }, transcript(c.id)), model: c.model, provider, target }));
|
|
714
|
+
const session = spare?.session ?? provider.open(this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: titleOf({ ...c, project }, transcript(c.id)), model: c.model, provider, target }));
|
|
714
715
|
live = {
|
|
715
716
|
session, provider, project, busy: true, usedAt: Date.now(), turn: 0, turnStartedAt: Date.now(), logAt: transcript(c.id).at(-1)?.n ?? 0,
|
|
716
717
|
ended: () => { }, settleStalled: () => { }, stalled: false, lastOutputAt: Date.now(),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omni-notify-mcp",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.461",
|
|
4
4
|
"homepage": "https://www.npmjs.com/package/omni-notify-mcp",
|
|
5
5
|
"description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
|
|
6
6
|
"main": "dist/daemon.js",
|