omni-notify-mcp 1.3.465 → 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/gateway/panelPage.js +6 -7
- package/dist/messaging/emailInbound.js +21 -7
- package/dist/messaging/notificationEngine.js +7 -3
- package/dist/notify.js +50 -92
- package/dist/shared/agentSession.js +72 -215
- 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() {
|
|
@@ -203,11 +203,11 @@ function control(row) {
|
|
|
203
203
|
}
|
|
204
204
|
return wrap;
|
|
205
205
|
}
|
|
206
|
-
var busy = {}
|
|
206
|
+
var busy = {};
|
|
207
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); }); }
|
|
208
208
|
function setupRow(g) {
|
|
209
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;
|
|
210
|
-
button.
|
|
210
|
+
button.title = "Makes what is installed match what is set above, and shows both";
|
|
211
211
|
facts.setAttribute("aria-label", g.title + " setup");
|
|
212
212
|
factRows(facts, "Intent", g.setup ? g.setup.intent : []);
|
|
213
213
|
factRows(facts, "Installed", last ? (last.installed.length ? last.installed : ["nothing yet"]) : ["not checked yet"]);
|
|
@@ -220,14 +220,13 @@ function setupRow(g) {
|
|
|
220
220
|
busy[g.messenger] = true; button.disabled = true; working.textContent = "⏳ Working";
|
|
221
221
|
try {
|
|
222
222
|
var r = await call("POST", "/v1/messenger-setup", { messenger: g.messenger });
|
|
223
|
-
|
|
223
|
+
button.title = r.gaps.length ? r.gaps.join("\n") : "Everything this messenger needs is in place";
|
|
224
224
|
say(r.gaps.length ? "error" : "good", r.gaps.length ? "⚠️ " + g.messenger.toUpperCase() + " " + r.gaps.length + " MISSING" : "✅ " + g.messenger.toUpperCase() + " INSTALLED");
|
|
225
|
-
} catch (e) {
|
|
226
|
-
busy[g.messenger] = false;
|
|
225
|
+
} catch (e) { button.title = plainWhy(e); say("error", "❌ " + g.messenger.toUpperCase() + " FAILED"); }
|
|
226
|
+
busy[g.messenger] = false;
|
|
227
227
|
await load();
|
|
228
228
|
};
|
|
229
|
-
|
|
230
|
-
cell.colSpan = 2; cell.append(button, working, reason, facts); row.append(cell); return row;
|
|
229
|
+
cell.colSpan = 2; cell.append(button, working, facts); row.append(cell); return row;
|
|
231
230
|
}
|
|
232
231
|
function shownOf(s) { return JSON.stringify([s.state, s.conversation, s.groups, s.configPath]); }
|
|
233
232
|
function draw(s) {
|
|
@@ -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,45 +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
|
-
const heard = tgLastUpdateAt === 0 ? "nothing of his has arrived in this process" : `his last message or tap arrived ${ageLabel(tgLastUpdateAt)} ago`;
|
|
1716
|
-
const gap = telegramInboundGap();
|
|
1717
|
-
// NULL-OK: field gap is OPTIONAL and therefore it is ok to check for NULL
|
|
1718
|
-
if (gap !== undefined)
|
|
1719
|
-
return { ok: false, at: Date.now(), by: "the inbound poller", detail: `his replies and taps are NOT being read — ${gap}; ${heard}` };
|
|
1720
|
-
// NULL-OK: field outbound is OPTIONAL and therefore it is ok to check for NULL
|
|
1721
|
-
if (outbound === undefined || !outbound.ok)
|
|
1722
|
-
return outbound;
|
|
1723
|
-
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
|
+
}
|
|
1724
1703
|
}
|
|
1725
1704
|
// The measurement is taken where the transport is; a probe that fails is a RESULT
|
|
1726
1705
|
// recorded here, never a throw that takes the caller with it.
|
|
1727
1706
|
function measureReach(channel, cfg) {
|
|
1728
1707
|
const probing = channel === "telegram"
|
|
1729
1708
|
? (cfg.telegram?.token ? probeTelegramReach(cfg.telegram.token) : null)
|
|
1730
|
-
: null;
|
|
1709
|
+
: channel === "email" ? probeEmailReach() : null;
|
|
1731
1710
|
if (!probing)
|
|
1732
1711
|
return null;
|
|
1733
1712
|
return probing.then((reach) => { recordReach(channel, reach.ok, reach.by, reach.detail); return reach; });
|
|
1734
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
|
+
}
|
|
1735
1718
|
// The channels whose transport this process can verify by itself.
|
|
1736
1719
|
function probeableChannels(cfg) {
|
|
1737
|
-
|
|
1738
|
-
if (cfg.telegram?.enabled && cfg.telegram.token && cfg.telegram.chatIds?.length)
|
|
1739
|
-
channels.push("telegram");
|
|
1740
|
-
return channels;
|
|
1720
|
+
return [...askableChannels(cfg), ...(emailDeliverable(cfg) ? ["email"] : [])];
|
|
1741
1721
|
}
|
|
1742
1722
|
// The measurement must EXIST before anything reads it, so a channel is measured
|
|
1743
1723
|
// the moment its config does: at boot, and again on every config write — which is
|
|
@@ -1765,14 +1745,7 @@ export function deliveryReport() {
|
|
|
1765
1745
|
secretsReadFailure = null;
|
|
1766
1746
|
const able = deliverableChannels(cfg, loadSecretsForReport());
|
|
1767
1747
|
const enabled = Object.keys(able).filter((channel) => able[channel]);
|
|
1768
|
-
const
|
|
1769
|
-
const telegram = telegramCarriage(transportReach.get("telegram"));
|
|
1770
|
-
// NULL-OK: field telegram is OPTIONAL and therefore it is ok to check for NULL
|
|
1771
|
-
if (telegram === undefined)
|
|
1772
|
-
reach.delete("telegram");
|
|
1773
|
-
else
|
|
1774
|
-
reach.set("telegram", telegram);
|
|
1775
|
-
const verdict = deliveryVerdict(enabled, reach);
|
|
1748
|
+
const verdict = deliveryVerdict(enabled, transportReach);
|
|
1776
1749
|
// A secrets file that could not be read is a READ THAT DID NOT HAPPEN, so
|
|
1777
1750
|
// nothing it might hold is claimed OR denied: the report NAMES it and the
|
|
1778
1751
|
// verdict is held unhealthy rather than the channel silently disappearing
|
|
@@ -1815,8 +1788,13 @@ function deliverableChannels(cfg, secrets = loadSecrets()) {
|
|
|
1815
1788
|
slack: !!(cfg.slack?.enabled && ((slackBusChannels(secrets).length && (cfg.slack.botToken || slackCreds(secrets).token)) || cfg.slack.webhookUrl)),
|
|
1816
1789
|
teams: !!(cfg.teams?.enabled && cfg.teams.webhookUrl),
|
|
1817
1790
|
sms: smsDeliverable(cfg),
|
|
1791
|
+
email: emailDeliverable(cfg),
|
|
1818
1792
|
};
|
|
1819
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
|
+
}
|
|
1820
1798
|
/** The SMS channel can carry a text: enabled, credentialed and naming a number. */
|
|
1821
1799
|
function smsDeliverable(cfg) {
|
|
1822
1800
|
return !!(cfg.sms?.enabled && cfg.sms.accessKeyId && cfg.sms.secretAccessKey && cfg.sms.region && cfg.sms.to?.length);
|
|
@@ -2407,16 +2385,12 @@ let pollersWanted = false;
|
|
|
2407
2385
|
let pollerRuns = [];
|
|
2408
2386
|
let inboundPlatforms;
|
|
2409
2387
|
let mailInbox;
|
|
2410
|
-
/** Why this process runs no poller, or nothing while its pollers run: the inbound half of Telegram's carriage reads it. */
|
|
2411
|
-
let pollersNotRunning = "this process does not hold the gateway, so it runs no poller";
|
|
2412
|
-
/** 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. */
|
|
2413
2388
|
function startPollers() {
|
|
2414
|
-
|
|
2415
|
-
const inbox = (mailInbox ??= emailAgentInbox());
|
|
2389
|
+
pollersWanted = true;
|
|
2416
2390
|
migrateSlackCursors();
|
|
2417
2391
|
reconcileMessengersAtStart();
|
|
2418
|
-
|
|
2419
|
-
|
|
2392
|
+
inboundPlatforms ??= [[discordPlatform(), 2000], [teamsPlatform(), 5000], [ntfyPlatform(), 2000], [smsPlatform(), 0]];
|
|
2393
|
+
const inbox = (mailInbox ??= emailAgentInbox());
|
|
2420
2394
|
pollerRuns = [
|
|
2421
2395
|
startTelegramListener(),
|
|
2422
2396
|
startSlackListener(),
|
|
@@ -2428,7 +2402,6 @@ function startPollers() {
|
|
|
2428
2402
|
/** Each poller finishes the read it is in and returns; resolves once all have. */
|
|
2429
2403
|
async function stopPollers() {
|
|
2430
2404
|
pollersWanted = false;
|
|
2431
|
-
pollersNotRunning = "the pollers were stopped to hand the gateway to another build";
|
|
2432
2405
|
await Promise.all(pollerRuns);
|
|
2433
2406
|
}
|
|
2434
2407
|
// ── MCP server ────────────────────────────────────────────────────────────────
|
|
@@ -2462,23 +2435,14 @@ function drainInboxFor(tag) {
|
|
|
2462
2435
|
// nobody must not be swallowed by the part before it.
|
|
2463
2436
|
async function sendChunked(message, priority, clientId) {
|
|
2464
2437
|
const outcomes = [];
|
|
2465
|
-
|
|
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);
|
|
2466
2440
|
const buttons = decisionButtons(message);
|
|
2467
2441
|
for (const [i, chunk] of parts.entries()) {
|
|
2468
2442
|
outcomes.push(await sendNotification(withLead(`[${clientId}]`, chunk), priority, clientId, i === parts.length - 1 ? buttons : undefined));
|
|
2469
2443
|
}
|
|
2470
2444
|
return outcomes;
|
|
2471
2445
|
}
|
|
2472
|
-
/** 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. */
|
|
2473
|
-
function inboxText(messages) {
|
|
2474
|
-
const line = (m) => `[${m.ts}] ${m.text}`;
|
|
2475
|
-
const his = messages.filter((m) => m.origin !== "drop");
|
|
2476
|
-
const alerts = messages.filter((m) => m.origin === "drop");
|
|
2477
|
-
return [
|
|
2478
|
-
...(his.length > 0 ? [`⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n${his.map(line).join("\n")}`] : []),
|
|
2479
|
-
...(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")}`] : []),
|
|
2480
|
-
].join("\n\n");
|
|
2481
|
-
}
|
|
2482
2446
|
// A tool result that also carries any unsolicited message the user sent while
|
|
2483
2447
|
// the caller was busy, so a notify round-trip is never a deaf one.
|
|
2484
2448
|
function withInbox(text, isError, sessionTag, clientId) {
|
|
@@ -2486,8 +2450,9 @@ function withInbox(text, isError, sessionTag, clientId) {
|
|
|
2486
2450
|
if (messages.length === 0)
|
|
2487
2451
|
return { content: [{ type: "text", text }], isError };
|
|
2488
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");
|
|
2489
2454
|
return {
|
|
2490
|
-
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}` }],
|
|
2491
2456
|
isError,
|
|
2492
2457
|
};
|
|
2493
2458
|
}
|
|
@@ -2496,7 +2461,8 @@ function appendInbox(baseText, sessionTag, clientId) {
|
|
|
2496
2461
|
if (messages.length === 0)
|
|
2497
2462
|
return baseText;
|
|
2498
2463
|
log("·", "poll", `${messages.length} message(s) drained via heartbeat`, clientId);
|
|
2499
|
-
|
|
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}`;
|
|
2500
2466
|
}
|
|
2501
2467
|
const MCP_INSTRUCTIONS = `
|
|
2502
2468
|
This server is how a board decision, or an answer to something the user
|
|
@@ -2673,8 +2639,8 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2673
2639
|
"is split for you into numbered '(1/N) ...' parts, each 500 characters or less, and " +
|
|
2674
2640
|
"delivered in order. Never truncate to fit a part.", {
|
|
2675
2641
|
message: z.string().max(5000).describe("Notification message — up to 5000 chars; the server splits it into numbered parts"),
|
|
2676
|
-
priority: z.enum(["low", "normal", "high"]).default("normal")
|
|
2677
|
-
.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`),
|
|
2678
2644
|
answers: z.string().max(2000).optional()
|
|
2679
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."),
|
|
2680
2646
|
}, async ({ message, priority, answers }) => {
|
|
@@ -2743,7 +2709,7 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2743
2709
|
// whether a token is present — a revoked token satisfied the config check
|
|
2744
2710
|
// for four months and every question rode it into the void.
|
|
2745
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.
|
|
2746
|
-
const askCandidates =
|
|
2712
|
+
const askCandidates = askableChannels(cfg);
|
|
2747
2713
|
const askSkipNotes = [];
|
|
2748
2714
|
const askFormatNotes = [];
|
|
2749
2715
|
// Measured now, per candidate: what cannot carry is absent from `canCarry`.
|
|
@@ -2908,7 +2874,7 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2908
2874
|
return {
|
|
2909
2875
|
content: [{
|
|
2910
2876
|
type: "text",
|
|
2911
|
-
text:
|
|
2877
|
+
text: `⚠️ USER SENT YOU A MESSAGE — STOP AND RESPOND BEFORE CONTINUING:\n` + messages.map(m => `[${m.ts}] ${m.text}`).join("\n"),
|
|
2912
2878
|
}],
|
|
2913
2879
|
};
|
|
2914
2880
|
});
|
|
@@ -2928,7 +2894,8 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2928
2894
|
// drain and return them without parking a waiter.
|
|
2929
2895
|
const queued = drainInboxFor(sessionTag);
|
|
2930
2896
|
if (queued.length > 0) {
|
|
2931
|
-
|
|
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}` }] };
|
|
2932
2899
|
}
|
|
2933
2900
|
const token = randomUUID();
|
|
2934
2901
|
const entries = await new Promise((resolve) => {
|
|
@@ -2942,7 +2909,8 @@ export function createMcpServer(clientId, sessionTag) {
|
|
|
2942
2909
|
return { content: [{ type: "text", text: "inbox:empty" }] };
|
|
2943
2910
|
}
|
|
2944
2911
|
log("·", "wait_for_inbox", `${entries.length} message(s) delivered`, clientId);
|
|
2945
|
-
|
|
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}` }] };
|
|
2946
2914
|
});
|
|
2947
2915
|
server.tool("get_idle_seconds", "Returns how long it has been since the user's last keyboard/mouse input. " +
|
|
2948
2916
|
"Call this periodically during long work as a cheap heartbeat — the server " +
|
|
@@ -3155,7 +3123,7 @@ export function yieldGateway() {
|
|
|
3155
3123
|
}
|
|
3156
3124
|
/**
|
|
3157
3125
|
* Once the extension installs a newer build, this process is superseded and the gateway passes to the installed build:
|
|
3158
|
-
* 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.
|
|
3159
3127
|
*/
|
|
3160
3128
|
function tryOwnGateway(polling, host) {
|
|
3161
3129
|
if (ownershipAttempting)
|
|
@@ -3208,24 +3176,14 @@ function tryOwnGateway(polling, host) {
|
|
|
3208
3176
|
if (polling)
|
|
3209
3177
|
startOwnedWork();
|
|
3210
3178
|
})().catch((err) => {
|
|
3211
|
-
// OWNER:
|
|
3212
|
-
if (door !== undefined) {
|
|
3213
|
-
const stack = err.stack ?? String(err);
|
|
3214
|
-
if (pollersWanted)
|
|
3215
|
-
log("·", "listener", `the gateway's start failed AFTER its pollers started, which still read: ${stack}`);
|
|
3216
|
-
else {
|
|
3217
|
-
pollersNotRunning = `the pollers did not start: ${stack}`;
|
|
3218
|
-
log("·", "listener", pollersNotRunning);
|
|
3219
|
-
}
|
|
3220
|
-
return;
|
|
3221
|
-
}
|
|
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.
|
|
3222
3180
|
const cause = err.code ?? err.message;
|
|
3223
3181
|
if (cause !== lastBindRefusal)
|
|
3224
3182
|
log("·", "listener", `gateway port not bound (${cause}); staying dormant and retrying every ${OWNERSHIP_RETRY_MS / 1000}s`);
|
|
3225
3183
|
lastBindRefusal = cause;
|
|
3226
3184
|
}).finally(() => { ownershipAttempting = false; });
|
|
3227
3185
|
}
|
|
3228
|
-
/** 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. */
|
|
3229
3187
|
async function stepAside(polling, host) {
|
|
3230
3188
|
const gateway = AgentGateway.instance();
|
|
3231
3189
|
if (polling && !gateway.quiet())
|
|
@@ -3279,7 +3237,7 @@ export function startNotifyServer(host) {
|
|
|
3279
3237
|
tryOwnGateway(polling, host);
|
|
3280
3238
|
// a process holding the door is asked again when the installed build's manifest is written, the one thing that
|
|
3281
3239
|
// can supersede it; the beat re-asks only a dormant process, whose owner may be a BN on another machine that no local
|
|
3282
|
-
// 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.
|
|
3283
3241
|
const ownershipTimer = setInterval(() => {
|
|
3284
3242
|
if (door === undefined || supersededSaid || yielding)
|
|
3285
3243
|
tryOwnGateway(polling, host);
|