omni-notify-mcp 1.3.477 → 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.
@@ -63,12 +63,14 @@ const boundOf = (key) => listConversations().find((c) => c.chat === key && c.she
63
63
  const sidesOf = (key) => listConversations().filter((c) => c.chat === key && c.forkOf !== undefined && c.state !== "closed" && c.shelf === undefined);
64
64
  /** A conversation in the middle of a turn, or holding a message stored for its next one. */
65
65
  const busy = (c) => turnInFlight(readEvents(c.id), c) !== undefined;
66
- /** The bound chat's main conversation while it is free (#4584); while it is busy undefined, so the message runs at once in a new conversation forked from it and never waits behind the reply under way. */
67
- const freeBound = (key) => {
66
+ /** The busy main conversation a message forks beside (#4584): an OpenCode one never forks, since each fork is a new OpenCode process left behind it, so its message queues on it instead. */
67
+ const forkedFrom = (key) => {
68
68
  const main = boundOf(key);
69
69
  // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
70
- return main === undefined || !busy(main) ? main : undefined;
70
+ return main !== undefined && main.provider !== "opencode" && busy(main) ? main : undefined;
71
71
  };
72
+ /** The bound chat's main conversation, unless it is busy and forks (#4584): then undefined, so the message runs at once in a new conversation forked from it and never waits behind the reply under way. */
73
+ const freeBound = (key) => (forkedFrom(key) === undefined ? boundOf(key) : undefined);
72
74
  /** The bound chat: ONE main conversation at the workspace root, every message goes on with it, or beside it in a fork while it is busy (#4584); a stop pauses the one at work, /new opens the next one at once. */
73
75
  const ONE = {
74
76
  conversationOf: boundOf,
@@ -88,11 +90,7 @@ const ONE = {
88
90
  return `⏹ Stopped${forks === 0 ? "" : `, with ${parallel}`}. Your next message picks the conversation up where it stopped.`;
89
91
  },
90
92
  folderOf: () => rootFolder(),
91
- forkOf: (key) => {
92
- const main = boundOf(key);
93
- // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
94
- return main !== undefined && busy(main) ? main.sessionId : undefined;
95
- },
93
+ forkOf: (key) => forkedFrom(key)?.sessionId,
96
94
  async renew(key, platform, end, provider) {
97
95
  for (const c of ONE.allOf(key)) {
98
96
  end(c.id);
@@ -125,6 +123,17 @@ export const SLACK_DM = "slack:dm:";
125
123
  function carriageOf(platform, key) {
126
124
  return key.startsWith(SLACK_DM) ? ONE : CARRIAGE[platform];
127
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
+ }
128
137
  const COMMAND_RE = /^\/?(new|stop)(@\w+)?$/i;
129
138
  const FINAL_KINDS = new Set(["answer", "failed", "stopped", "archived", "deleted"]);
130
139
  export class AgentGateway {
@@ -170,7 +179,9 @@ export class AgentGateway {
170
179
  for (const [turn, sent] of owed) {
171
180
  const pending = readEvents(c.id).filter((e) => e.turn === Number(turn) && e.n > sent && e.role !== "user").map((e) => ({ ...e, id: c.id }));
172
181
  // OWNER: ITER/LOOP — a thread that cannot be reached is shown on its conversation and the next owed turn is still carried on.
173
- 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)}` }));
182
+ const answered = this.awaitTurn(c.id, Number(turn), partsRelay((part) => door(c, part), carriageOf(c.platform, c.chat ?? "")), pending);
183
+ // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
184
+ void (c.forkOf === undefined ? answered : answered.finally(() => this.end(c.id))).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)}` }));
174
185
  }
175
186
  }
176
187
  /** No chat message waiting on its conversation's creation: the gateway can pass to another process without losing one. A turn under way never holds it — the next build takes a cut turn up again on its session and sends its answer to its chat (#2116, #4584). */
@@ -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
@@ -290,16 +319,25 @@ export class AgentGateway {
290
319
  // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
291
320
  const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
292
321
  const turn = {};
293
- const [creation] = await Promise.allSettled([createdIn(project, act.kind === "say" ? act.provider : undefined, () => key, (on) => {
294
- const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: act.text, receivedMs: monotonicMs() - arrived });
295
- turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false, forkOf !== undefined));
322
+ // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
323
+ const provider = forkOf !== undefined ? open.provider : act.kind === "say" ? act.provider : undefined;
324
+ const [creation] = await Promise.allSettled([createdIn(project, provider, () => key, (on) => {
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));
328
+ // NULL-OK: field forkOf is OPTIONAL and therefore it is ok to check for NULL
329
+ turn.answered = forkOf === undefined ? answered : answered.finally(() => this.end(created.id));
296
330
  turn.id = created.id;
297
331
  return created;
298
332
  })]);
299
333
  if (creation.status === "rejected") {
300
334
  // NULL-OK: field id is OPTIONAL and therefore it is ok to check for NULL
301
- if (turn.id === undefined)
302
- 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
+ }
303
341
  const reason = creation.reason instanceof Error ? creation.reason.message : String(creation.reason);
304
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`);
305
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}`));
@@ -421,8 +459,9 @@ export function chatTurnText(key, text, context) {
421
459
  if (bound === undefined)
422
460
  return [brief, ...context, text].join("\n\n");
423
461
  // A message beside a main conversation whose session is not written yet runs in a session of its own, which has not had the brief.
424
- const first = !readEvents(bound.id).some((e) => e.role === "user") || (busy(bound) && !bound.started);
425
- return [...(first ? [brief] : []), ...answeredBeside(key, bound), ...(busy(bound) ? [BESIDE] : []), ...context, text].join("\n\n");
462
+ const beside = forkedFrom(key) !== undefined;
463
+ const first = !readEvents(bound.id).some((e) => e.role === "user") || (beside && !bound.started);
464
+ return [...(first ? [brief] : []), ...answeredBeside(key, bound), ...(beside ? [BESIDE] : []), ...context, text].join("\n\n");
426
465
  }
427
466
  /** The Claude CLI's own folder of session transcripts. */
428
467
  function claudeProjects() {
@@ -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,59 +1,59 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const { spawn } = require("child_process");
6
-
7
- const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
8
-
9
- function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
10
- return [
11
- deploy,
12
- "--domain", domain,
13
- ...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
14
- // NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
15
- "--project-root", projectRoot ?? home,
16
- "--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
17
- "--notify-dir", doorsDir,
18
- ];
19
- }
20
-
21
- function runDeploy({ node, args, cwd, env, onOutput }) {
22
- return new Promise((resolve, reject) => {
23
- const child = spawn(node, args, { windowsHide: true, cwd, env });
24
- child.stdout.on("data", (chunk) => onOutput(String(chunk)));
25
- child.stderr.on("data", (chunk) => onOutput(String(chunk)));
26
- child.on("error", reject);
27
- child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
28
- });
29
- }
30
-
31
- const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
32
-
33
- function writeRecord(file, record) {
34
- const staged = `${file}.${process.pid}.tmp`;
35
- fs.writeFileSync(staged, JSON.stringify(record, null, 2));
36
- try {
37
- fs.renameSync(staged, file);
38
- } catch (err) {
39
- fs.rmSync(staged, { force: true });
40
- throw err;
41
- }
42
- }
43
-
44
- async function runRecorded(recordFile, recordText) {
45
- const record = { ...JSON.parse(recordText), pid: process.pid };
46
- const log = recordFile.replace(/\.json$/, ".log");
47
- const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
48
- try {
49
- const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
50
- write({ endedAt: new Date().toISOString(), ...ended });
51
- } catch (err) {
52
- // OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
53
- write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
54
- }
55
- }
56
-
57
- if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
58
-
59
- module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { spawn } = require("child_process");
6
+
7
+ const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
8
+
9
+ function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
10
+ return [
11
+ deploy,
12
+ "--domain", domain,
13
+ ...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
14
+ // NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
15
+ "--project-root", projectRoot ?? home,
16
+ "--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
17
+ "--notify-dir", doorsDir,
18
+ ];
19
+ }
20
+
21
+ function runDeploy({ node, args, cwd, env, onOutput }) {
22
+ return new Promise((resolve, reject) => {
23
+ const child = spawn(node, args, { windowsHide: true, cwd, env });
24
+ child.stdout.on("data", (chunk) => onOutput(String(chunk)));
25
+ child.stderr.on("data", (chunk) => onOutput(String(chunk)));
26
+ child.on("error", reject);
27
+ child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
28
+ });
29
+ }
30
+
31
+ const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
32
+
33
+ function writeRecord(file, record) {
34
+ const staged = `${file}.${process.pid}.tmp`;
35
+ fs.writeFileSync(staged, JSON.stringify(record, null, 2));
36
+ try {
37
+ fs.renameSync(staged, file);
38
+ } catch (err) {
39
+ fs.rmSync(staged, { force: true });
40
+ throw err;
41
+ }
42
+ }
43
+
44
+ async function runRecorded(recordFile, recordText) {
45
+ const record = { ...JSON.parse(recordText), pid: process.pid };
46
+ const log = recordFile.replace(/\.json$/, ".log");
47
+ const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
48
+ try {
49
+ const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
50
+ write({ endedAt: new Date().toISOString(), ...ended });
51
+ } catch (err) {
52
+ // OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
53
+ write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
54
+ }
55
+ }
56
+
57
+ if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
58
+
59
+ module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
@@ -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
  }