omni-notify-mcp 1.3.476 β†’ 1.3.477

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.
@@ -18,6 +18,7 @@ import { choicesOf, StreamedReply } from "./messaging/messenger.js";
18
18
  import { appendEvent, archiveConversation, conversationRefusal, openConversation, readConversation, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, rootFolder, routeAsk, stopTargetOf, sendToConversation, startConversation, turnInFlight, updateConversation, } from "./gateway/conversationOwner.js";
19
19
  import { conversationOwner } from "./gateway/conversationOwner.js";
20
20
  import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
21
+ import { toolLine } from "./shared/conversation/provider.js";
21
22
  import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
22
23
  export const AGENT_PREFIX = "!";
23
24
  /** The thread's newest conversation is ended; the next message opens a fresh one. */
@@ -30,6 +31,8 @@ async function endNewest(key, _platform, end) {
30
31
  return stay === 0 ? "πŸ†• New conversation. Your next ! message starts it." : `πŸ†• Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`;
31
32
  }
32
33
  const stoppedOfMany = ([stopped], others) => others === 0 ? "⏹ Conversation ended. Your next ! message opens a new one." : `⏹ Conversation ${stopped.id.slice(0, 8)} ended. ${others} other conversation${others === 1 ? " stays" : "s stay"} open.`;
34
+ /** The pieces of a turn shown while they happen and never stored: a tool step started or ended. */
35
+ const LIVE_KINDS = new Set(["step", "stepDone", "stepFailed"]);
33
36
  /** Each carried event of a turn sent as its parts. */
34
37
  function partsRelay(reply, carriage) {
35
38
  return {
@@ -47,7 +50,7 @@ const CHAT = {
47
50
  routeOf: routeAsk,
48
51
  stopOf: (key) => [stopTargetOf(key)].filter((c) => c !== undefined),
49
52
  allOf: openConversationsOf,
50
- carries: (kind) => kind !== "returned",
53
+ carries: (kind) => kind !== "returned" && !LIVE_KINDS.has(kind),
51
54
  parts: (event) => (event.kind === "answer" ? splitForNotify(event.text) : [event.text]),
52
55
  stopped: stoppedOfMany,
53
56
  renew: endNewest,
@@ -100,7 +103,7 @@ const ONE = {
100
103
  return `πŸ†• Fresh conversation β€” your next message starts it.${notice === undefined ? "" : `\n${notice.text}`}`;
101
104
  },
102
105
  };
103
- const MAILED_KINDS = new Set(["answer", "failed", "stopped"]);
106
+ const MAILED_KINDS = new Set(["answer", "failed", "stopped", "asking"]);
104
107
  /** An email thread: its one conversation, a stopped one resumed by the next reply; only what needs Meni is mailed, each whole. */
105
108
  const THREADS_ONE = (key) => listConversations().find((c) => c.chat === key);
106
109
  const MAIL = {
@@ -203,7 +206,7 @@ export class AgentGateway {
203
206
  const said = raw.trim();
204
207
  const text = said.replace(/^!\s*/, "");
205
208
  const cmd = text.match(COMMAND_RE);
206
- const commanded = cmd !== null && (bare || text.startsWith("/") || said.startsWith(AGENT_PREFIX));
209
+ const commanded = cmd !== null && (bare || text.startsWith("/") || said.startsWith(AGENT_PREFIX) || cmd[1].toLowerCase() === "stop");
207
210
  return commanded ? { kind: cmd[1].toLowerCase() === "new" ? "new" : "stop" } : { kind: "say", text };
208
211
  }
209
212
  /** A message inside a thread the agent holds is all for the agent: `/new` and `/stop` act, anything else is said, with or without `!`. */
@@ -242,7 +245,7 @@ export class AgentGateway {
242
245
  const arrived = monotonicMs();
243
246
  const carriage = carriageOf(platform, key);
244
247
  const reply = typeof out === "function" ? out : out.say;
245
- const relayOf = (id, n, queued) => (typeof out === "function" ? partsRelay(out, carriage) : out.turn(id, n, queued));
248
+ const relayOf = (id, n, queued, parallel = false) => (typeof out === "function" ? partsRelay(out, carriage) : out.turn(id, n, queued, parallel));
246
249
  const refusal = conversationRefusal();
247
250
  if (refusal !== undefined)
248
251
  return reply(refusal);
@@ -289,7 +292,7 @@ export class AgentGateway {
289
292
  const turn = {};
290
293
  const [creation] = await Promise.allSettled([createdIn(project, act.kind === "say" ? act.provider : undefined, () => key, (on) => {
291
294
  const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: act.text, receivedMs: monotonicMs() - arrived });
292
- turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false));
295
+ turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false, forkOf !== undefined));
293
296
  turn.id = created.id;
294
297
  return created;
295
298
  })]);
@@ -350,6 +353,8 @@ export class AgentGateway {
350
353
  relay.close();
351
354
  throw err;
352
355
  });
356
+ if (LIVE_KINDS.has(event.kind))
357
+ continue;
353
358
  const final = FINAL_KINDS.has(event.kind ?? "");
354
359
  if (!closed)
355
360
  editOwed(id, (o) => { if (final)
@@ -439,17 +444,9 @@ function transcriptOf(sessionId) {
439
444
  function fsFailure(err) {
440
445
  return err instanceof Error && typeof err.code === "string";
441
446
  }
442
- /** A tool step as he reads it: the tool and what it is doing. */
443
- function stepOf(block) {
444
- const input = block.input ?? {};
445
- const what = [input.description, input.command, input.file_path, input.pattern, input.url, input.prompt].find((v) => typeof v === "string" && v.trim() !== "");
446
- // NULL-OK: field what is OPTIONAL and therefore it is ok to check for NULL
447
- const shown = what === undefined ? "" : ` β€” ${what.replace(/\s+/g, " ").slice(0, 90)}`;
448
- return `πŸ”§ ${String(block.name ?? "tool")}${shown}`;
449
- }
450
447
  /**
451
- * A conversation's Claude transcript read as it grows while a turn runs: each text block the agent writes and each tool
452
- * it starts reach the chat's preview. The CLI writes one line per block, so the preview moves block by block.
448
+ * A conversation's Claude transcript read as it grows while a turn runs: each text block the agent writes reaches the
449
+ * chat as a message once the agent has gone on to a tool or a next text. The CLI writes one line per block.
453
450
  */
454
451
  class TranscriptTail {
455
452
  sessionId;
@@ -543,27 +540,35 @@ class TranscriptTail {
543
540
  this.log(`transcript ${this.sessionId}: a line is not JSON (${err.message}) β€” it is left out of the chat's preview`);
544
541
  return;
545
542
  }
546
- if (entry.type !== "assistant" || !Array.isArray(entry.message?.content))
543
+ if (!Array.isArray(entry.message?.content))
547
544
  return;
548
545
  for (const block of entry.message.content) {
549
- if (block.type === "text" && typeof block.text === "string")
546
+ if (entry.type === "assistant" && block.type === "text" && typeof block.text === "string")
550
547
  this.reply.wrote(block.text);
551
- if (block.type === "tool_use")
552
- this.reply.step(stepOf(block));
548
+ if (entry.type === "assistant" && block.type === "tool_use")
549
+ this.reply.step(String(block.id), toolLine(String(block.name ?? "tool"), block.input));
550
+ if (entry.type === "user" && block.type === "tool_result")
551
+ this.reply.stepDone(String(block.tool_use_id), block.is_error !== true);
553
552
  }
554
553
  }
555
554
  }
556
- /** The draft of each streamed turn this process shows, one id per turn so no turn's preview lands on another's. */
557
- let draftIds = 0;
558
- /** The bound chat's turns as they happen (#4453): the working state at once, the agent's text and steps as a paced preview, the answer with its choices as buttons. */
555
+ /** How long a turn took, in one short line a CLI prints when it ends; empty when the turn was not timed. */
556
+ function tookLine(event) {
557
+ const ms = event.timing?.agentMs ?? event.timing?.totalMs;
558
+ // NULL-OK: field ms is OPTIONAL and therefore it is ok to check for NULL
559
+ if (ms === undefined)
560
+ return "";
561
+ const seconds = Math.max(1, Math.round(ms / 1000));
562
+ return `\n\n⏱ ${seconds < 60 ? `${seconds} s` : `${Math.floor(seconds / 60)} min ${seconds % 60} s`}`;
563
+ }
564
+ /** The bound chat's turns as they happen (#4453): the start line at once, each text the agent finishes as a message of its own, the answer with its choices as buttons. */
559
565
  export function streamedChat(messenger, log) {
560
566
  return {
561
- say: (text) => messenger.send(text),
562
- turn(id, _n, queued) {
563
- const reply = new StreamedReply(messenger, ++draftIds, log);
567
+ say: async (text) => { await messenger.send(text); },
568
+ turn(id, _n, _queued, parallel) {
569
+ const chat = parallel ? messenger.alongside() : messenger;
570
+ const reply = new StreamedReply(chat, log);
564
571
  let tail;
565
- if (!queued)
566
- reply.begin();
567
572
  const ended = () => {
568
573
  // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
569
574
  tail?.stop();
@@ -577,16 +582,35 @@ export function streamedChat(messenger, log) {
577
582
  async event(event) {
578
583
  switch (event.kind) {
579
584
  case "start":
580
- reply.begin(event.text);
585
+ // The start line stays in the store for the web page; the chat gets no message before the first real output, so nothing sits between his message and his next one.
581
586
  // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
582
587
  tail ??= TranscriptTail.of(id, reply, log);
583
588
  return;
589
+ case "said":
590
+ reply.said(event.text);
591
+ return;
592
+ case "step":
593
+ // NULL-OK: field uid is OPTIONAL and therefore it is ok to check for NULL
594
+ reply.step(event.uid ?? event.text, event.text);
595
+ return;
596
+ case "stepDone":
597
+ case "stepFailed":
598
+ // NULL-OK: field uid is OPTIONAL and therefore it is ok to check for NULL
599
+ reply.stepDone(event.uid ?? "", event.kind === "stepDone", event.text);
600
+ return;
601
+ case "asking": {
602
+ const { text, choices } = choicesOf(event.text);
603
+ reply.ask(text, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
604
+ return;
605
+ }
584
606
  case "answer": {
585
607
  ended();
586
608
  const { text, choices } = choicesOf(event.text);
587
- return reply.finish(text, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
609
+ return reply.finish(`${text}${tookLine(event)}`, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
588
610
  }
589
611
  case "failed":
612
+ ended();
613
+ return reply.finish(`${event.text}${tookLine(event)}`);
590
614
  case "stopped":
591
615
  case "archived":
592
616
  case "deleted":
@@ -597,7 +621,8 @@ export function streamedChat(messenger, log) {
597
621
  case "restored":
598
622
  return;
599
623
  default:
600
- return messenger.send(event.text);
624
+ await chat.send(event.text);
625
+ return;
601
626
  }
602
627
  },
603
628
  };
@@ -2,11 +2,11 @@
2
2
  * One private chat as one BN conversation (#4453): the messenger interface the conversation's turn is relayed through,
3
3
  * the streamed reply that paces its updates, and the Telegram messenger with every Bot API call classified.
4
4
  *
5
- * A turn shows the platform's own working state the moment the message is stored, then the agent's text and tool steps
6
- * as they are written β€” one preview updated no faster than the platform allows β€” and ends in the answer, split at the
7
- * platform's message limit, its πŸ”˜ lines turned into buttons. Built from https://core.telegram.org/bots/api
8
- * (sendMessageDraft, sendMessage, answerCallbackQuery, editMessageReplyMarkup, ResponseParameters) and the Bot FAQ's
9
- * "one message per second per chat".
5
+ * A turn says so in a real message the moment it starts, sends each text the agent finishes as a message of its own while
6
+ * the turn goes on β€” no faster than the platform allows β€” and ends in the answer, split at the platform's message limit,
7
+ * its πŸ”˜ lines turned into buttons. There is no preview and no typing state: the chat shows only messages. Built from
8
+ * https://core.telegram.org/bots/api (sendMessage, answerCallbackQuery, editMessageReplyMarkup, ResponseParameters) and
9
+ * the Bot FAQ's "one message per second per chat".
10
10
  */
11
11
  import { markdownToTelegramHtml, stripTelegramMarks } from "./telegramFormat.js";
12
12
  import { messageBlocks } from "./slackBlocks.js";
@@ -74,110 +74,122 @@ export function splitMessage(text, limit) {
74
74
  close(part, undefined);
75
75
  return parts.filter((p) => p !== "");
76
76
  }
77
+ // GATE: how long tool lines are held to be sent as ONE message β€” a run of tool calls costs a message, never one per call.
78
+ const STEP_BATCH_MS = 2500;
77
79
  /**
78
- * One turn's reply in a chat: the working state at once, then a preview of what the agent writes, sent no faster than
79
- * the messenger's pace and again before the platform lets it lapse, then the answer itself. A preview the platform
80
- * refuses for good is stopped for the rest of the turn and named under the answer, never dropped unsaid.
80
+ * One turn's messages in a chat, slim and in order: each text the agent finishes is one message when it finishes, a run
81
+ * of tool calls is one short message of CLI-style lines, and the answer is one message at the end. Every message keeps the
82
+ * messenger's pace and its order; the turn's last text β€” its answer β€” is never also sent as a finished text. There is no
83
+ * streaming, no edit and no typing state: only messages.
81
84
  */
82
85
  export class StreamedReply {
83
86
  messenger;
84
- id;
85
87
  log;
86
- said = "";
87
- doing = "";
88
- shown;
88
+ held = "";
89
89
  lastAt = 0;
90
- timer;
91
- /** The timer only re-sends an unchanged preview before it lapses, so a new update may take its place. */
92
- holding = false;
93
90
  inFlight = Promise.resolve();
94
91
  ended = false;
95
- began = false;
96
- previewOff;
97
- constructor(messenger, id, log) {
92
+ steps = [];
93
+ stepTimer;
94
+ constructor(messenger, log) {
98
95
  this.messenger = messenger;
99
- this.id = id;
100
96
  this.log = log;
101
97
  }
102
- /** Shows the working state now; a reply already begun is left as it is. */
103
- begin(doing = "") {
104
- if (this.ended)
105
- return;
106
- if (doing !== "")
107
- this.doing = doing;
108
- if (this.began)
109
- return this.schedule();
110
- this.began = true;
111
- this.flush();
112
- }
113
- /** A block of text the agent wrote during the turn. */
98
+ /** A text the agent finished writing: the tool lines before it go out first, then it is sent at once. */
99
+ said(text) {
100
+ this.flushSteps();
101
+ this.post(text);
102
+ }
103
+ /** A block of text the agent wrote, for a CLI that reports only finished blocks: the one before it is complete and goes out now, this one may be the answer and waits. */
114
104
  wrote(block) {
115
105
  const text = block.trim();
116
106
  if (text === "")
117
107
  return;
118
- this.said = this.said === "" ? text : `${this.said}\n\n${text}`;
119
- this.begin();
108
+ this.release();
109
+ this.held = text;
110
+ }
111
+ /** The agent started a tool: the text it wrote before is complete, and the tool is a line of the next steps message. */
112
+ step(id, line) {
113
+ if (this.ended)
114
+ return;
115
+ this.release();
116
+ this.steps.push({ id, text: line, mark: "" });
117
+ // NULL-OK: field stepTimer is OPTIONAL and therefore it is ok to check for NULL
118
+ this.stepTimer ??= setTimeout(() => this.flushSteps(), STEP_BATCH_MS);
119
+ this.stepTimer.unref();
120
+ }
121
+ /** A tool ended: its line shows how, if its message has not gone out yet; a run of tools that has all ended goes out at once. */
122
+ stepDone(id, ok, why) {
123
+ const line = this.steps.find((s) => s.id === id);
124
+ // NULL-OK: field line is OPTIONAL and therefore it is ok to check for NULL
125
+ if (line === undefined)
126
+ return;
127
+ line.mark = ok ? " βœ…" : ` ❌${why === undefined || why === "" ? "" : ` ${why}`}`;
128
+ if (this.steps.every((s) => s.mark !== ""))
129
+ this.flushSteps();
130
+ }
131
+ /** The tool lines waiting go out as one message. */
132
+ flushSteps() {
133
+ clearTimeout(this.stepTimer);
134
+ this.stepTimer = undefined;
135
+ if (this.steps.length === 0)
136
+ return;
137
+ const text = this.steps.map((s) => `${s.text}${s.mark}`).join("\n");
138
+ this.steps = [];
139
+ this.post(text);
120
140
  }
121
- /** The step the agent is on now. */
122
- step(line) {
123
- this.doing = line;
124
- this.begin();
141
+ release() {
142
+ if (this.held === "")
143
+ return;
144
+ const text = this.held;
145
+ this.held = "";
146
+ this.said(text);
125
147
  }
126
- /** Ends the preview with nothing more to send: the turn was ended from the chat. */
148
+ /** Ends the reply with nothing more to send: the turn was ended from the chat. */
127
149
  close() {
128
150
  this.ended = true;
129
- clearTimeout(this.timer);
151
+ this.held = "";
152
+ this.steps = [];
153
+ clearTimeout(this.stepTimer);
154
+ this.stepTimer = undefined;
130
155
  }
131
- /** Ends the preview and sends the reply's final text, split at the limit, its choices as buttons on the last part. */
156
+ /** Ends the turn and sends the reply's final text, split at the limit, its choices as buttons on the last part. */
132
157
  async finish(text, buttons = []) {
158
+ this.flushSteps();
133
159
  this.ended = true;
134
- clearTimeout(this.timer);
160
+ this.held = "";
135
161
  await this.inFlight;
136
- const body = this.previewOff === undefined ? text : `${text}\n\n_⚠️ The live preview was off for this turn: ${this.previewOff}_`;
137
- const parts = splitMessage(body, this.messenger.limit);
162
+ const parts = splitMessage(text, this.messenger.limit);
138
163
  for (const [i, part] of parts.entries()) {
139
- // Each part keeps the messenger's pace after the preview and the part before it, so the chat never takes two updates closer than it allows.
140
- await sleep(this.lastAt + this.messenger.paceMs - Date.now());
164
+ await this.paced();
165
+ await this.messenger.send(part, i === parts.length - 1 ? buttons : [], i === 0);
141
166
  this.lastAt = Date.now();
142
- await this.messenger.send(part, i === parts.length - 1 ? buttons : [], i === 0 ? this.id : undefined);
143
167
  }
144
168
  }
145
- view() {
146
- const doing = this.doing === "" ? "" : `_${this.doing}_`;
147
- const whole = [this.said, doing].filter((s) => s !== "").join("\n\n");
148
- const room = this.messenger.limit - 2;
149
- return whole.length <= room ? whole : `…${whole.slice(whole.length - room)}`;
150
- }
151
- /** The next update at the messenger's pace; one already paced is left to go, a hold waiting to re-send the preview gives way to it. */
152
- schedule() {
153
- if (this.ended || this.previewOff !== undefined || (this.timer !== undefined && !this.holding))
154
- return;
155
- this.wait(Math.max(0, this.lastAt + this.messenger.paceMs - Date.now()), false);
169
+ /** Waits until the platform's pace allows the next message: its gap is counted from the end of the last one. */
170
+ paced() {
171
+ return sleep(Math.max(0, this.lastAt + this.messenger.paceMs - Date.now()));
156
172
  }
157
- wait(ms, holding) {
158
- clearTimeout(this.timer);
159
- this.holding = holding;
160
- this.timer = setTimeout(() => this.flush(), ms);
161
- this.timer.unref();
173
+ /** A question the agent asks mid-turn: one message with its choices as buttons, and the turn goes on after it. */
174
+ ask(text, buttons) {
175
+ this.flushSteps();
176
+ this.post(text, buttons, true);
162
177
  }
163
- flush() {
164
- this.timer = undefined;
165
- if (this.ended || this.previewOff !== undefined)
178
+ post(text, buttons = [], answer = false) {
179
+ const body = text.trim();
180
+ if (this.ended || body === "")
166
181
  return;
167
- const view = this.view();
168
- const stale = Date.now() - this.lastAt >= this.messenger.holdMs;
169
- if (view === this.shown && !stale)
170
- return this.wait(this.lastAt + this.messenger.holdMs - Date.now(), true);
171
- this.shown = view;
172
- this.lastAt = Date.now();
173
- this.inFlight = this.inFlight.then(() => this.messenger.draft(this.id, view)).catch((err) => {
174
- // OWNER: the preview is shown on a timer, its own trigger root β€” a refused preview is stopped for the rest of the turn and named under the answer, a passing failure is retried by the next update.
175
- const why = err instanceof Error ? err.message : String(err);
176
- if (err instanceof ChannelOff || err instanceof TelegramRefused || err instanceof TelegramUnknown || err instanceof SlackRefused || err instanceof SlackUnknown)
177
- this.previewOff = why;
178
- this.log(`preview ${this.id} not shown: ${why}${this.previewOff === undefined ? " β€” the next update sends it again" : " β€” no more previews this turn"}`);
182
+ this.inFlight = this.inFlight.then(async () => {
183
+ const parts = splitMessage(body, this.messenger.limit);
184
+ for (const [i, part] of parts.entries()) {
185
+ await this.paced();
186
+ await this.messenger.send(part, i === parts.length - 1 ? buttons : [], answer && i === 0);
187
+ this.lastAt = Date.now();
188
+ }
189
+ }).catch((err) => {
190
+ // OWNER: a text of a turn is sent from the turn's own event trigger β€” one that cannot be sent is named in the log and the answer, sent whole at the end, still carries the turn.
191
+ this.log(`a text of the turn was not sent: ${err instanceof Error ? err.message : String(err)}`);
179
192
  });
180
- this.wait(this.messenger.holdMs, true);
181
193
  }
182
194
  }
183
195
  // ── Telegram ───────────────────────────────────────────────────────────────
@@ -267,7 +279,7 @@ export async function telegramCall(url, method, body, tries = TELEGRAM_TRIES, ti
267
279
  }
268
280
  }
269
281
  const unparsable = (err) => err instanceof TelegramRefused && err.status === 400 && /can't parse entities/i.test(err.description);
270
- /** The bound private chat: messages in Telegram's rich text, previews by sendMessageDraft, choices as inline buttons. */
282
+ /** The bound private chat: messages in Telegram's rich text, choices as inline buttons. */
271
283
  export class TelegramMessenger {
272
284
  api;
273
285
  file;
@@ -276,13 +288,13 @@ export class TelegramMessenger {
276
288
  switchedOn;
277
289
  log;
278
290
  thread;
291
+ replyTo;
292
+ quoting;
279
293
  // GATE: source characters per message β€” Telegram takes 4096 after entities are parsed, and the markdown source is never shorter than what it renders, so a part this size always fits.
280
294
  limit = 3900;
281
- // GATE: the Bot FAQ's "avoid sending more than one message per second" in a chat β€” no preview is updated faster.
295
+ // GATE: the Bot FAQ's "avoid sending more than one message per second" in a chat β€” no two messages of a turn go out faster.
282
296
  paceMs = 1000;
283
- // GATE: a draft is a 30-second preview (sendMessageDraft); it is sent again after this long so it never lapses while the agent works.
284
- holdMs = 20_000;
285
- constructor(api, file, chatId, mode, switchedOn, log, thread) {
297
+ constructor(api, file, chatId, mode, switchedOn, log, thread, replyTo, quoting = false) {
286
298
  this.api = api;
287
299
  this.file = file;
288
300
  this.chatId = chatId;
@@ -290,16 +302,22 @@ export class TelegramMessenger {
290
302
  this.switchedOn = switchedOn;
291
303
  this.log = log;
292
304
  this.thread = thread;
305
+ this.replyTo = replyTo;
306
+ this.quoting = quoting;
293
307
  }
294
308
  /** #4586: every message of this messenger lands in its story's topic when it has one. */
295
309
  get topic() { return this.thread === undefined ? {} : { message_thread_id: this.thread }; }
296
310
  async send(text, buttons = []) {
297
- const reply_markup = buttons.length === 0 ? undefined : { inline_keyboard: buttons.map((b) => [{ text: b.label, callback_data: b.data }]) };
298
- await this.formatted("sendMessage", { chat_id: this.chatId, reply_markup, ...this.topic }, text);
311
+ await this.formatted("sendMessage", { chat_id: this.chatId, reply_markup: this.markup(buttons), ...this.topic, ...this.quote }, text);
299
312
  }
300
- async draft(id, text) {
301
- await this.formatted("sendMessageDraft", { chat_id: Number(this.chatId), draft_id: id, ...this.topic }, text);
313
+ alongside() {
314
+ return this.replyTo === undefined ? this : new TelegramMessenger(this.api, this.file, this.chatId, this.mode, this.switchedOn, this.log, this.thread, this.replyTo, true);
302
315
  }
316
+ markup(buttons) {
317
+ return buttons.length === 0 ? undefined : { inline_keyboard: buttons.map((b) => [{ text: b.label, callback_data: b.data }]) };
318
+ }
319
+ /** The message every one of this messenger's quotes, when it runs beside another conversation's. */
320
+ get quote() { return this.quoting && this.replyTo !== undefined ? { reply_parameters: { message_id: this.replyTo, allow_sending_without_reply: true } } : {}; }
303
321
  /** The bytes of a photo or file he sent, by getFile and its download link; Telegram's own refusal (a file over 20 MB) is thrown as it said it. */
304
322
  async received(fileId) {
305
323
  const { file_path } = await telegramCall(this.api("getFile"), "getFile", { file_id: fileId });
@@ -504,11 +522,8 @@ export class SlackMessenger {
504
522
  tappable;
505
523
  // GATE: source characters per message β€” chat.update refuses a text over 4,000 characters (msg_too_long), and mrkdwn's escapes (& as &amp;) can lengthen the source, so a part leaves room for them.
506
524
  limit = 3500;
507
- // GATE: chat.update is a Tier 3 method (about 50 calls a minute) β€” no preview is updated faster.
525
+ // GATE: chat.postMessage is Tier 4 and Slack asks for about one message per second per channel β€” no two messages of a turn go out faster than this.
508
526
  paceMs = 1200;
509
- // GATE: a Slack message stays until it is edited, so an unchanged preview is sent again only after ten minutes.
510
- holdMs = 600_000;
511
- previews = new Map();
512
527
  constructor(base, token, channel, switchedOn,
513
528
  /** The thread every message of this view lands in; undefined posts at the top of the chat. */
514
529
  threadTs, state = { choices: [] }, log = () => undefined,
@@ -527,57 +542,42 @@ export class SlackMessenger {
527
542
  inThread(ts) {
528
543
  return new SlackMessenger(this.base, this.token, this.channel, this.switchedOn, ts, { choices: [] }, this.log, this.tappable);
529
544
  }
530
- async send(text, buttons = [], ends) {
545
+ async send(text, buttons = [], answer = false) {
546
+ const { fallback, blocks } = this.shown(text, buttons, answer);
547
+ await this.post(fallback, blocks);
548
+ }
549
+ /** Slack threads its own replies; a parallel conversation's answers are labelled by the thread they are in. */
550
+ alongside() {
551
+ return this;
552
+ }
553
+ shown(text, buttons, answer) {
531
554
  const labels = buttons.map((b) => b.label);
532
555
  const numbered = labels.map((label, i) => `${KEYCAPS[i] ?? `${i + 1}.`} ${label}`);
533
556
  // The text is what a notification and a client without blocks show, so it carries the choices too.
534
557
  const fallback = numbered.length === 0 ? text : `${text}\n\n${numbered.join("\n")}\n_Tap a choice, reply with its number, or answer in your own words._`;
535
558
  // Each answer's own choices replace the last ones, so a number he answers a later question with is never taken as an older choice.
536
- // NULL-OK: field ends is OPTIONAL and therefore it is ok to check for NULL
537
- if (ends !== undefined)
559
+ if (answer)
538
560
  this.state.choices = [];
539
561
  if (labels.length > 0)
540
562
  this.state.choices = labels;
541
- // NULL-OK: field ends is OPTIONAL and therefore it is ok to check for NULL
542
- const preview = ends === undefined ? undefined : this.previews.get(ends);
543
- // NULL-OK: field ends is OPTIONAL and therefore it is ok to check for NULL
544
- if (ends !== undefined)
545
- this.previews.delete(ends);
546
- const blocks = messageBlocks(text, labels, `bn_choices_${Date.now().toString(36)}`, this.tappable());
547
- // NULL-OK: field preview is OPTIONAL and therefore it is ok to check for NULL
548
- await this.post(preview, fallback, blocks);
549
- }
550
- async draft(id, text) {
551
- const shown = text === "" ? "⏳ _Working…_" : text;
552
- const posted = await this.post(this.previews.get(id), shown, messageBlocks(shown, [], "bn_preview"));
553
- // NULL-OK: field posted is OPTIONAL and therefore it is ok to check for NULL
554
- if (posted !== undefined)
555
- this.previews.set(id, posted);
556
- }
557
- /** Posts the message, or edits `ts` into it, as blocks; blocks Slack refuses go out once more as the plain mrkdwn text, logged. Answers the ts of a new message. */
558
- async post(ts, text, blocks) {
563
+ return { fallback, blocks: messageBlocks(text, labels, `bn_choices_${Date.now().toString(36)}`, this.tappable()) };
564
+ }
565
+ /** Posts the message as blocks; blocks Slack refuses go out once more as the plain mrkdwn text, logged. */
566
+ async post(text, blocks) {
559
567
  const where = { channel: this.channel };
560
568
  // NULL-OK: field threadTs is OPTIONAL and therefore it is ok to check for NULL
561
- if (ts === undefined && this.threadTs !== undefined)
569
+ if (this.threadTs !== undefined)
562
570
  where.thread_ts = this.threadTs;
563
- // NULL-OK: field ts is OPTIONAL and therefore it is ok to check for NULL
564
- const method = ts === undefined ? "chat.postMessage" : "chat.update";
565
- // NULL-OK: field ts is OPTIONAL and therefore it is ok to check for NULL
566
- if (ts !== undefined)
567
- where.ts = ts;
568
571
  const shown = markdownToSlackMrkdwn(text);
569
- let answer;
570
572
  try {
571
- answer = await this.call(method, { ...where, text: shown, blocks: JSON.stringify(blocks) });
573
+ await this.call("chat.postMessage", { ...where, text: shown, blocks: JSON.stringify(blocks) });
572
574
  }
573
575
  catch (err) {
574
576
  if (!(err instanceof SlackRefused) || err.error !== "invalid_blocks")
575
577
  throw err;
576
- this.log(`${method} to ${this.channel} went out as plain text β€” Slack refused its blocks: ${err.message}`);
577
- answer = await this.call(method, { ...where, text: shown, blocks: "[]" });
578
+ this.log(`chat.postMessage to ${this.channel} went out as plain text β€” Slack refused its blocks: ${err.message}`);
579
+ await this.call("chat.postMessage", { ...where, text: shown, blocks: "[]" });
578
580
  }
579
- // NULL-OK: field ts is OPTIONAL and therefore it is ok to check for NULL
580
- return ts === undefined ? String(answer.ts) : undefined;
581
581
  }
582
582
  /** One post or edit in the chat, refused while Slack is switched off in BN settings. */
583
583
  call(method, body) {