@operad-io/telegram 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/replies.ts CHANGED
@@ -1,25 +1,27 @@
1
1
  /**
2
2
  * The reply side of the Telegram plugin: every new assistant message of a chat
3
- * bound to a Telegram chat is sent to that chat, once.
3
+ * bound to a Telegram chat, and the line that says a reply failed, is sent to
4
+ * that chat once.
4
5
  *
5
6
  * It wakes on the client API's `events()`, which names a chat whenever it
6
- * changes. What it then reads, the chat's bindings and its messages with their
7
- * ids and roles, the client API does not give (a row has no channels; the
8
- * transcript section is rendered Markdown with no message ids), so those two
9
- * reads stay on the plugin's store. What was sent
10
- * is recorded in the plugin's own file, per message and per chunk, so a restart
11
- * sends neither a sent message again nor skips one written while the process was
12
- * down. A send that fails is retried on the injected wait; a send that gives up
13
- * is recorded as a `send_failed` event of the plugin and is not tried again. Only replies are sent,
14
- * never the tool calls (ADR 0033 D7).
7
+ * changes. What it then reads, the chat's bindings and its messages and failure
8
+ * entries, the client API does not give (a row has no channels; the transcript
9
+ * section is rendered Markdown with no message ids), so those reads stay on the
10
+ * plugin's store. What was sent is recorded in the plugin's own file, per item
11
+ * and per chunk, so a restart sends neither a sent item again nor skips one
12
+ * written while the process was down. A send that fails is retried on the
13
+ * injected wait; a send that gives up is recorded as a `send_failed` event of the
14
+ * plugin and is not tried again. Only replies and failure lines are sent, never
15
+ * the tool calls (ADR 0033 D7).
15
16
  */
16
17
 
17
- import { CHAT_TYPE, allMessages, chatData, type Message } from "@operad-io/chat";
18
+ import { CHAT_TYPE, allEntries, allMessages, chatData } from "@operad-io/chat";
18
19
  import { messageOf, type SourceContext } from "@operad-io/engine";
19
20
  import { BotApiError, type BotApi } from "./api.ts";
21
+ import { TelegramEvents, type TelegramEvent } from "./events.ts";
20
22
  import { telegramChunks, type TelegramChunk } from "./format.ts";
21
23
  import { TELEGRAM_SOURCE } from "./source.ts";
22
- import { readSent, writeSent, type SentRecord, type SentState } from "./state.ts";
24
+ import { readSent, writeSent, pruneSent, SENT_STATE_MARGIN_MS, type SentRecord, type SentState } from "./state.ts";
23
25
 
24
26
  /** How a failed send is tried again. */
25
27
  export interface RetryPolicy {
@@ -43,6 +45,14 @@ export interface ReplySenderOptions {
43
45
  readonly retry?: RetryPolicy | undefined;
44
46
  }
45
47
 
48
+ /** One thing to send: a reply, or the line that says a reply failed. */
49
+ interface Outgoing {
50
+ readonly id: string;
51
+ readonly at: number;
52
+ readonly sequence: number;
53
+ readonly text: string;
54
+ }
55
+
46
56
  /** The Telegram chat ids a chat is bound to. */
47
57
  export function telegramChatsOf(channels: readonly string[]): readonly number[] {
48
58
  const found: number[] = [];
@@ -73,6 +83,9 @@ export class ReplySender {
73
83
  private readonly retry: RetryPolicy;
74
84
  private readonly controller = new AbortController();
75
85
  private readonly queues = new Map<string, Promise<void>>();
86
+ /** At most one sweep waits behind the one running for each chat. */
87
+ private readonly queuedSweeps = new Map<string, Promise<void>>();
88
+ private following: { readonly stop: () => Promise<void> } | undefined;
76
89
  private state: SentState;
77
90
  private stopped = false;
78
91
  private watching: Promise<void> = Promise.resolve();
@@ -90,34 +103,38 @@ export class ReplySender {
90
103
  else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
91
104
  }
92
105
 
93
- /** Sends what is waiting on every bound chat, then follows the client's events. */
94
- start(): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
95
- const iterator = this.ctx.client.events()[Symbol.asyncIterator]();
96
- // Wake-ups are pulled before the sweep so a change during it is not missed.
106
+ /** Sends what is waiting on every bound chat, then follows changes, alone or through the plugin's one loop. */
107
+ start(events?: TelegramEvents): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
108
+ const local = events === undefined ? new TelegramEvents(this.ctx, { wait: this.wait }) : undefined;
97
109
  const initial = this.sweepAll().catch((error: unknown) => this.log(`could not send replies: ${messageOf(error)}`));
98
110
  this.watching = (async () => {
99
111
  await initial;
100
- while (!this.stopped) {
101
- const next = await iterator.next();
102
- if (next.done === true || this.stopped) return;
103
- const id = next.value.id;
104
- if (id.length > 0) void this.sweepChat(id).catch((error: unknown) => this.log(`could not send replies: ${messageOf(error)}`));
105
- }
112
+ if (this.stopped) return;
113
+ this.following = local?.start({
114
+ replies: (event) => this.handleEvent(event),
115
+ });
106
116
  })();
107
117
  return {
108
118
  ready: initial,
109
119
  stop: async () => {
110
120
  this.stopped = true;
111
121
  this.controller.abort();
112
- await iterator.return?.();
122
+ await this.following?.stop();
113
123
  await this.watching.catch(() => undefined);
114
124
  await Promise.all([...this.queues.values()]);
115
125
  },
116
126
  };
117
127
  }
118
128
 
129
+ /** One stored change of a chat, as the plugin's one event loop hands it over. */
130
+ handleEvent(event: TelegramEvent): void {
131
+ if (event.section !== undefined) return;
132
+ void this.sweepChat(event.id).catch((error: unknown) => this.log(`could not send replies: ${messageOf(error)}`));
133
+ }
134
+
119
135
  /** Sweeps every chat bound to Telegram once. */
120
136
  async sweepAll(): Promise<void> {
137
+ const startedAt = this.clock();
121
138
  const ids: string[] = [];
122
139
  let cursor: string | undefined;
123
140
  do {
@@ -128,13 +145,27 @@ export class ReplySender {
128
145
  cursor = page.next;
129
146
  } while (cursor !== undefined);
130
147
  await Promise.all(ids.map((id) => this.sweepChat(id)));
148
+ // Every message older than this sweep's start was read, so nothing before
149
+ // it can still be new. Moving `since` a margin behind the start lets the
150
+ // done records behind it go without risking a message written around the
151
+ // boundary.
152
+ const since = Math.max(this.state.since, startedAt - SENT_STATE_MARGIN_MS);
153
+ if (this.stopped || since <= this.state.since) return;
154
+ this.state = pruneSent({ since, sent: this.state.sent });
155
+ writeSent(this.ctx.home, this.state);
131
156
  }
132
157
 
133
- /** Sends the unsent assistant messages of one chat; one sweep of a chat runs at a time. */
158
+ /** Sends the unsent replies and failure lines of one chat; at most one sweep waits per chat. */
134
159
  sweepChat(chatId: string): Promise<void> {
160
+ const queued = this.queuedSweeps.get(chatId);
161
+ if (queued !== undefined) return queued;
135
162
  const previous = this.queues.get(chatId) ?? Promise.resolve();
136
- const run = previous.then(() => this.sweep(chatId));
163
+ const run = previous.then(() => {
164
+ if (this.queuedSweeps.get(chatId) === run) this.queuedSweeps.delete(chatId);
165
+ return this.sweep(chatId);
166
+ });
137
167
  const settled = run.catch(() => undefined);
168
+ this.queuedSweeps.set(chatId, run);
138
169
  this.queues.set(chatId, settled);
139
170
  void settled.then(() => {
140
171
  if (this.queues.get(chatId) === settled) this.queues.delete(chatId);
@@ -149,20 +180,31 @@ export class ReplySender {
149
180
  const targets = telegramChatsOf(chatData(stored.data).channels);
150
181
  const target = targets[0];
151
182
  if (target === undefined) return;
183
+ const outgoing: Outgoing[] = [];
152
184
  for (const message of allMessages(this.ctx.store, chatId)) {
185
+ if (message.role !== "assistant") continue;
186
+ outgoing.push({ id: message.id, at: message.at, sequence: message.sequence, text: message.text });
187
+ }
188
+ // A failed reply has no assistant message; its one failure entry is sent too.
189
+ for (const entry of allEntries(this.ctx.store, chatId)) {
190
+ if (entry.kind !== "failure" || entry.text === undefined) continue;
191
+ outgoing.push({ id: `failure:${entry.sequence}`, at: entry.at, sequence: entry.sequence, text: entry.text });
192
+ }
193
+ outgoing.sort((left, right) => left.sequence - right.sequence);
194
+ for (const item of outgoing) {
153
195
  if (this.stopped) return;
154
- if (message.role !== "assistant" || message.at < this.state.since) continue;
155
- const key = `${chatId}/${message.id}`;
196
+ if (item.at < this.state.since) continue;
197
+ const key = `${chatId}/${item.id}`;
156
198
  const record = this.state.sent[key];
157
199
  if (record?.done === true) continue;
158
- await this.send(chatId, key, message, target, record);
200
+ await this.send(chatId, key, item, target, record);
159
201
  }
160
202
  }
161
203
 
162
204
  private async send(
163
205
  chatId: string,
164
206
  key: string,
165
- message: Message,
207
+ message: Outgoing,
166
208
  target: number,
167
209
  record: SentRecord | undefined,
168
210
  ): Promise<void> {
@@ -170,7 +212,7 @@ export class ReplySender {
170
212
  let sent = record?.chunks ?? 0;
171
213
  let telegramId = record?.telegramId;
172
214
  if (chunks.length === 0) {
173
- this.remember(key, { chunks: 0, done: true });
215
+ this.remember(key, { chunks: 0, done: true, at: message.at });
174
216
  return;
175
217
  }
176
218
  while (sent < chunks.length) {
@@ -183,12 +225,12 @@ export class ReplySender {
183
225
  if (this.stopped) return;
184
226
  const tries = error instanceof SendGaveUp ? error.tries : 1;
185
227
  await this.giveUp(chatId, message, sent, chunks.length, tries, error instanceof SendGaveUp ? error.last : error);
186
- this.remember(key, { chunks: sent, ...(telegramId === undefined ? {} : { telegramId }), done: true, failed: true });
228
+ this.remember(key, { chunks: sent, ...(telegramId === undefined ? {} : { telegramId }), done: true, failed: true, at: message.at });
187
229
  return;
188
230
  }
189
231
  sent += 1;
190
232
  telegramId = id;
191
- this.remember(key, { chunks: sent, telegramId, done: sent >= chunks.length });
233
+ this.remember(key, { chunks: sent, telegramId, done: sent >= chunks.length, at: message.at });
192
234
  }
193
235
  }
194
236
 
@@ -226,7 +268,7 @@ export class ReplySender {
226
268
  * after a crash records it once. It is the plugin's own record; nothing is
227
269
  * written into the chat's messages or entries, which are the chat plugin's.
228
270
  */
229
- private async giveUp(chatId: string, message: Message, sent: number, total: number, tries: number, error: unknown): Promise<void> {
271
+ private async giveUp(chatId: string, message: Outgoing, sent: number, total: number, tries: number, error: unknown): Promise<void> {
230
272
  const part = total > 1 ? ` (part ${sent + 1} of ${total})` : "";
231
273
  const text = `could not send the reply${part}; gave up after ${tries} ${tries === 1 ? "try" : "tries"}: ${messageOf(error)}`;
232
274
  await this.ctx.logger.write(`reply ${message.id} of chat ${chatId}: ${text}`);
@@ -240,7 +282,7 @@ export class ReplySender {
240
282
  }
241
283
 
242
284
  private remember(key: string, record: SentRecord): void {
243
- this.state = { since: this.state.since, sent: { ...this.state.sent, [key]: record } };
285
+ this.state = pruneSent({ since: this.state.since, sent: { ...this.state.sent, [key]: record } });
244
286
  writeSent(this.ctx.home, this.state);
245
287
  }
246
288
 
package/src/settings.ts CHANGED
@@ -14,6 +14,7 @@ export const TELEGRAM_SETTINGS: ActionArgsSchema = {
14
14
  properties: {
15
15
  users: {
16
16
  type: "array",
17
+ title: "Allowed users",
17
18
  items: { type: "integer", minimum: 1 },
18
19
  default: [],
19
20
  description:
@@ -21,12 +22,14 @@ export const TELEGRAM_SETTINGS: ActionArgsSchema = {
21
22
  },
22
23
  bot: {
23
24
  type: "string",
25
+ title: "Default bot",
24
26
  minLength: 1,
25
27
  default: DEFAULT_BOT,
26
28
  description: "The bot a chat is opened on when a listed user writes first.",
27
29
  },
28
30
  pending: {
29
31
  type: "array",
32
+ title: "Forward pending",
30
33
  items: { type: "string", minLength: 1 },
31
34
  default: [],
32
35
  description:
package/src/source.ts CHANGED
@@ -16,10 +16,12 @@ import {
16
16
  MESSAGE_EVENT,
17
17
  allMessages,
18
18
  chatData,
19
+ parseCommand,
19
20
  titleFromMessage,
20
21
  } from "@operad-io/chat";
21
22
  import { messageOf, type SourceContext, type SourceHandle } from "@operad-io/engine";
22
23
  import type { BotApi, TelegramMessage, TelegramUpdate } from "./api.ts";
24
+ import { stripBotName, PENDING_COMMAND, type CommandResponder } from "./commands.ts";
23
25
  import type { PendingResponder } from "./pending.ts";
24
26
  import { telegramSettings } from "./settings.ts";
25
27
  import { readOffset, writeOffset } from "./state.ts";
@@ -30,9 +32,15 @@ export const UPDATE_EVENT = "update";
30
32
  /** The source of every event this plugin sends. */
31
33
  export const TELEGRAM_SOURCE = "telegram";
32
34
 
35
+ /** The reaction that says a message was received. */
36
+ export const RECEIVED_REACTION = "👀";
37
+
33
38
  /** The longest summary an update event carries. */
34
39
  const SUMMARY_MAX = 300;
35
40
 
41
+ /** How many recently changed chats the source keeps for a resent message. */
42
+ export const RECENT_CHATS_MAX = 8;
43
+
36
44
  /** A delay that ends early when the signal is aborted. */
37
45
  export function delay(ms: number, signal: AbortSignal): Promise<void> {
38
46
  return new Promise((resolve) => {
@@ -50,24 +58,56 @@ export function delay(ms: number, signal: AbortSignal): Promise<void> {
50
58
  });
51
59
  }
52
60
 
61
+ /** What the source asks of the typing side: show an indicator on receipt. */
62
+ export interface TypingResponder {
63
+ /** Starts the indicator for an accepted message before its run is reported. */
64
+ received(chatId: string, target: number): void;
65
+ }
66
+
53
67
  export interface TelegramSourceOptions {
54
68
  readonly api: BotApi;
55
69
  readonly clock?: (() => number) | undefined;
56
70
  /** How long Telegram may hold a long poll open. */
57
71
  readonly longPollSecs?: number | undefined;
58
- /** The pause between two polls once one returns. */
72
+ /** The pause after a poll that failed. */
59
73
  readonly pollIntervalMs?: number | undefined;
60
74
  readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
61
75
  /** Takes the taps on pending items' buttons and the replies to their messages. */
62
76
  readonly pending?: PendingResponder | undefined;
77
+ /** Takes a command's text, the greeting `/start` and the taps on a command's choices. */
78
+ readonly commands?: CommandResponder | undefined;
79
+ /** Shows typing as soon as an ordinary message is accepted. */
80
+ readonly typing?: TypingResponder | undefined;
63
81
  }
64
82
 
65
83
  /** One bound chat and whether it still takes messages. */
66
- interface BoundChat {
84
+ export interface BoundChat {
67
85
  readonly id: string;
68
86
  readonly closed: boolean;
69
87
  }
70
88
 
89
+ /** Every chat bound to Telegram, or to one channel, newest first. */
90
+ export async function boundChats(
91
+ ctx: Pick<SourceContext, "store">,
92
+ channel?: string,
93
+ ): Promise<readonly BoundChat[]> {
94
+ const found: BoundChat[] = [];
95
+ let cursor: string | undefined;
96
+ do {
97
+ const page = await ctx.store.list(CHAT_TYPE, {
98
+ ...(cursor === undefined ? {} : { cursor }),
99
+ });
100
+ for (const object of page.objects) {
101
+ const data = chatData(object.data);
102
+ if (channel !== undefined && !data.channels.includes(channel)) continue;
103
+ if (channel === undefined && data.channels.length === 0) continue;
104
+ found.push({ id: object.id, closed: data.closed });
105
+ }
106
+ cursor = page.next;
107
+ } while (cursor !== undefined);
108
+ return found.sort((left, right) => right.id.localeCompare(left.id));
109
+ }
110
+
71
111
  /** The message text the source reads: text, else a caption. */
72
112
  function messageText(message: TelegramMessage): string | undefined {
73
113
  const text = (message.text ?? message.caption ?? "").trim();
@@ -96,8 +136,12 @@ export class TelegramSource {
96
136
  private readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
97
137
  private readonly controller = new AbortController();
98
138
  private readonly pending: PendingResponder | undefined;
139
+ private readonly commands: CommandResponder | undefined;
140
+ private readonly typing: TypingResponder | undefined;
99
141
  private readonly users: readonly number[];
100
142
  private readonly bot: string;
143
+ /** Chats that changed recently, newest last; dedupe reads only these and the open chat. */
144
+ private readonly recent = new Set<string>();
101
145
 
102
146
  constructor(ctx: SourceContext, options: TelegramSourceOptions) {
103
147
  this.ctx = ctx;
@@ -107,6 +151,8 @@ export class TelegramSource {
107
151
  this.pollIntervalMs = options.pollIntervalMs ?? 1_000;
108
152
  this.wait = options.wait ?? delay;
109
153
  this.pending = options.pending;
154
+ this.commands = options.commands;
155
+ this.typing = options.typing;
110
156
  const settings = telegramSettings(ctx.settings);
111
157
  this.users = settings.users;
112
158
  this.bot = settings.bot;
@@ -145,14 +191,19 @@ export class TelegramSource {
145
191
  let stopped = false;
146
192
  const loop = async (): Promise<void> => {
147
193
  while (!stopped && !this.controller.signal.aborted) {
194
+ let failed = false;
148
195
  try {
149
196
  await this.poll();
150
197
  } catch (error) {
151
198
  if (stopped || this.controller.signal.aborted) return;
199
+ failed = true;
152
200
  await this.ctx.logger.write(`could not read updates: ${messageOf(error)}`);
153
201
  }
154
202
  if (stopped || this.controller.signal.aborted) return;
155
- await this.wait(this.pollIntervalMs, this.controller.signal);
203
+ // getUpdates already holds the request open when there is nothing new,
204
+ // so a poll that came back is followed at once. Only a failed poll
205
+ // waits, so a broken connection cannot spin.
206
+ if (failed) await this.wait(this.pollIntervalMs, this.controller.signal);
156
207
  }
157
208
  };
158
209
  void loop();
@@ -164,11 +215,28 @@ export class TelegramSource {
164
215
  };
165
216
  }
166
217
 
218
+ /** A chat changed; keep it for the short dedupe list a resent update may need. */
219
+ changed(chatId: string): void {
220
+ this.remember(chatId);
221
+ }
222
+
223
+ private remember(chatId: string): void {
224
+ this.recent.delete(chatId);
225
+ this.recent.add(chatId);
226
+ while (this.recent.size > RECENT_CHATS_MAX) {
227
+ const oldest = this.recent.values().next().value;
228
+ if (oldest === undefined) return;
229
+ this.recent.delete(oldest);
230
+ }
231
+ }
232
+
167
233
  private async handle(update: TelegramUpdate): Promise<void> {
168
234
  const key = String(update.update_id);
169
235
  if (update.callback_query !== undefined) {
170
- // A tap is handled by the pending side; either way it is recorded once.
236
+ // A tap is handled by the pending side or the command side; either way
237
+ // it is recorded once.
171
238
  await this.pending?.handleCallback(update.callback_query);
239
+ await this.commands?.handleCallback(update.callback_query);
172
240
  await this.record(key);
173
241
  return;
174
242
  }
@@ -180,10 +248,20 @@ export class TelegramSource {
180
248
  const summary = summaryOf(message);
181
249
  const from = message.from?.id;
182
250
  const listed = from !== undefined && this.users.includes(from);
183
- const text = messageText(message);
251
+ const raw = messageText(message);
184
252
  // A group, a channel, an unlisted sender or a message with no text is
185
- // recorded and stops there: no chat, no reply, nothing started.
186
- if (message.chat.type !== "private" || !listed || text === undefined) {
253
+ // recorded and stops there: no chat, no reply, nothing started. A command
254
+ // from anyone else is dropped the same way, without a reply.
255
+ if (message.chat.type !== "private" || !listed || raw === undefined) {
256
+ await this.record(key, undefined, summary);
257
+ return;
258
+ }
259
+ // `/model@operad_bot sonnet` is `/model sonnet`.
260
+ const text = stripBotName(raw);
261
+
262
+ // Telegram's own `/start` is a greeting that points at `/help`; it never
263
+ // starts a reply and never needs a chat.
264
+ if (this.commands !== undefined && (await this.commands.greet(text, message.chat.id))) {
187
265
  await this.record(key, undefined, summary);
188
266
  return;
189
267
  }
@@ -197,7 +275,10 @@ export class TelegramSource {
197
275
 
198
276
  const channel = telegramChannel(message.chat.id);
199
277
  const bound = await this.boundChats(channel);
278
+ // Dedupe against the open chat and the chats that changed recently, not
279
+ // every chat this Telegram chat was ever bound to.
200
280
  for (const chat of bound) {
281
+ if (chat.closed && !this.recent.has(chat.id)) continue;
201
282
  const previous = this.messageFrom(chat.id, key);
202
283
  if (previous === undefined) continue;
203
284
  // The message is already written; recording the event sendMessage uses
@@ -210,17 +291,76 @@ export class TelegramSource {
210
291
  object: `chat:${previous.chatId}`,
211
292
  });
212
293
  }
294
+ this.remember(previous.chatId);
213
295
  await this.record(key, previous.chatId, summary);
214
296
  return;
215
297
  }
216
298
 
217
299
  const open = bound.find((chat) => !chat.closed);
218
- const chatId = open?.id ?? (await this.openBoundChat(channel, text, from));
219
- await this.ctx.client.act("chat:send", chatId, {
220
- args: { note: text, ref: key },
221
- actor: { via: TELEGRAM_SOURCE, id: String(from) },
222
- });
300
+ const parsed = parseCommand(text);
301
+ // A chat opened by a command is not titled by the command's text.
302
+ const title = parsed === undefined ? text : undefined;
303
+ const chatId = open?.id ?? (await this.openBoundChat(channel, title, from));
304
+ this.remember(chatId);
305
+ const command =
306
+ parsed === undefined || this.commands === undefined
307
+ ? undefined
308
+ : await this.commands.command(chatId, parsed.name);
309
+ // A command that takes one choice and was sent without it answers with
310
+ // its choices instead of running; a tap runs it as `/<name> <choice>`.
311
+ if (
312
+ command !== undefined &&
313
+ this.commands !== undefined &&
314
+ (await this.commands.offer(command, text, chatId, message.chat.id))
315
+ ) {
316
+ await this.record(key, chatId, summary);
317
+ await this.commands.refresh(chatId);
318
+ return;
319
+ }
320
+ // `/pending` holds the pending pass until its count line; a line that could
321
+ // not be sent still lets the items it prepared go.
322
+ const pendingCommand =
323
+ command !== undefined && command.info.action === PENDING_COMMAND && command.info.plugin === TELEGRAM_SOURCE;
324
+ try {
325
+ // The chat's type is known here; another type may hold the same bare id.
326
+ const result = await this.ctx.client.act("chat:send", `chat:${chatId}`, {
327
+ args: { note: text, ref: key },
328
+ actor: { via: TELEGRAM_SOURCE, id: String(from) },
329
+ });
330
+ // An ordinary message is acknowledged at once, before its run is reported.
331
+ // A command's outcome is its answer, so it gets neither a reaction nor typing.
332
+ if (command === undefined) {
333
+ this.typing?.received(chatId, message.chat.id);
334
+ await this.react(message);
335
+ }
336
+ // What a command returned is the answer the person who typed it sees; an
337
+ // ordinary message's "sent ..." is not sent back.
338
+ if (command !== undefined) {
339
+ const outcome = typeof result.value === "string" && result.value.trim().length > 0 ? result.value : "done";
340
+ await this.commands?.say(message.chat.id, outcome);
341
+ }
342
+ } finally {
343
+ // `/pending` sends its count as a command's answer, then the items it prepared.
344
+ if (pendingCommand) await this.pending?.show(message.chat.id);
345
+ }
223
346
  await this.record(key, chatId, summary);
347
+ if (command !== undefined || open === undefined) await this.commands?.refresh(chatId);
348
+ }
349
+
350
+ /** Marks an accepted message as received; a refusal is logged once and changes nothing else. */
351
+ private async react(message: TelegramMessage): Promise<void> {
352
+ try {
353
+ await this.api.setMessageReaction({
354
+ chatId: message.chat.id,
355
+ messageId: message.message_id,
356
+ reaction: RECEIVED_REACTION,
357
+ signal: this.controller.signal,
358
+ });
359
+ } catch (error) {
360
+ await this.ctx.logger.write(
361
+ `could not react to message ${message.message_id}: ${messageOf(error)}`,
362
+ );
363
+ }
224
364
  }
225
365
 
226
366
  private async record(key: string, chatId?: string, summary?: string): Promise<void> {
@@ -235,20 +375,8 @@ export class TelegramSource {
235
375
  }
236
376
 
237
377
  /** Every chat bound to this channel, newest first. */
238
- private async boundChats(channel: string): Promise<readonly BoundChat[]> {
239
- const found: BoundChat[] = [];
240
- let cursor: string | undefined;
241
- do {
242
- const page = await this.ctx.store.list(CHAT_TYPE, {
243
- ...(cursor === undefined ? {} : { cursor }),
244
- });
245
- for (const object of page.objects) {
246
- const data = chatData(object.data);
247
- if (data.channels.includes(channel)) found.push({ id: object.id, closed: data.closed });
248
- }
249
- cursor = page.next;
250
- } while (cursor !== undefined);
251
- return found.sort((left, right) => right.id.localeCompare(left.id));
378
+ private boundChats(channel: string): Promise<readonly BoundChat[]> {
379
+ return boundChats(this.ctx, channel);
252
380
  }
253
381
 
254
382
  /** The message already written for this update on a chat, if any. */
@@ -262,9 +390,13 @@ export class TelegramSource {
262
390
  return found === undefined ? undefined : { id: found.id, chatId };
263
391
  }
264
392
 
265
- private async openBoundChat(channel: string, text: string, userId: number): Promise<string> {
266
- const opened = await this.ctx.client.act("bot:chat", this.bot, {
267
- args: { title: titleFromMessage(text) ?? "Telegram", channels: [channel] },
393
+ private async openBoundChat(channel: string, text: string | undefined, userId: number): Promise<string> {
394
+ // A typed id: another plugin's type may hold an object under the same bare
395
+ // id (the bot plugin's nightly tidy keeps one per bot), and a bare id is
396
+ // then ambiguous.
397
+ const botName = this.bot.startsWith("bot:") ? this.bot.slice("bot:".length) : this.bot;
398
+ const opened = await this.ctx.client.act("bot:chat", `bot:${botName}`, {
399
+ args: { title: (text === undefined ? undefined : titleFromMessage(text)) ?? "Telegram", channels: [channel] },
268
400
  actor: { via: TELEGRAM_SOURCE, id: String(userId) },
269
401
  });
270
402
  if (opened.opens === undefined || !opened.opens.startsWith("chat:")) {