@operad-io/telegram 0.1.0 → 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.
@@ -0,0 +1,494 @@
1
+ /**
2
+ * The progress side of the Telegram plugin: while a reply runs, one message is
3
+ * edited to the unfinished part of the chat's transcript, the text being
4
+ * written and the tool calls in progress.
5
+ *
6
+ * The plugin's one event loop hands it a stored chat change, or the live
7
+ * `transcript` tail itself. A tail carries the whole text and status, so it is
8
+ * shown without reading the section again; the throttle is checked before any
9
+ * read, so a tail inside the two-second window costs nothing. The first status
10
+ * or tail creates the message. Edits happen at most once every two seconds per
11
+ * chat and only when the reduced Markdown changed. When the reply is recorded,
12
+ * the reply side sends the final reply as new message(s) first and this side
13
+ * deletes the progress message. A failed edit is only logged; it never stops
14
+ * the final reply. What is remembered in `<home>/telegram/` is the message id,
15
+ * so a restart can delete a message a killed serve left behind.
16
+ */
17
+
18
+ import { CHAT_TYPE, TRANSCRIPT, allEntries, allMessages, chatData } from "@operad-io/chat";
19
+ import { messageOf, type SourceContext } from "@operad-io/engine";
20
+ import { BotApiError, type BotApi } from "./api.ts";
21
+ import { TelegramEvents, type TelegramEvent } from "./events.ts";
22
+ import { progressStatusLine, telegramProgress, type TelegramChunk } from "./format.ts";
23
+ import { telegramChatsOf } from "./replies.ts";
24
+ import { delay } from "./source.ts";
25
+ import { readProgress, writeProgress, type ProgressRecord, type ProgressState } from "./state.ts";
26
+
27
+ /** How often one chat's progress message may be edited. */
28
+ export const PROGRESS_INTERVAL_MS = 2_000;
29
+
30
+ /** What finishes a reply: the reply side sends the final messages before the progress message goes. */
31
+ export interface ReplySweeper {
32
+ sweepChat(chatId: string): Promise<void>;
33
+ }
34
+
35
+ export interface ProgressSenderOptions {
36
+ readonly api: BotApi;
37
+ readonly replies?: ReplySweeper | undefined;
38
+ readonly clock?: (() => number) | undefined;
39
+ readonly intervalMs?: number | undefined;
40
+ /** Waits `ms` unless `signal` aborts first; a test gives one it moves itself. */
41
+ readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
42
+ }
43
+
44
+ /** One chat's progress message and when it may next be changed. */
45
+ interface ChatProgress {
46
+ /** The Telegram chat this bound chat writes to. */
47
+ readonly target: number;
48
+ messageId: number | undefined;
49
+ /** The reduced Markdown last taken by Telegram, so an unchanged text is not edited. */
50
+ text: string | undefined;
51
+ nextAt: number;
52
+ dirty: boolean;
53
+ /** A manual check reads the section even before a message exists. */
54
+ probe: boolean;
55
+ /** The newest live tail waiting for this chat, already carrying its whole text. */
56
+ live: TelegramEvent | undefined;
57
+ timer: AbortController | undefined;
58
+ }
59
+
60
+ /** Whether the last person's message already has a reply or a failure line after it. */
61
+ function answered(messages: readonly { readonly role: string; readonly sequence: number }[], entries: readonly { readonly kind: string; readonly sequence: number }[]): boolean {
62
+ let lastUser = 0;
63
+ for (const message of messages) {
64
+ if (message.role === "user") lastUser = Math.max(lastUser, message.sequence);
65
+ }
66
+ if (messages.some((message) => message.role === "assistant" && message.sequence > lastUser)) return true;
67
+ return entries.some((entry) => entry.kind === "failure" && entry.sequence > lastUser);
68
+ }
69
+
70
+ export class ProgressSender {
71
+ private readonly ctx: SourceContext;
72
+ private readonly api: BotApi;
73
+ private readonly replies: ReplySweeper | undefined;
74
+ private readonly clock: () => number;
75
+ private readonly intervalMs: number;
76
+ private readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
77
+ private readonly controller = new AbortController();
78
+ private readonly chats = new Map<string, ChatProgress>();
79
+ private readonly working = new Map<string, Promise<void>>();
80
+ private readonly marks = new Map<string, string>();
81
+ /** Live tails that arrived before their chat was known to be bound. */
82
+ private readonly pendingLive = new Map<string, TelegramEvent>();
83
+ /** Chats a manual check must bind even without a live event. */
84
+ private readonly probes = new Set<string>();
85
+ /** Chats already found not bound to Telegram, so their tails do not read again. */
86
+ private readonly unbound = new Set<string>();
87
+ private state: ProgressState;
88
+ private stopped = false;
89
+ private following: { readonly stop: () => Promise<void> } | undefined;
90
+ private watching: Promise<void> = Promise.resolve();
91
+
92
+ constructor(ctx: SourceContext, options: ProgressSenderOptions) {
93
+ this.ctx = ctx;
94
+ this.api = options.api;
95
+ this.replies = options.replies;
96
+ this.clock = options.clock ?? ctx.clock;
97
+ this.intervalMs = options.intervalMs ?? PROGRESS_INTERVAL_MS;
98
+ this.wait = options.wait ?? delay;
99
+ this.state = readProgress(ctx.home);
100
+ if (ctx.signal.aborted) this.controller.abort();
101
+ else ctx.signal.addEventListener("abort", () => this.controller.abort(), { once: true });
102
+ }
103
+
104
+ /** Deletes a message a killed serve left behind, then follows changes, alone or through the plugin's one loop. */
105
+ start(events?: TelegramEvents): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
106
+ const local = events === undefined ? new TelegramEvents(this.ctx, { wait: this.wait }) : undefined;
107
+ const initial = this.cleanLeftovers().catch((error: unknown) =>
108
+ this.log(`could not clean a progress message: ${messageOf(error)}`),
109
+ );
110
+ this.watching = (async () => {
111
+ await initial;
112
+ if (this.stopped) return;
113
+ this.following = local?.start({
114
+ progress: (event) => this.handleEvent(event),
115
+ });
116
+ })();
117
+ return {
118
+ ready: initial,
119
+ stop: async () => {
120
+ this.stopped = true;
121
+ this.controller.abort();
122
+ for (const chat of this.chats.values()) this.cancelTimer(chat);
123
+ await this.following?.stop();
124
+ await this.watching.catch(() => undefined);
125
+ await Promise.all([...this.working.values()]);
126
+ },
127
+ };
128
+ }
129
+
130
+ /** One event from the plugin's one loop: a live tail, or a stored chat change. */
131
+ handleEvent(event: TelegramEvent): void {
132
+ if (event.id.length === 0) return;
133
+ const chat = this.chats.get(event.id);
134
+ if (event.section !== undefined) {
135
+ const tail = event.tail;
136
+ // An empty tail with no status and no message to finish has nothing to show.
137
+ if (chat === undefined && (tail === undefined || tail.trim().length === 0) && event.status === undefined) return;
138
+ void this.wake(event.id, event, false);
139
+ return;
140
+ }
141
+ // A stored change matters only while a progress message is on the chat. A
142
+ // chat that changed may now be bound, so its earlier "not bound" is stale.
143
+ this.unbound.delete(event.id);
144
+ if (chat?.messageId === undefined) return;
145
+ void this.wake(event.id, event, false);
146
+ }
147
+
148
+ /** Checks one chat now, as a manual read does; resolves when this check is over. */
149
+ syncChat(chatId: string): Promise<void> {
150
+ return this.wake(chatId, undefined, true);
151
+ }
152
+
153
+ /** Waits for the checks asked so far. */
154
+ async settled(): Promise<void> {
155
+ await Promise.resolve();
156
+ while (this.working.size > 0) {
157
+ await Promise.all([...this.working.values()].map((work) => work.catch(() => undefined)));
158
+ }
159
+ }
160
+
161
+ /** Deletes every recorded progress message; one Telegram refuses stays for the next start. */
162
+ private async cleanLeftovers(): Promise<void> {
163
+ const left: Record<string, ProgressRecord> = {};
164
+ for (const [chatId, record] of Object.entries(this.state)) {
165
+ if (this.stopped) return;
166
+ try {
167
+ await this.api.deleteMessage({
168
+ chatId: record.target,
169
+ messageId: record.messageId,
170
+ signal: this.controller.signal,
171
+ });
172
+ } catch (error) {
173
+ if (this.stopped) return;
174
+ left[chatId] = record;
175
+ await this.log(`could not delete a progress message in chat ${chatId}: ${messageOf(error)}`);
176
+ }
177
+ }
178
+ this.state = left;
179
+ writeProgress(this.ctx.home, this.state);
180
+ }
181
+
182
+ /** Creates a chat's state only once its binding, and so its Telegram chat, is known. */
183
+ private chatOf(chatId: string, target: number): ChatProgress {
184
+ const existing = this.chats.get(chatId);
185
+ if (existing !== undefined) return existing;
186
+ const created: ChatProgress = {
187
+ target,
188
+ messageId: undefined,
189
+ text: undefined,
190
+ nextAt: 0,
191
+ dirty: false,
192
+ probe: false,
193
+ live: undefined,
194
+ timer: undefined,
195
+ };
196
+ this.chats.set(chatId, created);
197
+ return created;
198
+ }
199
+
200
+ private wake(chatId: string, event: TelegramEvent | undefined, manual: boolean): Promise<void> {
201
+ if (this.stopped) return Promise.resolve();
202
+ const existing = this.chats.get(chatId);
203
+ if (existing !== undefined) {
204
+ this.request(chatId, existing, event, manual);
205
+ return this.working.get(chatId) ?? Promise.resolve();
206
+ }
207
+ if (manual) this.unbound.delete(chatId);
208
+ if (event?.section !== undefined && this.unbound.has(chatId)) return Promise.resolve();
209
+ if (event?.section !== undefined) this.pendingLive.set(chatId, event);
210
+ else if (manual) this.probes.add(chatId);
211
+ else return Promise.resolve();
212
+ const work = this.working.get(chatId);
213
+ if (work !== undefined) return work;
214
+ const run = this.bindAndPump(chatId)
215
+ .catch((error: unknown) => this.log(`could not show progress: ${messageOf(error)}`))
216
+ .finally(() => {
217
+ if (this.working.get(chatId) === run) this.working.delete(chatId);
218
+ const chat = this.chats.get(chatId);
219
+ if (chat?.dirty === true && !this.stopped) this.pump(chatId);
220
+ });
221
+ this.working.set(chatId, run);
222
+ return run;
223
+ }
224
+
225
+ private async bindAndPump(chatId: string): Promise<void> {
226
+ const stored = await this.ctx.store.get(CHAT_TYPE, chatId);
227
+ if (this.stopped) return;
228
+ const target = stored === undefined ? undefined : telegramChatsOf(chatData(stored.data).channels)[0];
229
+ if (target === undefined) {
230
+ this.unbound.add(chatId);
231
+ this.pendingLive.delete(chatId);
232
+ this.probes.delete(chatId);
233
+ return;
234
+ }
235
+ this.unbound.delete(chatId);
236
+ const live = this.pendingLive.get(chatId);
237
+ this.pendingLive.delete(chatId);
238
+ const probe = this.probes.delete(chatId);
239
+ if (live === undefined && !probe) return;
240
+ const chat = this.chatOf(chatId, target);
241
+ if (live !== undefined) chat.live = live;
242
+ chat.probe = probe;
243
+ chat.dirty = true;
244
+ await this.loop(chatId, chat);
245
+ }
246
+
247
+ private request(chatId: string, chat: ChatProgress, event: TelegramEvent | undefined, manual: boolean): void {
248
+ if (this.stopped) return;
249
+ chat.live = event?.section === undefined ? undefined : event;
250
+ if (manual) chat.probe = true;
251
+ chat.dirty = true;
252
+ this.cancelTimer(chat);
253
+ this.pump(chatId);
254
+ }
255
+
256
+ private pump(chatId: string): void {
257
+ if (this.stopped || this.working.has(chatId)) return;
258
+ const run = this.loopFor(chatId)
259
+ .catch((error: unknown) => this.log(`could not show progress: ${messageOf(error)}`))
260
+ .finally(() => {
261
+ if (this.working.get(chatId) === run) this.working.delete(chatId);
262
+ const chat = this.chats.get(chatId);
263
+ if (chat?.dirty === true && !this.stopped) this.pump(chatId);
264
+ });
265
+ this.working.set(chatId, run);
266
+ }
267
+
268
+ private async loopFor(chatId: string): Promise<void> {
269
+ const chat = this.chats.get(chatId);
270
+ if (chat === undefined) return;
271
+ await this.loop(chatId, chat);
272
+ }
273
+
274
+ private async loop(chatId: string, chat: ChatProgress): Promise<void> {
275
+ while (!this.stopped && chat.dirty) {
276
+ chat.dirty = false;
277
+ const live = chat.live;
278
+ chat.live = undefined;
279
+ await this.step(chatId, chat, live);
280
+ }
281
+ }
282
+
283
+ private async step(chatId: string, chat: ChatProgress, live: TelegramEvent | undefined): Promise<void> {
284
+ if (this.stopped) return;
285
+ const now = this.clock();
286
+ // The throttle comes before every read: a tail inside the window is not even
287
+ // looked at, and the next wake reads the section's whole current tail.
288
+ if (chat.messageId !== undefined && now < chat.nextAt) {
289
+ this.schedule(chatId, chat, chat.nextAt - now);
290
+ return;
291
+ }
292
+ if (live?.section !== undefined) {
293
+ const tail = live.tail;
294
+ const status = live.status;
295
+ const statusLine = status === undefined ? undefined : progressStatusLine(status, now);
296
+ if ((tail === undefined || tail.trim().length === 0) && statusLine === undefined) {
297
+ if (chat.messageId !== undefined) {
298
+ // A cancelled run may send no event at all: look again while it says
299
+ // the run still goes on, and delete the message once it has ended.
300
+ if (await this.running(chatId)) this.later(chatId, chat);
301
+ else await this.finish(chatId, chat, false);
302
+ }
303
+ return;
304
+ }
305
+ const chunk = telegramProgress(tail ?? "", statusLine);
306
+ if (chunk === undefined) {
307
+ this.later(chatId, chat);
308
+ return;
309
+ }
310
+ if (chat.messageId !== undefined && chat.text === chunk.html) {
311
+ this.later(chatId, chat);
312
+ return;
313
+ }
314
+ await this.apply(chatId, chat, chunk);
315
+ this.later(chatId, chat);
316
+ return;
317
+ }
318
+
319
+ const probe = chat.probe;
320
+ chat.probe = false;
321
+ if (chat.messageId === undefined && !probe) return;
322
+
323
+ const messages = allMessages(this.ctx.store, chatId);
324
+ const entries = allEntries(this.ctx.store, chatId);
325
+ if (chat.messageId !== undefined && answered(messages, entries)) {
326
+ await this.finish(chatId, chat, true);
327
+ return;
328
+ }
329
+
330
+ const mark = this.marks.get(chatId);
331
+ const section = await this.ctx.client.section(`chat:${chatId}`, TRANSCRIPT, undefined, {
332
+ ...(mark === undefined ? {} : { after: mark }),
333
+ });
334
+ if (section.mark !== undefined) this.marks.set(chatId, section.mark);
335
+ const tail = section.tail;
336
+ const status = section.status;
337
+ const statusLine = status === undefined ? undefined : progressStatusLine(status, this.clock());
338
+ if ((tail === undefined || tail.trim().length === 0) && statusLine === undefined) {
339
+ if (chat.messageId !== undefined) {
340
+ // A cancelled run may send no event at all: look again while it says
341
+ // the run still goes on, and delete the message once it has ended.
342
+ if (await this.running(chatId)) this.later(chatId, chat);
343
+ else await this.finish(chatId, chat, false);
344
+ }
345
+ return;
346
+ }
347
+ const chunk = telegramProgress(tail ?? "", statusLine);
348
+ if (chunk === undefined) {
349
+ this.later(chatId, chat);
350
+ return;
351
+ }
352
+ if (chat.messageId !== undefined && chat.text === chunk.html) {
353
+ this.later(chatId, chat);
354
+ return;
355
+ }
356
+ await this.apply(chatId, chat, chunk);
357
+ this.later(chatId, chat);
358
+ }
359
+
360
+ /** Looks again after the interval while a progress message is on the chat. */
361
+ private later(chatId: string, chat: ChatProgress): void {
362
+ if (chat.messageId === undefined) return;
363
+ this.schedule(chatId, chat, this.intervalMs);
364
+ }
365
+
366
+ /** Whether the client still says a run works on the chat. */
367
+ private async running(chatId: string): Promise<boolean> {
368
+ try {
369
+ const view = await this.ctx.client.get(`chat:${chatId}`);
370
+ return view.row.running === true;
371
+ } catch {
372
+ return false;
373
+ }
374
+ }
375
+
376
+ private schedule(chatId: string, chat: ChatProgress, ms: number): void {
377
+ if (chat.timer !== undefined || this.stopped) return;
378
+ const timer = new AbortController();
379
+ chat.timer = timer;
380
+ void this.wait(Math.max(0, ms), timer.signal).then(
381
+ () => {
382
+ // A canceled timer is not a wake: its chat was already pumped or stopped.
383
+ if (chat.timer !== timer) return;
384
+ chat.timer = undefined;
385
+ if (this.stopped) return;
386
+ chat.dirty = true;
387
+ this.pump(chatId);
388
+ },
389
+ () => {
390
+ if (chat.timer === timer) chat.timer = undefined;
391
+ },
392
+ );
393
+ }
394
+
395
+ private cancelTimer(chat: ChatProgress): void {
396
+ const timer = chat.timer;
397
+ if (timer === undefined) return;
398
+ chat.timer = undefined;
399
+ timer.abort();
400
+ }
401
+
402
+ /** Sends the first progress message or edits the one that is there. */
403
+ private async apply(chatId: string, chat: ChatProgress, chunk: TelegramChunk): Promise<void> {
404
+ const target = chat.target;
405
+ chat.nextAt = this.clock() + this.intervalMs;
406
+ let plain = false;
407
+ let creating = chat.messageId === undefined;
408
+ for (let attempt = 1; !this.stopped; ) {
409
+ try {
410
+ if (creating) {
411
+ chat.messageId = await this.api.sendMessage({
412
+ chatId: target,
413
+ text: plain ? chunk.plain : chunk.html,
414
+ ...(plain ? {} : { parseMode: "HTML" as const }),
415
+ signal: this.controller.signal,
416
+ });
417
+ creating = false;
418
+ } else {
419
+ const messageId = chat.messageId;
420
+ if (messageId === undefined) return;
421
+ await this.api.editMessage({
422
+ chatId: target,
423
+ messageId,
424
+ text: plain ? chunk.plain : chunk.html,
425
+ ...(plain ? {} : { parseMode: "HTML" as const }),
426
+ signal: this.controller.signal,
427
+ });
428
+ }
429
+ const messageId = chat.messageId;
430
+ if (messageId === undefined) return;
431
+ chat.text = chunk.html;
432
+ this.remember(chatId, { target, messageId, text: chunk.html });
433
+ return;
434
+ } catch (error) {
435
+ if (this.stopped) return;
436
+ if (error instanceof BotApiError && error.badMarkup && !plain) {
437
+ plain = true;
438
+ attempt -= 1;
439
+ continue;
440
+ }
441
+ const asked = error instanceof BotApiError && error.retryAfterSecs !== undefined ? error.retryAfterSecs * 1_000 : 0;
442
+ if (asked > 0 && attempt < 3) {
443
+ const wait = Math.max(asked, chat.nextAt - this.clock());
444
+ await this.wait(wait, this.controller.signal);
445
+ chat.nextAt = this.clock() + this.intervalMs;
446
+ attempt += 1;
447
+ continue;
448
+ }
449
+ await this.log(`could not show progress in chat ${chatId}: ${messageOf(error)}`);
450
+ return;
451
+ }
452
+ }
453
+ }
454
+
455
+ /** Sends the final reply first, then removes the progress message. */
456
+ private async finish(chatId: string, chat: ChatProgress, final: boolean): Promise<void> {
457
+ const messageId = chat.messageId;
458
+ const target = chat.target;
459
+ if (messageId === undefined || target === undefined) return;
460
+ if (final && this.replies !== undefined) {
461
+ try {
462
+ await this.replies.sweepChat(chatId);
463
+ } catch (error) {
464
+ if (!this.stopped) await this.log(`could not send the final reply of chat ${chatId}: ${messageOf(error)}`);
465
+ }
466
+ }
467
+ try {
468
+ await this.api.deleteMessage({ chatId: target, messageId, signal: this.controller.signal });
469
+ } catch (error) {
470
+ if (this.stopped) return;
471
+ await this.log(`could not delete the progress message of chat ${chatId}: ${messageOf(error)}`);
472
+ return;
473
+ }
474
+ chat.messageId = undefined;
475
+ chat.text = undefined;
476
+ this.forget(chatId);
477
+ }
478
+
479
+ private remember(chatId: string, record: ProgressRecord): void {
480
+ this.state = { ...this.state, [chatId]: record };
481
+ writeProgress(this.ctx.home, this.state);
482
+ }
483
+
484
+ /** Forgets a chat's record after its message is deleted. */
485
+ private forget(chatId: string): void {
486
+ const { [chatId]: _gone, ...rest } = this.state;
487
+ this.state = rest;
488
+ writeProgress(this.ctx.home, this.state);
489
+ }
490
+
491
+ private async log(message: string): Promise<void> {
492
+ await this.ctx.logger.write(message);
493
+ }
494
+ }