omni-notify-mcp 1.3.481 → 1.3.482

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.
@@ -123,6 +123,17 @@ export const SLACK_DM = "slack:dm:";
123
123
  function carriageOf(platform, key) {
124
124
  return key.startsWith(SLACK_DM) ? ONE : CARRIAGE[platform];
125
125
  }
126
+ /** The turns a conversation hands the one replacing it on another provider: his messages and its answers, newest last, each cut to fit. */
127
+ const CARRIED_TURNS = 8;
128
+ const CARRIED_CHARS = 1500;
129
+ function carriedOver(from, to) {
130
+ const said = readEvents(from.id).filter((e) => e.role === "user" || e.kind === "answer").slice(-CARRIED_TURNS);
131
+ if (said.length === 0)
132
+ return undefined;
133
+ // A stored message of his ends with his own words (the brief and context ride before them), so the end of each turn is what is kept.
134
+ const lines = said.map((e) => `${e.role === "user" ? "He said" : `${from.provider} answered`}: ${e.text.length > CARRIED_CHARS ? `(cut)… ${e.text.slice(-CARRIED_CHARS)}` : e.text}`);
135
+ return `(BN: he switched this chat from ${from.provider} to ${to}. This conversation goes on from the one ${from.provider} held — its latest turns, read them as this chat's history:\n${lines.join("\n\n")})`;
136
+ }
126
137
  const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
127
138
  const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
128
139
  export class AgentGateway {
@@ -261,17 +272,35 @@ export class AgentGateway {
261
272
  this.end(c.id);
262
273
  return reply(carriage.stopped(stopped, carriage.allOf(key).filter((c) => !stopped.includes(c)).length));
263
274
  }
264
- if (act.kind === "new")
265
- return reply(await carriage.renew(key, platform, (id) => this.end(id), act.provider));
275
+ if (act.kind === "new") {
276
+ try {
277
+ return reply(await carriage.renew(key, platform, (id) => this.end(id), act.provider));
278
+ }
279
+ catch (err) {
280
+ if (!(err instanceof GatewayError))
281
+ throw err;
282
+ // OWNER: the message is the trigger root — a fresh conversation the gateway refused (its CLI does not answer, no subscription has room) is answered to the chat with the reason, never silence.
283
+ return reply(`❌ NOT STARTED — ${err.message}`);
284
+ }
285
+ }
266
286
  if (act.text === "")
267
287
  return reply("Send `! <your message>` to talk to the agent.");
268
288
  const replaced = open !== undefined && act.provider !== undefined && open.provider !== act.provider;
269
- if (replaced) {
289
+ // #4671 — a provider switch keeps the thread: the conversation it replaces hands its latest turns to the new one, so nothing said is lost.
290
+ const carried = replaced ? carriedOver(open, act.provider) : undefined;
291
+ // The conversations it replaces end only once the new one is made: a provider that refuses leaves the chat on the one it had, every turn kept.
292
+ const retire = () => {
293
+ if (!replaced)
294
+ return;
270
295
  for (const c of carriage.allOf(key)) {
271
296
  this.end(c.id);
272
297
  archiveConversation(c.id);
273
298
  }
274
- }
299
+ };
300
+ // The one chat's brief rides the first turn of a conversation; the replacing one has had none, so it is given it with the turns carried over.
301
+ // NULL-OK: field carried is OPTIONAL and therefore it is ok to check for NULL
302
+ const said = carried === undefined ? act.text : [...(carriage === ONE ? [chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram")] : []), carried, act.text].join("\n\n");
303
+ const switched = (id) => (replaced ? [this.told(id, 1, `🔀 Switched from ${open.provider} to ${act.provider} — the conversation goes on there, its last turns carried over.`)] : []);
275
304
  const target = replaced ? undefined : carriage.routeOf(key, act.text);
276
305
  const forkOf = replaced ? undefined : carriage.forkOf(key);
277
306
  // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
@@ -293,8 +322,9 @@ export class AgentGateway {
293
322
  // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
294
323
  const provider = forkOf !== undefined ? open.provider : act.kind === "say" ? act.provider : undefined;
295
324
  const [creation] = await Promise.allSettled([createdIn(project, provider, () => key, (on) => {
296
- const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: act.text, receivedMs: monotonicMs() - arrived });
297
- const answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false, forkOf !== undefined));
325
+ retire();
326
+ const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: said, receivedMs: monotonicMs() - arrived });
327
+ const answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false, forkOf !== undefined), switched(created.id));
298
328
  // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
299
329
  turn.answered = forkOf === undefined ? answered : answered.finally(() => this.end(created.id));
300
330
  turn.id = created.id;
@@ -302,8 +332,12 @@ export class AgentGateway {
302
332
  })]);
303
333
  if (creation.status === "rejected") {
304
334
  // NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
305
- if (turn.id === undefined)
306
- throw creation.reason;
335
+ if (turn.id === undefined) {
336
+ if (!(creation.reason instanceof GatewayError))
337
+ throw creation.reason;
338
+ // OWNER: the message is the trigger root — a conversation the gateway refused to start (the named CLI does not answer, no subscription has room, the other owner holds it) is answered to the chat with the reason, never thrown past the poll loop into silence.
339
+ return reply(replaced ? `❌ NOT SWITCHED to ${act.provider} — ${creation.reason.message}\nThis chat stays on ${open.provider}, everything said in it kept, until ${act.provider} answers or another provider is chosen. This message was not sent: send it again then.` : `❌ NOT STARTED — ${creation.reason.message}\nThis message was not sent: send it again once a provider answers.`);
340
+ }
307
341
  const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
308
342
  process.stderr.write(`[agent-gateway] conversation ${turn.id.slice(0, 8)}: the unread-room notice could not be written (${reason}); the turn runs on and its answer is delivered\n`);
309
343
  this.deliver(this.told(turn.id, 1, `⚠️ No CLI was named and DeepAgent's subscription room could not be read; that notice could not be written to this conversation: ${reason}`));
@@ -7,13 +7,16 @@
7
7
  import { createHash } from "crypto";
8
8
  import { existsSync, mkdirSync, readFileSync } from "fs";
9
9
  import { dirname, join } from "path";
10
- import { CONFIG_DIR, deliveryReport, isDndActive } from "../notify.js";
10
+ import { CHAT_PROVIDERS, CONFIG_DIR, deliveryReport, isDndActive } from "../notify.js";
11
11
  import { MESSENGER_SETUPS } from "../messaging/setup.js";
12
12
  import { extensionModule } from "./extensionModule.js";
13
13
  import { GatewayError, conversationEnabled, setConversationEnabled, writeRecordFile } from "./conversationOwner.js";
14
14
  import { TELEGRAM_PARSE_MODES } from "../messaging/telegramFormat.js";
15
15
  const channelReading = () => extensionModule("channelReading.cjs");
16
16
  const CONFIG_PATH = join(CONFIG_DIR, "config.json");
17
+ /** #4617 — the agent CLI a one chat runs on: auto is the subscription-first pick; /provider in the chat writes the same field. */
18
+ const CHAT_PROVIDER_CHOICES = ["auto", ...CHAT_PROVIDERS];
19
+ const chatProviderRow = (chat) => ({ path: [chat, "provider"], label: "Agent provider", kind: "choice", choices: CHAT_PROVIDER_CHOICES, fallback: "auto", hint: "The agent CLI this chat's conversation runs on. auto (default) takes the subscription with room first. Changing it switches the open conversation on its next message, its latest turns carried over; /provider in the chat reads and changes it too." });
17
20
  // Every config field the notify server reads, one editable row each. A field the server no longer reads is not listed: a control for it would change nothing.
18
21
  export const SETTINGS = [
19
22
  { title: "🔕 Master", rows: [
@@ -29,6 +32,7 @@ export const SETTINGS = [
29
32
  { path: ["telegram", "enabled"], label: "Enabled", kind: "toggle" },
30
33
  { 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." },
31
34
  { 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." },
35
+ chatProviderRow("telegram"),
32
36
  ] },
33
37
  { 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: [
34
38
  { path: ["slack", "enabled"], label: "Enabled", kind: "toggle" },
@@ -38,6 +42,7 @@ export const SETTINGS = [
38
42
  { path: ["slack", "configRefreshToken"], label: "Configuration refresh token", kind: "secret", hint: "Generated with the configuration token. BN renews the 12-hour token with it, so setup keeps working." },
39
43
  { 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." },
40
44
  { 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." },
45
+ chatProviderRow("slack"),
41
46
  ] },
42
47
  { guide: { summary: "AWS End User Messaging credentials", steps: ["AWS Console, IAM: create a user allowed `sms-voice:SendTextMessage`; copy its Access Key ID and Secret.", "AWS End User Messaging, Phone numbers, request a number; it becomes your From number.", "Paste the key, secret, region and From number below, then add recipients under Send to.", "Switch Enabled to On."], need: [["sms.accessKeyId"], ["sms.secretAccessKey"], ["sms.region"], ["sms.originationNumber"], ["sms.to"]] }, title: "📱 SMS (AWS)", rows: [
43
48
  { path: ["sms", "enabled"], label: "Enabled", kind: "toggle" },
@@ -1,10 +1,11 @@
1
1
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
2
2
  import { dirname } from "path";
3
- import { TelegramRefused } from "./messenger.js";
3
+ import { TelegramRefused, TelegramUnreachable } from "./messenger.js";
4
4
  /**
5
5
  * #4586 — one Telegram topic per story inside the one bound chat. BN creates a story's topic (createForumTopic, which Bot API 9.3+ allows
6
6
  * in a private chat with topic mode on), sends that story's messages into it (message_thread_id), reads a message he writes inside a topic
7
- * as that story's, and closes the topic when the story ships. A chat that refuses topics keeps the plain chat: nothing here ever blocks a send.
7
+ * as that story's, and closes the topic when the story ships. A chat that refuses topics keeps the plain chat: nothing here ever blocks a send,
8
+ * and every refusal or store write that fails is said on BN's console trail (#4660), never silently.
8
9
  */
9
10
  /** The story a message is about: its board decision link names it, else its headline does ("#4123 ..." / "Story #4123"); undefined for a plain message. */
10
11
  export function storyOfMessage(text) {
@@ -22,86 +23,109 @@ export function shippedStory(text) {
22
23
  }
23
24
  export class StoryTopics {
24
25
  file;
25
- data = {};
26
+ trail;
27
+ data;
26
28
  /** Chats Telegram refused a topic in, until when: the plain chat is the whole path there meanwhile. */
27
29
  refused = new Map();
28
- constructor(file) {
30
+ /** Topics this process forgot (Telegram no longer has them): a merge never brings them back from this process's own older copy. */
31
+ forgotten = new Map();
32
+ constructor(file, trail) {
29
33
  this.file = file;
30
- if (existsSync(file)) {
31
- try {
32
- this.data = JSON.parse(readFileSync(file, "utf8"));
33
- }
34
- catch {
35
- this.data = {};
36
- }
34
+ this.trail = trail;
35
+ this.data = this.onDisk();
36
+ }
37
+ /** The store as another process (a build handing over) may have left it: none yet is empty, an unreadable one is said on the trail and read as empty. */
38
+ onDisk() {
39
+ if (!existsSync(this.file))
40
+ return {};
41
+ try {
42
+ return JSON.parse(readFileSync(this.file, "utf8"));
43
+ }
44
+ catch (err) {
45
+ // OWNER: the topic store is a routing aid, never a send's gate — an unreadable store is said on the trail and read as empty, so the plain chat or a fresh topic carries the message.
46
+ this.trail(`topic store ${this.file} unreadable, read as empty: ${err instanceof Error ? err.message : String(err)}`);
47
+ return {};
37
48
  }
38
49
  }
39
- save() {
40
- // Another process (a build handing over) may have written topics since this one loaded: its entries are kept.
50
+ /** One change, written read-merge-write so another process's entries are never dropped (#4733); a write that fails keeps the change in memory and is said on the trail (#4744). */
51
+ persist(change) {
52
+ const disk = this.onDisk();
53
+ const merged = { ...disk, ...this.data };
54
+ // A topic another process closed stays closed here too; one this process forgot is never written back from its old copy.
55
+ for (const [key, t] of Object.entries(disk))
56
+ if (t.closed === true)
57
+ merged[key] = t;
58
+ for (const [key, thread] of this.forgotten)
59
+ if (merged[key]?.thread === thread)
60
+ delete merged[key];
61
+ change(merged);
62
+ this.data = merged;
41
63
  try {
42
- this.data = { ...JSON.parse(readFileSync(this.file, "utf8")), ...this.data };
64
+ mkdirSync(dirname(this.file), { recursive: true });
65
+ const staged = `${this.file}.${process.pid}.tmp`;
66
+ writeFileSync(staged, JSON.stringify(merged, null, 2));
67
+ renameSync(staged, this.file);
68
+ }
69
+ catch (err) {
70
+ // OWNER: a topic note that cannot be written must not cost the message its send — the change holds in memory for this process and the failure is said on the trail.
71
+ this.trail(`topic store ${this.file} not written, the change holds only in this process: ${err instanceof Error ? err.message : String(err)}`);
43
72
  }
44
- catch { /* no store yet */ }
45
- mkdirSync(dirname(this.file), { recursive: true });
46
- const staged = `${this.file}.tmp`;
47
- writeFileSync(staged, JSON.stringify(this.data, null, 2));
48
- renameSync(staged, this.file);
49
73
  }
50
74
  /** The open topic of a story in a chat, if BN made one. */
51
75
  threadOf(chat, story) {
52
76
  const t = this.data[`${chat}:${story}`];
53
77
  return t === undefined || t.closed === true ? undefined : t.thread;
54
78
  }
55
- /** The story a topic (thread) of a chat belongs to. */
79
+ /** The story a topic (thread) of a chat belongs to — a closed one's too, so his late message in it is still read as that story's. */
56
80
  storyOf(chat, thread) {
57
81
  for (const [key, t] of Object.entries(this.data))
58
82
  if (key.startsWith(`${chat}:`) && t.thread === thread)
59
83
  return Number(key.slice(chat.length + 1));
60
84
  return undefined;
61
85
  }
62
- /** The story's topic, created on first use; undefined when this chat cannot hold topics (the caller then sends to the plain chat). */
86
+ /** The story's topic, created on first use; undefined when this chat cannot hold topics or the story's topic is closed (the caller then sends to the plain chat). */
63
87
  async ensure(api, chat, story, name) {
64
88
  const known = this.threadOf(chat, story);
65
89
  if (known !== undefined)
66
90
  return known;
67
- // A closed story's topic is still its topic: a later message about it goes there, never into a second topic.
68
- const closed = this.data[`${chat}:${story}`];
69
- if (closed !== undefined) {
70
- // Reopened so the message is never sent into a closed topic; a ship notice closes it again after.
71
- try {
72
- await api.call("reopenForumTopic", { chat_id: chat, message_thread_id: closed.thread });
73
- closed.closed = false;
74
- this.save();
75
- }
76
- catch { /* a topic that cannot be reopened is still tried: the sender falls back to the plain chat on a refusal */ }
77
- return closed.thread;
78
- }
91
+ // A shipped story's topic stays closed: a later message naming it goes to the plain chat, never reopening it or making a second one (#4725).
92
+ if (this.data[`${chat}:${story}`] !== undefined)
93
+ return undefined;
79
94
  if ((this.refused.get(chat) ?? 0) > Date.now())
80
95
  return undefined;
96
+ let made;
81
97
  try {
82
- const made = await api.call("createForumTopic", { chat_id: chat, name: name.slice(0, 128) });
83
- const thread = Number(made?.message_thread_id);
84
- if (!Number.isInteger(thread)) {
85
- this.refused.set(chat, Date.now() + 600_000);
86
- return undefined;
87
- }
88
- this.data[`${chat}:${story}`] = { thread };
89
- this.save();
90
- return thread;
98
+ made = await api.call("createForumTopic", { chat_id: chat, name: name.slice(0, 128) });
91
99
  }
92
100
  catch (err) {
93
- // Only Telegram's own refusal (topics not on for this chat) pauses topics for a while; a network failure or a 429 is no verdict on the chat.
94
- if (err instanceof TelegramRefused && err.status !== 429)
101
+ if (!(err instanceof TelegramRefused) && !(err instanceof TelegramUnreachable))
102
+ throw err;
103
+ // OWNER: ITER/LOOP — a topic Telegram will not make costs this message only its topic: the plain chat carries it and why is said on the trail (#4660). Only Telegram's own refusal pauses topics; a network failure or a 429 is no verdict on the chat.
104
+ const pauses = err instanceof TelegramRefused && err.status !== 429;
105
+ if (pauses)
95
106
  this.refused.set(chat, Date.now() + 600_000);
107
+ this.trail(`topic for #${story} REFUSED in chat ${chat}: ${err.message}; the plain chat carries it${pauses ? ", topics paused 10 min" : ""}`);
108
+ return undefined;
109
+ }
110
+ const thread = Number(made?.message_thread_id);
111
+ if (!Number.isInteger(thread)) {
112
+ this.refused.set(chat, Date.now() + 600_000);
113
+ this.trail(`topic for #${story} NOT made in chat ${chat}: createForumTopic answered no message_thread_id (${JSON.stringify(made)}); the plain chat carries it, topics paused 10 min`);
96
114
  return undefined;
97
115
  }
116
+ this.forgotten.delete(`${chat}:${story}`);
117
+ this.persist((store) => { store[`${chat}:${story}`] = { thread }; });
118
+ this.trail(`topic ${thread} made for #${story} in chat ${chat}`);
119
+ return thread;
98
120
  }
99
121
  /** A topic Telegram no longer has (he deleted it): forgotten, so the next message makes a fresh one and nothing keeps failing. */
100
122
  forget(chat, story) {
101
- if (!delete this.data[`${chat}:${story}`])
123
+ const key = `${chat}:${story}`;
124
+ if (this.data[key] === undefined)
102
125
  return;
103
- mkdirSync(dirname(this.file), { recursive: true });
104
- writeFileSync(this.file, JSON.stringify(this.data, null, 2));
126
+ this.forgotten.set(key, this.data[key].thread);
127
+ this.persist((store) => { delete store[key]; });
128
+ this.trail(`topic of #${story} in chat ${chat} is gone from Telegram: forgotten, the next message makes a fresh one`);
105
129
  }
106
130
  /** Closes a story's topic once it ships; the mapping stays so his late message in it is still read as that story's. */
107
131
  async close(api, chat, story) {
@@ -111,16 +135,15 @@ export class StoryTopics {
111
135
  try {
112
136
  await api.call("closeForumTopic", { chat_id: chat, message_thread_id: t.thread });
113
137
  }
114
- catch {
138
+ catch (err) {
139
+ if (!(err instanceof TelegramRefused) && !(err instanceof TelegramUnreachable))
140
+ throw err;
141
+ // OWNER: the ship notice already went out; a topic Telegram will not close stays open and why is said on the trail.
142
+ this.trail(`topic ${t.thread} of #${story} NOT closed in chat ${chat}: ${err.message}`);
115
143
  return false;
116
144
  }
117
- t.closed = true;
118
- try {
119
- this.save();
120
- }
121
- catch {
122
- // The topic is closed in Telegram, and so it stays in memory; only the note of it could not be written (the file is held).
123
- }
145
+ this.persist((store) => { store[`${chat}:${story}`] = { thread: t.thread, closed: true }; });
146
+ this.trail(`topic ${t.thread} of #${story} closed in chat ${chat}: its story shipped`);
124
147
  return true;
125
148
  }
126
149
  }
package/dist/notify.js CHANGED
@@ -495,7 +495,8 @@ async function sendNotification(message, priority, client, buttons, topic) {
495
495
  ({ response: r, unformatted: plain } = await postTelegramMessage(tgApi(cfg.telegram.token, "sendMessage"), body, mode));
496
496
  }
497
497
  else if (r.ok && thread !== undefined && topic !== undefined && topic.ships) {
498
- void storyTopics.close(topicCalls(cfg.telegram.token), chatId, topic.story);
498
+ // OWNER: ITER/LOOP — the ship notice is delivered; an undocumented answer to the close is logged whole, the topic stays open.
499
+ void storyTopics.close(topicCalls(cfg.telegram.token), chatId, topic.story).catch((err) => log("·", "telegram:topic", `topic of #${topic.story} NOT closed: ${err instanceof Error ? err.message : String(err)}`));
499
500
  }
500
501
  if (r.ok) {
501
502
  sent++;
@@ -1185,29 +1186,67 @@ const TELEGRAM_WELCOME = "🔗 This chat is your BN agent now.\n\nWrite anything
1185
1186
  function boundTelegramChat(chatIds, chat, sender) {
1186
1187
  return chatIds.includes(chat) && sender === chat;
1187
1188
  }
1188
- /** Binds the bot to this private chat, written straight into config.json as a staged file renamed over it, and read back. */
1189
- function bindTelegramChat(chat) {
1189
+ /** One section of config.json changed in place, written as a staged file renamed over it; the caller reads its change back. */
1190
+ function writeConfigSection(name, change) {
1190
1191
  const raw = existsSync(CONFIG_PATH) ? JSON.parse(readFileSync(CONFIG_PATH, "utf-8")) : {};
1191
- raw.telegram = { ...(raw.telegram ?? {}), chatIds: [chat] };
1192
+ const section = { ...(raw[name] ?? {}) };
1193
+ change(section);
1194
+ raw[name] = section;
1192
1195
  const staged = `${CONFIG_PATH}.${process.pid}.tmp`;
1193
1196
  writeFileSync(staged, JSON.stringify(raw, null, 2));
1194
1197
  renameSync(staged, CONFIG_PATH);
1198
+ }
1199
+ /** Binds the bot to this private chat, written straight into config.json, and read back. */
1200
+ function bindTelegramChat(chat) {
1201
+ writeConfigSection("telegram", (section) => { section.chatIds = [chat]; });
1195
1202
  if (!(loadConfig().telegram?.chatIds ?? []).includes(chat))
1196
1203
  throw new Error(`the binding to chat ${chat} did not hold in ${CONFIG_PATH}`);
1197
1204
  log("·", "telegram", `this bot is bound to chat ${chat}: every message from it reaches the BN conversation, every other sender is refused`);
1198
1205
  }
1199
- /** Telegram runs on the CLI `telegram.provider` in config.json names, else on the shared subscription-first pick (Claude while its subscription has room, then the next with room; a refusal says why). */
1200
- const TELEGRAM_PROVIDERS = ["claude", "codex", "copilot", "opencode"];
1201
- function telegramProvider() {
1202
- const named = loadConfig().telegram?.provider;
1203
- return typeof named === "string" && TELEGRAM_PROVIDERS.includes(named) ? named : undefined;
1204
- }
1205
- function setTelegramProvider(name) {
1206
+ /** A one chat runs on the CLI `<platform>.provider` in config.json names, else on the shared subscription-first pick (Claude while its subscription has room, then the next with room; a refusal says why). */
1207
+ export const CHAT_PROVIDERS = ["claude", "codex", "copilot", "opencode"];
1208
+ function chatProvider(platform) {
1209
+ const named = loadConfig()[platform]?.provider;
1210
+ return typeof named === "string" && CHAT_PROVIDERS.includes(named) ? named : undefined;
1211
+ }
1212
+ /** The `/provider` command of a one chat (#4617, #4671): bare, it reads the provider and the choices; with a name it switches the chat to it from its next message, the conversation's latest turns carried over; `auto` hands it back to the subscription-first pick. */
1213
+ const PROVIDER_COMMAND = /^\/?provider(?:@\w+)?(?:\s+(\S+))?$/i;
1214
+ function switchChatProvider(platform, name) {
1215
+ const now = chatProvider(platform) ?? "auto (the subscription with room)";
1216
+ const choices = `Choices: ${[...CHAT_PROVIDERS, "auto"].map((p) => `/provider ${p}`).join(" · ")}`;
1217
+ // NULL-OK: field name is OPTIONAL and therefore it is ok to check for NULL
1206
1218
  if (name === undefined)
1207
- return `🤖 Provider for new conversations: ${telegramProvider() ?? "the subscription with room"} (set telegram.provider in config.json to change it)`;
1208
- return `❌ Telegram runs on ${telegramProvider() ?? "the subscription with room"}; /provider cannot change it - set telegram.provider in config.json.`;
1219
+ return `🤖 This chat runs on ${now}.\n${choices}\nTo change the subscription or key a provider uses, just ask: the agent switches it with DeepAgent.`;
1220
+ const wanted = name.toLowerCase();
1221
+ if (wanted !== "auto" && !CHAT_PROVIDERS.includes(wanted))
1222
+ return `❌ No provider called "${name}". ${choices}`;
1223
+ writeConfigSection(platform, (section) => {
1224
+ if (wanted === "auto")
1225
+ delete section.provider;
1226
+ else
1227
+ section.provider = wanted;
1228
+ });
1229
+ const held = chatProvider(platform);
1230
+ if ((wanted === "auto" ? undefined : wanted) !== held)
1231
+ throw new Error(`${platform}.provider=${wanted} did not hold in ${CONFIG_PATH} (it reads ${held ?? "auto"})`);
1232
+ log("·", platform, `provider for this chat set to ${wanted}`);
1233
+ return wanted === "auto"
1234
+ ? "✅ Auto: a new conversation takes the subscription with room first; the one open now stays on its provider until /new."
1235
+ : `✅ ${wanted} from your next message — this conversation goes on there with its latest turns carried over.`;
1236
+ }
1237
+ /** His /provider answered in the chat it came from: the switch, or why it did not happen — never silence. */
1238
+ function providerAnswer(platform, name) {
1239
+ try {
1240
+ return switchChatProvider(platform, name);
1241
+ }
1242
+ catch (err) {
1243
+ // OWNER: the message is the trigger root — a provider choice that could not be written is answered in his chat with the reason and logged; the chat keeps its provider.
1244
+ const why = err instanceof Error ? err.message : String(err);
1245
+ log("·", platform, `provider NOT switched: ${why}`);
1246
+ return `❌ NOT SWITCHED — ${why}. This chat keeps ${chatProvider(platform) ?? "auto"}.`;
1247
+ }
1209
1248
  }
1210
- const storyTopics = new StoryTopics(join(CONFIG_DIR, "story-topics.json"));
1249
+ const storyTopics = new StoryTopics(join(CONFIG_DIR, "story-topics.json"), (line) => log("·", "telegram:topic", line));
1211
1250
  const topicCalls = (token) => ({ call: (method, body) => telegramCall(tgApi(token, method), method, body) });
1212
1251
  function topicOfMessage(text) {
1213
1252
  const story = storyOfMessage(text);
@@ -1241,14 +1280,15 @@ function openAsksContext() {
1241
1280
  /** One said thing of the bound chat goes to its one conversation, its turn streamed back into the chat. */
1242
1281
  function toTelegramConversation(token, chat, act, thread, replyTo) {
1243
1282
  // #4586 — a topic is its own conversation (the story's); the plain chat keeps its one.
1244
- const routed = act.kind === "stop" ? act : { ...act, provider: telegramProvider() };
1245
- toOneChat(thread === undefined ? `telegram:${chat}` : `telegram:${chat}:${thread}`, "telegram", routed, telegramMessenger(token, chat, thread, replyTo));
1283
+ toOneChat(thread === undefined ? `telegram:${chat}` : `telegram:${chat}:${thread}`, "telegram", act, telegramMessenger(token, chat, thread, replyTo));
1246
1284
  }
1247
- /** One said thing of one of Meni's one chats — Telegram, or his Slack direct message — goes to its one conversation, its turn streamed back into that chat. */
1285
+ /** One said thing of one of Meni's one chats — Telegram, or his Slack direct message — goes to its one conversation on the provider that chat runs on, its turn streamed back into that chat. */
1248
1286
  function toOneChat(key, platform, act, messenger) {
1249
1287
  const trail = `agent:${platform}`;
1288
+ // #4671 — every act but a stop carries the chat's provider, so a message, a tapped choice and /new all start on the one /provider chose.
1289
+ const routed = act.kind === "stop" ? act : { ...act, provider: chatProvider(platform) };
1250
1290
  // OWNER: ITER/LOOP — the agent's answer outlives this message; the conversation reports its own failure into the chat, and a send that fails is logged here.
1251
- void AgentGateway.instance().handle(key, platform, act, streamedChat(messenger, (line) => log("→", trail, line))).catch((err) => {
1291
+ void AgentGateway.instance().handle(key, platform, routed, streamedChat(messenger, (line) => log("→", trail, line))).catch((err) => {
1252
1292
  log("→", trail, `NOT DELIVERED to ${key}: ${err instanceof Error ? err.message : String(err)}`);
1253
1293
  });
1254
1294
  }
@@ -1307,9 +1347,9 @@ async function takeTelegramUpdate(token, update) {
1307
1347
  await messenger.send(TELEGRAM_WELCOME);
1308
1348
  return;
1309
1349
  }
1310
- const providerCmd = text.trim().match(/^\/provider(?:@\w+)?(?:\s+(\S+))?$/i);
1350
+ const providerCmd = text.trim().match(PROVIDER_COMMAND);
1311
1351
  if (providerCmd !== null) {
1312
- await messenger.send(setTelegramProvider(providerCmd[1]));
1352
+ await messenger.send(providerAnswer("telegram", providerCmd[1]));
1313
1353
  return;
1314
1354
  }
1315
1355
  // #4494 — a digit he replied to a board decision message with is that decision's pick, and #4123 other words its answer, whatever else waits on him.
@@ -2370,6 +2410,12 @@ function takeSlackDmMessage(dm, owner, m, threadTs) {
2370
2410
  // NULL-OK: field picked is OPTIONAL and therefore it is ok to check for NULL
2371
2411
  if (picked !== undefined)
2372
2412
  return toOneChat(key, "slack", { kind: "say", text: chatTurnText(key, picked, [`He picked this choice on your last question: «${picked}»`, ...openAsksContext()]) }, view);
2413
+ const providerCmd = text.trim().match(PROVIDER_COMMAND);
2414
+ if (providerCmd !== null) {
2415
+ // OWNER: ITER/LOOP — the answer to his /provider goes back into the chat it came from; a send Slack refuses is logged and the next message is read.
2416
+ void view.send(providerAnswer("slack", providerCmd[1])).catch((err) => log("→", "agent:slack", `the /provider answer was not delivered: ${err instanceof Error ? err.message : String(err)}`));
2417
+ return;
2418
+ }
2373
2419
  const act = AgentGateway.instance().classifyChat(text, true);
2374
2420
  toOneChat(key, "slack", act.kind === "say" ? { kind: "say", text: chatTurnText(key, act.text, openAsksContext()) } : act, view);
2375
2421
  }
@@ -3331,12 +3377,25 @@ export function createMcpServer(clientId, sessionTag) {
3331
3377
  const askPrefix = `❓ [${clientId}]`;
3332
3378
  const replyHint = "\n\nTap an answer, reply to this message, or just tell BN in your own words.";
3333
3379
  const reply_markup = options.length === 0 ? undefined : { inline_keyboard: options.map((label, i) => [{ text: label, callback_data: `q|${short}|${i}` }]) };
3380
+ // #4711 (folded into #4671) — a question about a story goes into that story's topic, as its notifications do.
3381
+ const askTopic = topicOfMessage(question);
3334
3382
  for (const chatId of cfg.telegram.chatIds) {
3383
+ // NULL-OK: field askTopic is OPTIONAL and therefore it is ok to check for NULL
3384
+ const thread = askTopic === undefined ? undefined : await storyThreadFor(cfg.telegram.token, chatId, askTopic);
3385
+ const body = { chat_id: chatId, text: `${askPrefix} ${question}${replyHint}`, reply_markup, ...(thread === undefined ? {} : { message_thread_id: thread }) };
3335
3386
  // A non-2xx Telegram response does NOT reject this fetch — only a
3336
3387
  // network-level failure does — so this used to silently do nothing
3337
3388
  // on e.g. a revoked token: no error, no log line, just a question
3338
3389
  // the user never saw and no clue why. Story #443: check r.ok too.
3339
- await postTelegramMessage(tgApi(cfg.telegram.token, "sendMessage"), { chat_id: chatId, text: `${askPrefix} ${question}${replyHint}`, reply_markup }, telegramParseMode(cfg))
3390
+ await postTelegramMessage(tgApi(cfg.telegram.token, "sendMessage"), body, telegramParseMode(cfg))
3391
+ .then(async (sent) => {
3392
+ // NULL-OK: field thread is OPTIONAL and therefore it is ok to check for NULL
3393
+ if (sent.response.ok || thread === undefined || sent.response.status !== 400 || !/thread not found|TOPIC_DELETED|TOPIC_CLOSED/i.test(await sent.response.clone().text()))
3394
+ return sent;
3395
+ // The topic is gone or closed: the question goes to the plain chat, never lost to a topic.
3396
+ const { message_thread_id: _gone, ...plain } = body;
3397
+ return postTelegramMessage(tgApi(cfg.telegram.token, "sendMessage"), plain, telegramParseMode(cfg));
3398
+ })
3340
3399
  .then(async ({ response: r, unformatted }) => {
3341
3400
  if (r.ok) {
3342
3401
  telegramSent = true;
@@ -1,11 +1,11 @@
1
1
  import { execFile, spawn, spawnSync } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import * as fs from "node:fs";
3
+ import fs from "node:fs";
4
4
  import { createRequire } from "node:module";
5
5
  import { Agent } from "node:http";
6
- import * as net from "node:net";
6
+ import net from "node:net";
7
7
  import { homedir, tmpdir } from "node:os";
8
- import * as path from "node:path";
8
+ import path from "node:path";
9
9
  import { createInterface } from "node:readline";
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
11
11
  import { Duplex } from "node:stream";
@@ -35,7 +35,7 @@ function run(file, args, timeoutMs, env = process.env) {
35
35
  /** Every process on the machine; throws {@link ProcessTableUnread} when the table cannot be read, never answers an empty one for it. */
36
36
  export async function processTable() {
37
37
  if (process.platform === "win32") {
38
- const script = "Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ p = $_.ProcessId; pp = $_.ParentProcessId; n = $_.Name; c = $_.CommandLine } } | ConvertTo-Json -Compress";
38
+ const script = "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ p = $_.ProcessId; pp = $_.ParentProcessId; n = $_.Name; c = $_.CommandLine } } | ConvertTo-Json -Compress";
39
39
  const { code, out } = await run("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], TABLE_READ_MS);
40
40
  const text = out.trim();
41
41
  if (code !== 0 || !text.startsWith("["))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.481",
3
+ "version": "1.3.482",
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",