omni-notify-mcp 1.3.463 → 1.3.466
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 +2 -2
- package/dist/messaging/emailInbound.js +21 -7
- package/dist/messaging/notificationEngine.js +7 -3
- package/dist/notify.js +50 -95
- package/dist/shared/agentSession.js +29 -87
- package/dist/shared/conversation/opencodeEvents/server.mjs +25 -26
- package/dist/shared/conversation/sessionDriver.js +1 -1
- package/package.json +1 -1
- package/scripts/shared/ownerGuard.cs +665 -0
- package/scripts/shared/ownerGuard.ps1 +31 -0
- package/dist/channelReading.cjs +0 -18
- package/dist/gatewayInstall.cjs +0 -59
- package/dist/mcpHosts.cjs +0 -454
- package/dist/shared/webhost/package.json +0 -1
package/dist/agentGateway.js
CHANGED
|
@@ -170,9 +170,9 @@ export class AgentGateway {
|
|
|
170
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)}` }));
|
|
171
171
|
}
|
|
172
172
|
}
|
|
173
|
-
/** No chat message waiting on its conversation's creation: the gateway can pass to another process without losing one.
|
|
173
|
+
/** 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. */
|
|
174
174
|
quiet() {
|
|
175
|
-
return !creationsPending();
|
|
175
|
+
return this.driver.quiet() && !creationsPending() && [...this.turns.values()].every((turns) => turns.size === 0);
|
|
176
176
|
}
|
|
177
177
|
/** Gives the store back when this process hands the gateway over. */
|
|
178
178
|
async shutdown() {
|
|
@@ -263,11 +263,9 @@ 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
|
-
|
|
267
|
-
const { user
|
|
268
|
-
|
|
269
|
-
const transport = createTransport({ ...server, auth: { user: user, pass: pass } });
|
|
270
|
-
const message = {
|
|
266
|
+
answer(mail, subject, text) {
|
|
267
|
+
const { user } = this.account();
|
|
268
|
+
return this.mail({
|
|
271
269
|
from: { name: "BN agent", address: user },
|
|
272
270
|
to: user,
|
|
273
271
|
replyTo: agentAddress(user),
|
|
@@ -276,7 +274,23 @@ export class EmailAgentInbox {
|
|
|
276
274
|
references: [...mail.references, mail.messageId],
|
|
277
275
|
headers: { [AGENT_HEADER]: "answer" },
|
|
278
276
|
text,
|
|
279
|
-
};
|
|
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 } });
|
|
280
294
|
for (let attempt = 1;; attempt++) {
|
|
281
295
|
try {
|
|
282
296
|
await transport.sendMail(message);
|
|
@@ -284,7 +298,7 @@ export class EmailAgentInbox {
|
|
|
284
298
|
}
|
|
285
299
|
catch (err) {
|
|
286
300
|
if (attempt >= SMTP_ATTEMPTS || !transientSmtp(err))
|
|
287
|
-
throw new Error(`${server.host} did not take the
|
|
301
|
+
throw new Error(`${server.host} did not take the mail after ${attempt} attempt(s): ${err instanceof Error ? err.message : String(err)}`);
|
|
288
302
|
await new Promise((resolve) => setTimeout(resolve, 2000 * 2 ** (attempt - 1)));
|
|
289
303
|
}
|
|
290
304
|
}
|
|
@@ -15,6 +15,8 @@ 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"];
|
|
18
20
|
// 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
|
|
19
21
|
const CHANNEL_ROUTES = [
|
|
20
22
|
{ channel: "desktop", priorities: ["normal", "high"], atKeyboard: "desktopSignal" },
|
|
@@ -24,9 +26,10 @@ const CHANNEL_ROUTES = [
|
|
|
24
26
|
{ channel: "slack", priorities: EVERY_PRIORITY, atKeyboard: "channelLog" },
|
|
25
27
|
{ channel: "teams", priorities: EVERY_PRIORITY, atKeyboard: "heldBack" },
|
|
26
28
|
{ channel: "sms", priorities: ["high"], atKeyboard: "heldBack" },
|
|
29
|
+
{ channel: "email", priorities: ["email"], atKeyboard: "heldBack" },
|
|
27
30
|
];
|
|
28
31
|
export function describePriorityRouting() {
|
|
29
|
-
return
|
|
32
|
+
return PRIORITIES
|
|
30
33
|
.map((priority) => `${priority}=${CHANNEL_ROUTES.filter((route) => route.priorities.includes(priority)).map((route) => route.channel).join("+")}`)
|
|
31
34
|
.join("; ");
|
|
32
35
|
}
|
|
@@ -42,12 +45,12 @@ export function computeDesktopOnlyMode(priority, policy, ctx) {
|
|
|
42
45
|
reason: "DND active — every priority is held, no channel was attempted",
|
|
43
46
|
};
|
|
44
47
|
}
|
|
45
|
-
if (priority === "high") {
|
|
48
|
+
if (priority === "high" || priority === "email") {
|
|
46
49
|
return {
|
|
47
50
|
desktopOnly: false,
|
|
48
51
|
idle: ctx.idle,
|
|
49
52
|
idleKnown,
|
|
50
|
-
reason:
|
|
53
|
+
reason: `priority=${priority} — every enabled channel of that priority is used and activity gating is waived`,
|
|
51
54
|
};
|
|
52
55
|
}
|
|
53
56
|
// The measurement FAILED: a deliberate fail-open. Stated as its own branch so
|
|
@@ -108,6 +111,7 @@ export async function sendWithRouting(options) {
|
|
|
108
111
|
slack: options.enableSlack,
|
|
109
112
|
teams: options.enableTeams,
|
|
110
113
|
sms: options.enableSms,
|
|
114
|
+
email: options.enableEmail,
|
|
111
115
|
};
|
|
112
116
|
const decision = computeDesktopOnlyMode(priority, policy, ctx);
|
|
113
117
|
if (decision.suppressedReason === "dnd") {
|
package/dist/notify.js
CHANGED
|
@@ -452,6 +452,7 @@ async function sendNotification(message, priority, client, buttons) {
|
|
|
452
452
|
enableDiscord: able.discord,
|
|
453
453
|
enableSlack: able.slack,
|
|
454
454
|
enableTeams: able.teams,
|
|
455
|
+
enableEmail: able.email,
|
|
455
456
|
senders: measuredSends({
|
|
456
457
|
desktop: async () => {
|
|
457
458
|
if (cfg.desktop?.tts) {
|
|
@@ -567,6 +568,7 @@ async function sendNotification(message, priority, client, buttons) {
|
|
|
567
568
|
if (!r.ok)
|
|
568
569
|
throw new Error(`Teams ${r.status}: ${await r.text()}`);
|
|
569
570
|
},
|
|
571
|
+
email: () => (mailInbox ??= emailAgentInbox()).notifyOwner(message),
|
|
570
572
|
}),
|
|
571
573
|
});
|
|
572
574
|
if (result.suppressedReason) {
|
|
@@ -854,7 +856,7 @@ function writeInboxDrop(entry) {
|
|
|
854
856
|
const safeTs = entry.ts.replace(/[:.]/g, "-");
|
|
855
857
|
const tagPart = entry.tag ? `.${entry.tag}` : "";
|
|
856
858
|
const path = join(INBOX_DROP_DIR, `${safeTs}${tagPart}.md`);
|
|
857
|
-
const header =
|
|
859
|
+
const header = `# Unsolicited user message\n\n` +
|
|
858
860
|
`- Time: ${entry.ts}\n` +
|
|
859
861
|
(entry.tag ? `- Tag: @${entry.tag}\n` : "") +
|
|
860
862
|
`- Origin: ${entry.origin ?? "user"} (out-of-band)\n\n`;
|
|
@@ -1137,23 +1139,15 @@ async function telegramSendTo(token, chatId, text, replyTo) {
|
|
|
1137
1139
|
if (loadConfig().telegram?.enabled !== true)
|
|
1138
1140
|
throw new Error("Telegram is switched off in BN settings, so nothing is sent to it");
|
|
1139
1141
|
const { response: r, unformatted } = await postTelegramMessage(tgApi(token, "sendMessage"), { chat_id: chatId, text, reply_to_message_id: replyTo }, telegramParseMode(loadConfig()), AbortSignal.timeout(15_000));
|
|
1140
|
-
if (!r.ok)
|
|
1141
|
-
|
|
1142
|
-
recordReach("telegram", false, "a reply in his chat", refused);
|
|
1143
|
-
throw new Error(refused);
|
|
1144
|
-
}
|
|
1145
|
-
recordReach("telegram", true, "a reply in his chat", "Telegram took the message");
|
|
1142
|
+
if (!r.ok)
|
|
1143
|
+
throw new Error(await telegramSendErrorHint(r));
|
|
1146
1144
|
if (unformatted)
|
|
1147
1145
|
log("→", "telegram:format", `reply to ${chatId} went out UNFORMATTED — Telegram refused the formatting (can't parse entities)`);
|
|
1148
1146
|
}
|
|
1149
1147
|
// GATE: the update kinds the bot asks Telegram for — his messages, his taps on a button, and his stop on a streamed reply.
|
|
1150
1148
|
const TELEGRAM_UPDATES = ["message", "callback_query", "stopped_message_generation"];
|
|
1151
|
-
/** The bot token a refusal stopped the poller for
|
|
1149
|
+
/** The bot token a refusal stopped the poller for: it polls again only once BN settings hold another. */
|
|
1152
1150
|
let tgStoppedFor;
|
|
1153
|
-
let tgStoppedWhy = "";
|
|
1154
|
-
/** When getUpdates last answered this process, and when it last read an update (his message, tap or stop): the inbound half of Telegram's carriage. */
|
|
1155
|
-
let tgPolledAt = 0;
|
|
1156
|
-
let tgLastUpdateAt = 0;
|
|
1157
1151
|
const TELEGRAM_WELCOME = "🔗 This chat is your BN agent now.\n\nWrite anything — a question, a request, any project — and the agent answers here while it works. Its questions come as buttons; tap one or just answer in your own words.\n\n/new starts a fresh conversation · /stop stops the current turn";
|
|
1158
1152
|
/** The bound chat (#4453): one private chat whose id is a configured chat and whose sender is that chat's own user. */
|
|
1159
1153
|
function boundTelegramChat(chatIds, chat, sender) {
|
|
@@ -1382,7 +1376,6 @@ async function startTelegramListener() {
|
|
|
1382
1376
|
continue;
|
|
1383
1377
|
}
|
|
1384
1378
|
tgStoppedFor = undefined;
|
|
1385
|
-
tgStoppedWhy = "";
|
|
1386
1379
|
const bot = token.split(":")[0];
|
|
1387
1380
|
const cursorKey = `telegram:${bot}`;
|
|
1388
1381
|
if (bot !== tgPollBot) {
|
|
@@ -1401,7 +1394,6 @@ async function startTelegramListener() {
|
|
|
1401
1394
|
log("·", "telegram", `listener ready for bot ${bot}, offset=${tgPollOffset}`);
|
|
1402
1395
|
}
|
|
1403
1396
|
const updates = await telegramCall(tgApi(token, `getUpdates?offset=${tgPollOffset}&timeout=10&allowed_updates=${encodeURIComponent(JSON.stringify(TELEGRAM_UPDATES))}`), "getUpdates", undefined, 1, 15_000);
|
|
1404
|
-
tgPolledAt = Date.now();
|
|
1405
1397
|
if (tgConsecutiveErrors > 0) {
|
|
1406
1398
|
log("·", "telegram", `recovered after ${tgConsecutiveErrors} failed attempt(s)`);
|
|
1407
1399
|
tgConsecutiveErrors = 0;
|
|
@@ -1411,7 +1403,6 @@ async function startTelegramListener() {
|
|
|
1411
1403
|
for (const update of updates) {
|
|
1412
1404
|
POLL_CURSORS.set(cursorKey, String(update.update_id));
|
|
1413
1405
|
tgPollOffset = update.update_id + 1;
|
|
1414
|
-
tgLastUpdateAt = Date.now();
|
|
1415
1406
|
await takeTelegramUpdate(token, update).catch((err) => {
|
|
1416
1407
|
// OWNER: ITER/LOOP — one update that cannot be acted on is logged with its reason (with its stack when it is no failure Telegram's own answer explains), and the next update is still read.
|
|
1417
1408
|
const classified = err instanceof TelegramRefused || err instanceof TelegramUnreachable || err instanceof TelegramUnknown;
|
|
@@ -1424,7 +1415,6 @@ async function startTelegramListener() {
|
|
|
1424
1415
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1425
1416
|
if ((err instanceof TelegramRefused && err.status !== 409) || err instanceof TelegramUnknown) {
|
|
1426
1417
|
tgStoppedFor = token;
|
|
1427
|
-
tgStoppedWhy = msg;
|
|
1428
1418
|
log("·", "telegram:error", `the poller STOPPED: ${msg} — it polls again once BN settings hold another bot token`);
|
|
1429
1419
|
continue;
|
|
1430
1420
|
}
|
|
@@ -1699,48 +1689,35 @@ async function probeTelegramReach(token) {
|
|
|
1699
1689
|
return { ok: false, at: Date.now(), by: "a getMe probe", detail: err instanceof Error ? err.message : String(err) };
|
|
1700
1690
|
}
|
|
1701
1691
|
}
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
}
|
|
1713
|
-
/** Telegram carries only both ways: its outbound reading (a send, an ask or a getMe probe) AND its poller reading his replies; a dead poller is a channel that cannot carry, whatever the token answers. */
|
|
1714
|
-
function telegramCarriage(outbound) {
|
|
1715
|
-
// NULL-OK: field outbound is OPTIONAL and therefore it is ok to check for NULL
|
|
1716
|
-
if (door === undefined && lastOtherBn !== "")
|
|
1717
|
-
return outbound === undefined ? undefined : { ...outbound, detail: `${outbound.detail}; his replies are read by the BN on ${lastOtherBn}, which this process does not poll` };
|
|
1718
|
-
const heard = tgLastUpdateAt === 0 ? "nothing of his has arrived in this process" : `his last message or tap arrived ${ageLabel(tgLastUpdateAt)} ago`;
|
|
1719
|
-
const gap = telegramInboundGap();
|
|
1720
|
-
// NULL-OK: field gap is OPTIONAL and therefore it is ok to check for NULL
|
|
1721
|
-
if (gap !== undefined)
|
|
1722
|
-
return { ok: false, at: Date.now(), by: "the inbound poller", detail: `his replies and taps are NOT being read — ${gap}; ${heard}` };
|
|
1723
|
-
// NULL-OK: field outbound is OPTIONAL and therefore it is ok to check for NULL
|
|
1724
|
-
if (outbound === undefined || !outbound.ok)
|
|
1725
|
-
return outbound;
|
|
1726
|
-
return { ok: true, at: outbound.at, by: `${outbound.by} and the inbound poller`, detail: `${outbound.detail}; the poller read Telegram ${ageLabel(tgPolledAt)} ago; ${heard}` };
|
|
1692
|
+
async function probeEmailReach() {
|
|
1693
|
+
try {
|
|
1694
|
+
await (mailInbox ??= emailAgentInbox()).verify();
|
|
1695
|
+
return { ok: true, at: Date.now(), by: "an SMTP login check", detail: "the email account's SMTP server took its login" };
|
|
1696
|
+
}
|
|
1697
|
+
catch (err) {
|
|
1698
|
+
if (!(err instanceof Error))
|
|
1699
|
+
throw err;
|
|
1700
|
+
// OWNER: a throwing probe would take down the caller that asked for it, and no caller may die of a dead channel — the server's refusal is RECORDED as a reading and rendered (a console line and the delivery report). Nothing leaves this catch.
|
|
1701
|
+
return { ok: false, at: Date.now(), by: "an SMTP login check", detail: err.message };
|
|
1702
|
+
}
|
|
1727
1703
|
}
|
|
1728
1704
|
// The measurement is taken where the transport is; a probe that fails is a RESULT
|
|
1729
1705
|
// recorded here, never a throw that takes the caller with it.
|
|
1730
1706
|
function measureReach(channel, cfg) {
|
|
1731
1707
|
const probing = channel === "telegram"
|
|
1732
1708
|
? (cfg.telegram?.token ? probeTelegramReach(cfg.telegram.token) : null)
|
|
1733
|
-
: null;
|
|
1709
|
+
: channel === "email" ? probeEmailReach() : null;
|
|
1734
1710
|
if (!probing)
|
|
1735
1711
|
return null;
|
|
1736
1712
|
return probing.then((reach) => { recordReach(channel, reach.ok, reach.by, reach.detail); return reach; });
|
|
1737
1713
|
}
|
|
1714
|
+
// The channels an `ask` question can ride and wait for its answer on.
|
|
1715
|
+
function askableChannels(cfg) {
|
|
1716
|
+
return cfg.telegram?.enabled && cfg.telegram.token && cfg.telegram.chatIds?.length ? ["telegram"] : [];
|
|
1717
|
+
}
|
|
1738
1718
|
// The channels whose transport this process can verify by itself.
|
|
1739
1719
|
function probeableChannels(cfg) {
|
|
1740
|
-
|
|
1741
|
-
if (cfg.telegram?.enabled && cfg.telegram.token && cfg.telegram.chatIds?.length)
|
|
1742
|
-
channels.push("telegram");
|
|
1743
|
-
return channels;
|
|
1720
|
+
return [...askableChannels(cfg), ...(emailDeliverable(cfg) ? ["email"] : [])];
|
|
1744
1721
|
}
|
|
1745
1722
|
// The measurement must EXIST before anything reads it, so a channel is measured
|
|
1746
1723
|
// the moment its config does: at boot, and again on every config write — which is
|
|
@@ -1768,14 +1745,7 @@ export function deliveryReport() {
|
|
|
1768
1745
|
secretsReadFailure = null;
|
|
1769
1746
|
const able = deliverableChannels(cfg, loadSecretsForReport());
|
|
1770
1747
|
const enabled = Object.keys(able).filter((channel) => able[channel]);
|
|
1771
|
-
const
|
|
1772
|
-
const telegram = telegramCarriage(transportReach.get("telegram"));
|
|
1773
|
-
// NULL-OK: field telegram is OPTIONAL and therefore it is ok to check for NULL
|
|
1774
|
-
if (telegram === undefined)
|
|
1775
|
-
reach.delete("telegram");
|
|
1776
|
-
else
|
|
1777
|
-
reach.set("telegram", telegram);
|
|
1778
|
-
const verdict = deliveryVerdict(enabled, reach);
|
|
1748
|
+
const verdict = deliveryVerdict(enabled, transportReach);
|
|
1779
1749
|
// A secrets file that could not be read is a READ THAT DID NOT HAPPEN, so
|
|
1780
1750
|
// nothing it might hold is claimed OR denied: the report NAMES it and the
|
|
1781
1751
|
// verdict is held unhealthy rather than the channel silently disappearing
|
|
@@ -1818,8 +1788,13 @@ function deliverableChannels(cfg, secrets = loadSecrets()) {
|
|
|
1818
1788
|
slack: !!(cfg.slack?.enabled && ((slackBusChannels(secrets).length && (cfg.slack.botToken || slackCreds(secrets).token)) || cfg.slack.webhookUrl)),
|
|
1819
1789
|
teams: !!(cfg.teams?.enabled && cfg.teams.webhookUrl),
|
|
1820
1790
|
sms: smsDeliverable(cfg),
|
|
1791
|
+
email: emailDeliverable(cfg),
|
|
1821
1792
|
};
|
|
1822
1793
|
}
|
|
1794
|
+
/** #4581 — the email channel can carry a mail: the account the agent's email door signs in with is configured. */
|
|
1795
|
+
function emailDeliverable(cfg) {
|
|
1796
|
+
return !!(cfg.email?.host && cfg.email.user && cfg.email.pass);
|
|
1797
|
+
}
|
|
1823
1798
|
/** The SMS channel can carry a text: enabled, credentialed and naming a number. */
|
|
1824
1799
|
function smsDeliverable(cfg) {
|
|
1825
1800
|
return !!(cfg.sms?.enabled && cfg.sms.accessKeyId && cfg.sms.secretAccessKey && cfg.sms.region && cfg.sms.to?.length);
|
|
@@ -2410,16 +2385,12 @@ let pollersWanted = false;
|
|
|
2410
2385
|
let pollerRuns = [];
|
|
2411
2386
|
let inboundPlatforms;
|
|
2412
2387
|
let mailInbox;
|
|
2413
|
-
/** Why this process runs no poller, or nothing while its pollers run: the inbound half of Telegram's carriage reads it. */
|
|
2414
|
-
let pollersNotRunning = "this process does not hold the gateway, so it runs no poller";
|
|
2415
|
-
/** Every poller is built before any is marked wanted, so a failure to build one leaves none half-started and is thrown to the gateway's start, which holds it as the reason. */
|
|
2416
2388
|
function startPollers() {
|
|
2417
|
-
|
|
2418
|
-
const inbox = (mailInbox ??= emailAgentInbox());
|
|
2389
|
+
pollersWanted = true;
|
|
2419
2390
|
migrateSlackCursors();
|
|
2420
2391
|
reconcileMessengersAtStart();
|
|
2421
|
-
|
|
2422
|
-
|
|
2392
|
+
inboundPlatforms ??= [[discordPlatform(), 2000], [teamsPlatform(), 5000], [ntfyPlatform(), 2000], [smsPlatform(), 0]];
|
|
2393
|
+
const inbox = (mailInbox ??= emailAgentInbox());
|
|
2423
2394
|
pollerRuns = [
|
|
2424
2395
|
startTelegramListener(),
|
|
2425
2396
|
startSlackListener(),
|
|
@@ -2431,7 +2402,6 @@ function startPollers() {
|
|
|
2431
2402
|
/** Each poller finishes the read it is in and returns; resolves once all have. */
|
|
2432
2403
|
async function stopPollers() {
|
|
2433
2404
|
pollersWanted = false;
|
|
2434
|
-
pollersNotRunning = "the pollers were stopped to hand the gateway to another build";
|
|
2435
2405
|
await Promise.all(pollerRuns);
|
|
2436
2406
|
}
|
|
2437
2407
|
// ── MCP server ────────────────────────────────────────────────────────────────
|
|
@@ -2465,23 +2435,14 @@ function drainInboxFor(tag) {
|
|
|
2465
2435
|
// nobody must not be swallowed by the part before it.
|
|
2466
2436
|
async function sendChunked(message, priority, clientId) {
|
|
2467
2437
|
const outcomes = [];
|
|
2468
|
-
|
|
2438
|
+
// #4581 — an email carries the whole message, so the email priority is one mail, never one per part
|
|
2439
|
+
const parts = priority === "email" ? [message] : splitForNotify(message);
|
|
2469
2440
|
const buttons = decisionButtons(message);
|
|
2470
2441
|
for (const [i, chunk] of parts.entries()) {
|
|
2471
2442
|
outcomes.push(await sendNotification(withLead(`[${clientId}]`, chunk), priority, clientId, i === parts.length - 1 ? buttons : undefined));
|
|
2472
2443
|
}
|
|
2473
2444
|
return outcomes;
|
|
2474
2445
|
}
|
|
2475
|
-
/** The inbox as an agent is shown it: his own messages under the header that asks for a reply, and the trading app's dropped alerts under their own, never as his words. */
|
|
2476
|
-
function inboxText(messages) {
|
|
2477
|
-
const line = (m) => `[${m.ts}] ${m.text}`;
|
|
2478
|
-
const his = messages.filter((m) => m.origin !== "drop");
|
|
2479
|
-
const alerts = messages.filter((m) => m.origin === "drop");
|
|
2480
|
-
return [
|
|
2481
|
-
...(his.length > 0 ? [`⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n${his.map(line).join("\n")}`] : []),
|
|
2482
|
-
...(alerts.length > 0 ? [`🚨 APP ALERTS — raised by the trading app's alerting, NOT messages from Meni; never answer one to him as if he wrote it:\n${alerts.map(line).join("\n")}`] : []),
|
|
2483
|
-
].join("\n\n");
|
|
2484
|
-
}
|
|
2485
2446
|
// A tool result that also carries any unsolicited message the user sent while
|
|
2486
2447
|
// the caller was busy, so a notify round-trip is never a deaf one.
|
|
2487
2448
|
function withInbox(text, isError, sessionTag, clientId) {
|
|
@@ -2489,8 +2450,9 @@ function withInbox(text, isError, sessionTag, clientId) {
|
|
|
2489
2450
|
if (messages.length === 0)
|
|
2490
2451
|
return { content: [{ type: "text", text }], isError };
|
|
2491
2452
|
log("·", "poll", `${messages.length} message(s) drained via a notify result`, clientId);
|
|
2453
|
+
const inbox = messages.map((m) => `[${m.ts}] ${m.text}`).join("\n");
|
|
2492
2454
|
return {
|
|
2493
|
-
content: [{ type: "text", text: `${text}\n\n${
|
|
2455
|
+
content: [{ type: "text", text: `${text}\n\n⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n${inbox}` }],
|
|
2494
2456
|
isError,
|
|
2495
2457
|
};
|
|
2496
2458
|
}
|
|
@@ -2499,7 +2461,8 @@ function appendInbox(baseText, sessionTag, clientId) {
|
|
|
2499
2461
|
if (messages.length === 0)
|
|
2500
2462
|
return baseText;
|
|
2501
2463
|
log("·", "poll", `${messages.length} message(s) drained via heartbeat`, clientId);
|
|
2502
|
-
|
|
2464
|
+
const inbox = messages.map(m => `[${m.ts}] ${m.text}`).join("\n");
|
|
2465
|
+
return `${baseText}\n\n⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n${inbox}`;
|
|
2503
2466
|
}
|
|
2504
2467
|
const MCP_INSTRUCTIONS = `
|
|
2505
2468
|
This server is how a board decision, or an answer to something the user
|
|
@@ -2676,8 +2639,8 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2676
2639
|
"is split for you into numbered '(1/N) ...' parts, each 500 characters or less, and " +
|
|
2677
2640
|
"delivered in order. Never truncate to fit a part.", {
|
|
2678
2641
|
message: z.string().max(5000).describe("Notification message — up to 5000 chars; the server splits it into numbered parts"),
|
|
2679
|
-
priority: z.enum(["low", "normal", "high"]).default("normal")
|
|
2680
|
-
.describe(`Channels per priority, each only when enabled: ${describePriorityRouting()} — high also
|
|
2642
|
+
priority: z.enum(["low", "normal", "high", "email"]).default("normal")
|
|
2643
|
+
.describe(`Channels per priority, each only when enabled: ${describePriorityRouting()} — high and email also bypass activity gating (neither overrides DND); email sends the whole message as one mail, the last step for a board decision nothing else got answered`),
|
|
2681
2644
|
answers: z.string().max(2000).optional()
|
|
2682
2645
|
.describe("The user's own words, verbatim, of the request this notification answers. Required unless the message is a board decision carrying its decision link."),
|
|
2683
2646
|
}, async ({ message, priority, answers }) => {
|
|
@@ -2746,7 +2709,7 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2746
2709
|
// whether a token is present — a revoked token satisfied the config check
|
|
2747
2710
|
// for four months and every question rode it into the void.
|
|
2748
2711
|
// #4451: only a channel that is switched on, with its token and chats, is a candidate — measureReach alone reads the token, so a Telegram switched off in settings was still probed, found alive, and asked through.
|
|
2749
|
-
const askCandidates =
|
|
2712
|
+
const askCandidates = askableChannels(cfg);
|
|
2750
2713
|
const askSkipNotes = [];
|
|
2751
2714
|
const askFormatNotes = [];
|
|
2752
2715
|
// Measured now, per candidate: what cannot carry is absent from `canCarry`.
|
|
@@ -2911,7 +2874,7 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2911
2874
|
return {
|
|
2912
2875
|
content: [{
|
|
2913
2876
|
type: "text",
|
|
2914
|
-
text:
|
|
2877
|
+
text: `⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n` + messages.map(m => `[${m.ts}] ${m.text}`).join("\n"),
|
|
2915
2878
|
}],
|
|
2916
2879
|
};
|
|
2917
2880
|
});
|
|
@@ -2931,7 +2894,8 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2931
2894
|
// drain and return them without parking a waiter.
|
|
2932
2895
|
const queued = drainInboxFor(sessionTag);
|
|
2933
2896
|
if (queued.length > 0) {
|
|
2934
|
-
|
|
2897
|
+
const body = queued.map(m => `[${m.ts}] ${m.text}`).join("\n");
|
|
2898
|
+
return { content: [{ type: "text", text: `⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n${body}` }] };
|
|
2935
2899
|
}
|
|
2936
2900
|
const token = randomUUID();
|
|
2937
2901
|
const entries = await new Promise((resolve) => {
|
|
@@ -2945,7 +2909,8 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2945
2909
|
return { content: [{ type: "text", text: "inbox:empty" }] };
|
|
2946
2910
|
}
|
|
2947
2911
|
log("·", "wait_for_inbox", `${entries.length} message(s) delivered`, clientId);
|
|
2948
|
-
|
|
2912
|
+
const body = entries.map(m => `[${m.ts}] ${m.text}`).join("\n");
|
|
2913
|
+
return { content: [{ type: "text", text: `⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n${body}` }] };
|
|
2949
2914
|
});
|
|
2950
2915
|
server.tool("get_idle_seconds", "Returns how long it has been since the user's last keyboard/mouse input. " +
|
|
2951
2916
|
"Call this periodically during long work as a cheap heartbeat — the server " +
|
|
@@ -3158,7 +3123,7 @@ export function yieldGateway() {
|
|
|
3158
3123
|
}
|
|
3159
3124
|
/**
|
|
3160
3125
|
* Once the extension installs a newer build, this process is superseded and the gateway passes to the installed build:
|
|
3161
|
-
* one that holds it steps aside once no
|
|
3126
|
+
* one that holds it steps aside once no answer is in flight, and then starts the installed build in its place.
|
|
3162
3127
|
*/
|
|
3163
3128
|
function tryOwnGateway(polling, host) {
|
|
3164
3129
|
if (ownershipAttempting)
|
|
@@ -3211,24 +3176,14 @@ function tryOwnGateway(polling, host) {
|
|
|
3211
3176
|
if (polling)
|
|
3212
3177
|
startOwnedWork();
|
|
3213
3178
|
})().catch((err) => {
|
|
3214
|
-
// OWNER:
|
|
3215
|
-
if (door !== undefined) {
|
|
3216
|
-
const stack = err.stack ?? String(err);
|
|
3217
|
-
if (pollersWanted)
|
|
3218
|
-
log("·", "listener", `the gateway's start failed AFTER its pollers started, which still read: ${stack}`);
|
|
3219
|
-
else {
|
|
3220
|
-
pollersNotRunning = `the pollers did not start: ${stack}`;
|
|
3221
|
-
log("·", "listener", pollersNotRunning);
|
|
3222
|
-
}
|
|
3223
|
-
return;
|
|
3224
|
-
}
|
|
3179
|
+
// OWNER: the bind is retried every few seconds; a refusal is logged once per cause so a port held by another program never leaves a silent, pollerless process.
|
|
3225
3180
|
const cause = err.code ?? err.message;
|
|
3226
3181
|
if (cause !== lastBindRefusal)
|
|
3227
3182
|
log("·", "listener", `gateway port not bound (${cause}); staying dormant and retrying every ${OWNERSHIP_RETRY_MS / 1000}s`);
|
|
3228
3183
|
lastBindRefusal = cause;
|
|
3229
3184
|
}).finally(() => { ownershipAttempting = false; });
|
|
3230
3185
|
}
|
|
3231
|
-
/** Hands the gateway over
|
|
3186
|
+
/** Hands the gateway over: the pollers finish their reads, the driver gives the store back, then the port is let go for the installed build to bind. */
|
|
3232
3187
|
async function stepAside(polling, host) {
|
|
3233
3188
|
const gateway = AgentGateway.instance();
|
|
3234
3189
|
if (polling && !gateway.quiet())
|
|
@@ -3282,7 +3237,7 @@ export function startNotifyServer(host) {
|
|
|
3282
3237
|
tryOwnGateway(polling, host);
|
|
3283
3238
|
// a process holding the door is asked again when the installed build's manifest is written, the one thing that
|
|
3284
3239
|
// can supersede it; the beat re-asks only a dormant process, whose owner may be a BN on another machine that no local
|
|
3285
|
-
// event announces, and a superseded one waiting for
|
|
3240
|
+
// event announces, and a superseded one waiting for its gateway to fall quiet before it steps aside.
|
|
3286
3241
|
const ownershipTimer = setInterval(() => {
|
|
3287
3242
|
if (door === undefined || supersededSaid || yielding)
|
|
3288
3243
|
tryOwnGateway(polling, host);
|