omp-superagent 0.0.0-stage → 0.1.2

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.
Files changed (97) hide show
  1. package/DESIGN.md +1502 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +198 -0
  4. package/README.md +224 -2
  5. package/THIRD_PARTY_NOTICES.md +388 -0
  6. package/assets/architecture.mmd +24 -0
  7. package/assets/architecture.svg +126 -0
  8. package/assets/superagent-avatar.jpg +0 -0
  9. package/assets/superagent-mascot.webp +0 -0
  10. package/config.example.json +26 -0
  11. package/docs/OPERATIONS.md +1178 -0
  12. package/docs/discord-voice.md +96 -0
  13. package/docs/releases/0.1.0.md +222 -0
  14. package/docs/releases/0.1.1.md +60 -0
  15. package/docs/releases/0.1.2.md +53 -0
  16. package/package.json +65 -4
  17. package/scripts/ci.ts +33 -0
  18. package/scripts/prepare-ulw.ts +18 -0
  19. package/scripts/release.ts +58 -0
  20. package/scripts/setup.sh +25 -0
  21. package/scripts/test-omp.sh +36 -0
  22. package/skills/head/SKILL.md +100 -0
  23. package/skills/head/references/model-selection.md +83 -0
  24. package/skills/head/references/routing.md +181 -0
  25. package/skills/head/references/supervision.md +122 -0
  26. package/skills/lane/SKILL.md +66 -0
  27. package/skills/lane/references/workflow.md +95 -0
  28. package/src/autostart.ts +295 -0
  29. package/src/board-extension.ts +217 -0
  30. package/src/board.ts +396 -0
  31. package/src/cli.ts +253 -0
  32. package/src/codex-live-bridge.py +73 -0
  33. package/src/codex-live.ts +244 -0
  34. package/src/codex-voice-requirements.txt +5 -0
  35. package/src/codex_live_auth.py +192 -0
  36. package/src/codex_live_media.py +219 -0
  37. package/src/codex_live_provider.py +192 -0
  38. package/src/config.ts +266 -0
  39. package/src/contracts.ts +381 -0
  40. package/src/credentials.ts +172 -0
  41. package/src/decision-tool.ts +59 -0
  42. package/src/decisions.ts +143 -0
  43. package/src/delivery.ts +17 -0
  44. package/src/dialog.ts +73 -0
  45. package/src/discord-command-registration.ts +201 -0
  46. package/src/discord-commands.ts +29 -0
  47. package/src/discord-context.ts +118 -0
  48. package/src/discord-markdown.ts +172 -0
  49. package/src/discord-voice-draft.ts +124 -0
  50. package/src/discord-voice-link.ts +270 -0
  51. package/src/discord-voice.ts +150 -0
  52. package/src/discord.ts +1012 -0
  53. package/src/extension.ts +446 -0
  54. package/src/gateway-client.ts +229 -0
  55. package/src/gateway-protocol.ts +85 -0
  56. package/src/gateway-restart.ts +151 -0
  57. package/src/gateway-server.ts +440 -0
  58. package/src/gateway-store.ts +251 -0
  59. package/src/gateway.ts +654 -0
  60. package/src/head-recovery.ts +61 -0
  61. package/src/host-broker-services.ts +108 -0
  62. package/src/host-extension.ts +561 -0
  63. package/src/host-owner.ts +366 -0
  64. package/src/host-protocol.ts +144 -0
  65. package/src/host-services.ts +54 -0
  66. package/src/host.ts +415 -0
  67. package/src/installed-omp.ts +71 -0
  68. package/src/lane-extension.ts +184 -0
  69. package/src/lane-models.ts +75 -0
  70. package/src/lane-report.ts +70 -0
  71. package/src/lane-rows.ts +12 -0
  72. package/src/managed-ulw-probe.ts +172 -0
  73. package/src/managed-ulw.ts +471 -0
  74. package/src/message-order.ts +21 -0
  75. package/src/messenger-commands.ts +16 -0
  76. package/src/messengers.ts +143 -0
  77. package/src/native-presets.ts +370 -0
  78. package/src/native-sessions.ts +32 -0
  79. package/src/native-settings.ts +131 -0
  80. package/src/openai-live.ts +377 -0
  81. package/src/pr-github-schema.ts +110 -0
  82. package/src/pr-github.ts +170 -0
  83. package/src/pr-watch.ts +200 -0
  84. package/src/repository.ts +12 -0
  85. package/src/runtime.ts +4229 -0
  86. package/src/setup-judge.ts +34 -0
  87. package/src/setup-memory.ts +39 -0
  88. package/src/setup-profiles.ts +84 -0
  89. package/src/setup.ts +300 -0
  90. package/src/slack-command-registration.ts +217 -0
  91. package/src/slack-commands.ts +18 -0
  92. package/src/slack.ts +779 -0
  93. package/src/store.ts +862 -0
  94. package/src/telegram-command-registration.ts +155 -0
  95. package/src/telegram.ts +677 -0
  96. package/src/workflow.ts +94 -0
  97. package/upstream/ulw.json +9 -0
@@ -0,0 +1,677 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { Api, InputFile } from "grammy";
4
+ import { AbortController as ApiAbortController, type AbortSignal as ApiAbortSignal } from "abort-controller";
5
+ import type { CallbackQuery, Chat, InlineKeyboardButton, InlineKeyboardMarkup, Message, Update, UserFromGetMe } from "grammy/types";
6
+ import { physicalRouteKey, type Approval, type Attachment, type DialogResponse, type Inbound, type MessageActivity, type MessageReference, type Messenger, type OutputRecord, type ReplyContext, type Route, type StorePort } from "./contracts.ts";
7
+ import { parseDialog, type Dialog } from "./dialog.ts";
8
+ import { validateDecisionAnswer, validateDecisionResponse } from "./decisions";
9
+ import { approvalCardToken, DeliveryError } from "./delivery.ts";
10
+ import { MESSENGER_COMMANDS } from "./messenger-commands.ts";
11
+
12
+ // grammY Api has no retry transformer installed. Only getUpdates is retried.
13
+ // Bot API: https://core.telegram.org/bots/api#getupdates (24-hour retention),
14
+ // #sendmessage (4096 characters), #getfile (20 MB), #inlinekeyboardbutton
15
+ // (64-byte callback_data), #createforumtopic, and #editmessagetext.
16
+ const TEXT_LIMIT = 4096;
17
+ const UPLOAD_LIMIT = 50 * 1024 * 1024;
18
+ const DOWNLOAD_LIMIT = 20 * 1024 * 1024;
19
+ // getUpdates retains updates for at most 24 hours. An old offset is therefore
20
+ // unnecessary after that idle interval; dropping it also safely precedes the
21
+ // documented random update_id reset after at least a week without updates.
22
+ const CURSOR_IDLE_MS = 24 * 60 * 60 * 1000;
23
+ const COMMAND_NAMES = new Set<string>(MESSENGER_COMMANDS.map(command => command.name));
24
+ type Handlers = Parameters<Messenger["start"]>[0];
25
+ type Answer = NonNullable<DialogResponse["answers"]>[number];
26
+ interface Progress {
27
+ messageId: string | null;
28
+ attempted: boolean;
29
+ active: boolean;
30
+ question: number;
31
+ answers: Answer[];
32
+ selected: string[];
33
+ customInput?: string;
34
+ lastUpdate?: string;
35
+ /** A final answer was attempted; only durable queue readback proves admission. */
36
+ answerRequest?: string;
37
+ }
38
+ interface Pending extends Progress {
39
+ approval: Approval;
40
+ token: string;
41
+ dialog: Dialog;
42
+ stamp: string;
43
+ busy: boolean;
44
+ verified: boolean;
45
+ }
46
+ interface CardView { text: string; reply_markup: InlineKeyboardMarkup }
47
+
48
+ export interface TelegramMessengerOptions {
49
+ token: string;
50
+ ownerId: string;
51
+ allowedChatIds: string[];
52
+ store: Pick<StorePort, "getMeta" | "setMeta"> & {
53
+ /** The Gateway retains answers while the original native request is pending. */
54
+ hasPendingAnswer?(approvalId: string, route: Route): boolean;
55
+ };
56
+ onError?: (error: unknown) => void;
57
+ /** Supported grammY HTTP boundary, also used for authenticated file downloads. */
58
+ fetch?: typeof fetch;
59
+ }
60
+
61
+ function hash(value: string): string { return createHash("sha256").update(value).digest("hex").slice(0, 24); }
62
+ function integer(value: string): boolean { return /^(0|[1-9][0-9]*)$/.test(value) && Number.isSafeInteger(Number(value)); }
63
+ function record(value: unknown): Record<string, unknown> { return value !== null && typeof value === "object" ? value as Record<string, unknown> : {}; }
64
+ function code(error: unknown): number | undefined { const value = record(error).error_code; return typeof value === "number" ? value : undefined; }
65
+ function notModified(error: unknown): boolean { return code(error) === 400 && String(record(error).description).includes("message is not modified"); }
66
+
67
+ /** grammY's Node entrypoint requires its SDK signal; keep caller cancellation scoped to the API call. */
68
+ export async function withTelegramSignal<T>(
69
+ signal: AbortSignal | undefined, call: (signal: ApiAbortSignal | undefined) => Promise<T>,
70
+ ): Promise<T> {
71
+ if (!signal) return call(undefined);
72
+ const controller = new ApiAbortController();
73
+ const abort = () => controller.abort();
74
+ signal.addEventListener("abort", abort, { once: true });
75
+ if (signal.aborted) abort();
76
+ try { return await call(controller.signal); }
77
+ finally { signal.removeEventListener("abort", abort); }
78
+ }
79
+
80
+ /** Never retain SDK errors: their nested HTTP causes/payloads can contain tokens. */
81
+ export function telegramDeliveryError(error: unknown): DeliveryError {
82
+ if (error instanceof DeliveryError) return error;
83
+ const status = code(error);
84
+ const retry = record(record(error).parameters).retry_after;
85
+ return new DeliveryError(status ? `Telegram API rejected operation (${status})` : "Telegram operation outcome is unknown",
86
+ status !== undefined && status >= 400 && status < 500 && status !== 408 ? "rejected" : "uncertain",
87
+ status === 429 && typeof retry === "number" && retry >= 0 ? retry * 1000 : undefined);
88
+ }
89
+
90
+ export class TelegramMessenger implements Messenger {
91
+ private readonly api: Api;
92
+ private readonly http: typeof fetch;
93
+ private readonly chats: Set<string>;
94
+ private readonly report: (error: unknown) => void;
95
+ private me: UserFromGetMe | null = null;
96
+ private handlers: Handlers | null = null;
97
+ private abort: AbortController | null = null;
98
+ private polling: Promise<void> | null = null;
99
+ private readonly pending = new Map<string, Pending>();
100
+ private readonly approvalFlights = new Map<string, Promise<string>>();
101
+
102
+ constructor(private readonly options: TelegramMessengerOptions) {
103
+ this.http = options.fetch ?? globalThis.fetch;
104
+ // Redirects may otherwise forward the bot token embedded in the API URL.
105
+ this.api = new Api(options.token, { fetch: this.http, sensitiveLogs: false, timeoutSeconds: 45, baseFetchConfig: { redirect: "error" } });
106
+ this.chats = new Set(options.allowedChatIds);
107
+ this.report = options.onError ?? (error => console.error("Telegram event failed:", error));
108
+ if (!/^[1-9][0-9]*$/.test(options.ownerId) || !Number.isSafeInteger(Number(options.ownerId)) ||
109
+ options.allowedChatIds.some(id => !/^-[1-9][0-9]*$/.test(id) || !Number.isSafeInteger(Number(id)))) {
110
+ throw new DeliveryError("Telegram requires a positive owner user ID and negative allowed group IDs", "rejected");
111
+ }
112
+ }
113
+
114
+ private get offsetKey(): string { return `telegram:${this.me!.id}:offset`; }
115
+ private get observedAtKey(): string { return `telegram:${this.me!.id}:observed-at`; }
116
+ private stateKey(token: string): string { return `telegram:${this.me!.id}:approval:${token}`; }
117
+ private cardKey(route: Route, messageId: string): string { return `telegram:${this.me!.id}:card:${hash(JSON.stringify([physicalRouteKey(route), messageId]))}`; }
118
+ private fileKey(route: Route, fileId: string): string { return `telegram:${this.me!.id}:file:${hash(JSON.stringify([physicalRouteKey(route), fileId]))}`; }
119
+ private fileIdentity(file: Attachment): string {
120
+ // Context metadata is not a download capability; older admitted files need
121
+ // not be reauthorized merely because voice metadata is now available.
122
+ return JSON.stringify({ id: file.id, name: file.name, url: file.url, size: file.size,
123
+ ...(file.contentType ? { contentType: file.contentType } : {}) });
124
+ }
125
+
126
+ async start(handlers: Handlers): Promise<void> {
127
+ if (this.handlers) throw new DeliveryError("Telegram messenger is already started", "rejected");
128
+ this.handlers = handlers;
129
+ this.abort = new AbortController();
130
+ // Observe rejection immediately, even if reconciliation fails while the
131
+ // authentication reads are still in flight. No raw startup error is logged.
132
+ const ready = handlers.ready?.then(() => true, () => false);
133
+ try {
134
+ this.me = await withTelegramSignal(this.abort.signal, signal => this.api.getMe(signal));
135
+ if (!this.me.is_bot || !Number.isSafeInteger(this.me.id)) throw new DeliveryError("Telegram getMe did not identify a bot", "rejected");
136
+ const webhook = await withTelegramSignal(this.abort.signal, signal => this.api.getWebhookInfo(signal));
137
+ if (webhook.url) throw new DeliveryError("Telegram bot already has a webhook; refusing to remove or replace it", "rejected");
138
+ const offset = this.options.store.getMeta(this.offsetKey);
139
+ if (offset !== null && !integer(offset)) throw new DeliveryError("Telegram stored update offset is invalid", "rejected");
140
+ this.polling = this.poll(offset === null ? undefined : Number(offset), this.abort.signal, ready);
141
+ } catch (error) {
142
+ this.abort.abort(); this.abort = null; this.handlers = null; this.me = null;
143
+ throw telegramDeliveryError(error);
144
+ }
145
+ }
146
+
147
+ private async poll(offset: number | undefined, signal: AbortSignal, ready?: Promise<boolean>): Promise<void> {
148
+ if (signal.aborted) return;
149
+ if (ready) {
150
+ const { promise, resolve } = Promise.withResolvers<boolean>();
151
+ const abort = () => { resolve(false); };
152
+ signal.addEventListener("abort", abort, { once: true });
153
+ try {
154
+ if (!await Promise.race([ready, promise])) {
155
+ if (!signal.aborted) this.report(new DeliveryError("Telegram startup reconciliation failed; intake remains stopped", "rejected"));
156
+ return;
157
+ }
158
+ } finally { signal.removeEventListener("abort", abort); }
159
+ }
160
+ let recovering = false;
161
+ while (!signal.aborted) {
162
+ try {
163
+ const savedObservedAt = this.options.store.getMeta(this.observedAtKey);
164
+ const now = Date.now();
165
+ // Missing timestamps (including older ledgers), clock rollback, and
166
+ // retention-expired cursors must not send an old high offset that could
167
+ // acknowledge a new, lower random update sequence before admission.
168
+ if (offset !== undefined && (savedObservedAt === null || !integer(savedObservedAt) ||
169
+ Number(savedObservedAt) > now || now - Number(savedObservedAt) >= CURSOR_IDLE_MS)) offset = undefined;
170
+ const updates = await withTelegramSignal(signal, sdkSignal => this.api.getUpdates({
171
+ ...(offset === undefined ? {} : { offset }), timeout: 30, limit: 100,
172
+ allowed_updates: ["message", "edited_message", "callback_query"],
173
+ }, sdkSignal));
174
+ const observedAt = Date.now();
175
+ if (recovering) { await this.handlers?.reconnect?.(); recovering = false; }
176
+ for (const update of updates) {
177
+ if (signal.aborted) return;
178
+ if (!Number.isSafeInteger(update.update_id) || update.update_id < 0) throw new DeliveryError("Telegram supplied an invalid update ID", "rejected");
179
+ if (offset !== undefined && update.update_id < offset) continue;
180
+ await this.process(update);
181
+ // The next getUpdates call acknowledges this cursor remotely. Persist
182
+ // only after durable admission/native approval processing completes.
183
+ const next = update.update_id + 1;
184
+ this.options.store.setMeta(this.offsetKey, String(next));
185
+ // Offset first: a crash between writes can only cause conservative
186
+ // replay, never pair a fresh timestamp with a stale high offset.
187
+ this.options.store.setMeta(this.observedAtKey, String(observedAt));
188
+ offset = next;
189
+ }
190
+ } catch (error) {
191
+ if (signal.aborted) return;
192
+ const safe = telegramDeliveryError(error);
193
+ this.report(safe);
194
+ if ([401, 403, 409].includes(code(error) ?? 0)) return;
195
+ recovering = true;
196
+ try { await delay(Math.max(1000, safe.retryAfterMs ?? 0), undefined, { signal }); }
197
+ catch { return; }
198
+ }
199
+ }
200
+ }
201
+
202
+ private route(chat: Chat, threadId?: number): Route | null {
203
+ if (!this.me || !Number.isSafeInteger(chat.id)) return null;
204
+ const channelId = String(chat.id);
205
+ if (chat.type === "private") {
206
+ if (channelId !== this.options.ownerId || (threadId !== undefined && !this.me.has_topics_enabled)) return null;
207
+ } else if ((chat.type !== "group" && chat.type !== "supergroup") || !this.chats.has(channelId) || chat.id >= 0 ||
208
+ (threadId !== undefined && (chat.type !== "supergroup" || !chat.is_forum))) return null;
209
+ if (threadId !== undefined && (!Number.isSafeInteger(threadId) || threadId <= 0)) return null;
210
+ return { platform: "telegram", accountId: String(this.me.id), authorityId: this.options.ownerId,
211
+ guildId: chat.type === "private" ? null : channelId, channelId, threadId: threadId === undefined ? null : String(threadId) };
212
+ }
213
+
214
+ /** Sender and physical destination are API identities, never quoted identities. */
215
+ normalize(message: Message): Inbound | null {
216
+ const data = record(message);
217
+ if (!message.from || message.from.is_bot || String(message.from.id) !== this.options.ownerId || message.sender_chat ||
218
+ data.forward_origin || data.forward_from || data.forward_sender_name || data.forward_from_chat || data.is_automatic_forward || data.via_bot || data.business_connection_id) return null;
219
+ const route = this.route(message.chat, message.message_thread_id);
220
+ if (!route || !Number.isSafeInteger(message.message_id) || message.message_id <= 0) return null;
221
+ const files: Attachment[] = [];
222
+ const add = (file: { file_id: string; file_unique_id: string; file_size?: number; file_name?: string; mime_type?: string; duration?: number }, name: string, contentType?: string, voice = false) => {
223
+ if (!/^[A-Za-z0-9_-]+$/.test(file.file_id)) return;
224
+ if (file.file_size !== undefined && (typeof file.file_size !== "number" || !Number.isSafeInteger(file.file_size) || file.file_size < 0)) {
225
+ throw new DeliveryError("Telegram supplied an invalid attachment size", "rejected");
226
+ }
227
+ files.push({ id: file.file_id, name: file.file_name ?? name, url: `telegram-file:${file.file_id}`,
228
+ size: file.file_size ?? null, ...(file.mime_type ?? contentType ? { contentType: file.mime_type ?? contentType } : {}),
229
+ ...(voice ? { voice: true as const } : {}),
230
+ ...(typeof file.duration === "number" && Number.isFinite(file.duration) && file.duration >= 0 ? { durationSeconds: file.duration } : {}) });
231
+ };
232
+ const photo = message.photo?.reduce((largest, candidate) => candidate.width * candidate.height > largest.width * largest.height ? candidate : largest);
233
+ if (photo) add(photo, `photo-${photo.file_unique_id}.jpg`, "image/jpeg");
234
+ if (message.document) add(message.document, `document-${message.document.file_unique_id}`);
235
+ if (message.audio) add(message.audio, `audio-${message.audio.file_unique_id}`);
236
+ if (message.video) add(message.video, `video-${message.video.file_unique_id}.mp4`, "video/mp4");
237
+ if (message.voice) add(message.voice, `voice-${message.voice.file_unique_id}.ogg`, "audio/ogg", true);
238
+ if (message.video_note) add(message.video_note, `video-note-${message.video_note.file_unique_id}.mp4`, "video/mp4");
239
+ const originalText = message.text ?? message.caption ?? "";
240
+ let text = originalText;
241
+ const entities = message.text === undefined ? message.caption_entities : message.entities;
242
+ // Telegram offsets/lengths are UTF-16, matching JS slice. Only an actual
243
+ // leading bot_command entity may address this bot; body mentions are text.
244
+ const entity = entities?.find(value => value.type === "bot_command" && value.offset === 0);
245
+ if (entity && Number.isSafeInteger(entity.length) && entity.length > 0 && entity.length <= text.length &&
246
+ (entity.length === text.length || /\s/.test(text[entity.length]!))) {
247
+ const qualified = /^\/([a-z0-9_]{1,32})@([a-z0-9_]+)$/i.exec(text.slice(0, entity.length));
248
+ if (qualified) {
249
+ if (!this.me?.username || qualified[2]!.toLowerCase() !== this.me.username.toLowerCase()) return null;
250
+ if (COMMAND_NAMES.has(qualified[1]!)) text = `/${qualified[1]}${text.slice(entity.length)}`;
251
+ }
252
+ }
253
+ if (!text && files.length === 0) return null;
254
+ const reply = this.replyContext(message, route);
255
+ // Preserve the existing owner-edit identity when optional context appears
256
+ // after an adapter upgrade or an independently edited referenced message.
257
+ let revision = "original";
258
+ if (message.edit_date !== undefined) {
259
+ const fileIdentity = files.map(({ voice: _voice, durationSeconds: _duration, ...file }) => file);
260
+ revision = `edit:${message.edit_date}:${hash(JSON.stringify([originalText, fileIdentity]))}`;
261
+ }
262
+ return { id: `telegram:${route.accountId}:${route.channelId}:${message.message_id}:${revision}`, route,
263
+ messageId: String(message.message_id), text, receivedAt: (message.edit_date ?? message.date) * 1000, attachments: files,
264
+ ...(reply ? { reply } : {}) };
265
+ }
266
+
267
+ private replyContext(message: Message, route: Route): ReplyContext | undefined {
268
+ const original = message.reply_to_message;
269
+ if (!original || !Number.isSafeInteger(original.message_id) || original.message_id <= 0) return;
270
+ const source = this.route(original.chat, original.message_thread_id);
271
+ if (!source || physicalRouteKey(source) !== physicalRouteKey(route)) return;
272
+ return { messageId: String(original.message_id), authorId: original.date !== 0 && original.from ? String(original.from.id) : null,
273
+ text: original.date === 0 ? null : original.text ?? original.caption ?? null, ...(message.quote ? { quote: message.quote.text } : {}) };
274
+ }
275
+
276
+ private async process(update: Update): Promise<void> {
277
+ if (update.callback_query) { await this.callback(update.callback_query); return; }
278
+ const message = update.message ?? update.edited_message;
279
+ if (!message) return;
280
+ const input = this.normalize(message);
281
+ if (!input) return;
282
+ // An exact reply to an active bot card is the only text approval surface.
283
+ const reply = message.reply_to_message;
284
+ const pending = reply && [...this.pending.values()].find(value => value.messageId === String(reply.message_id) &&
285
+ physicalRouteKey(value.approval.route) === physicalRouteKey(input.route));
286
+ if (pending) {
287
+ if (!reply.from || String(reply.from.id) !== String(this.me!.id) || !reply.from.is_bot || !this.matchesCard(pending, reply)) return;
288
+ if (!pending.active || !pending.verified || pending.busy || !message.text || message.edit_date !== undefined) return;
289
+ if (pending.lastUpdate === input.id) return;
290
+ if (pending.dialog.method === "input" || pending.dialog.method === "editor") {
291
+ await this.finish(pending, { value: message.text }, input.id); return;
292
+ }
293
+ if (pending.dialog.method === "ask") {
294
+ const question = pending.dialog.questions[pending.question]!;
295
+ pending.customInput = message.text;
296
+ if (!question.multi) pending.selected = [];
297
+ pending.lastUpdate = input.id;
298
+ this.save(pending);
299
+ await this.refresh(pending);
300
+ return;
301
+ }
302
+ return;
303
+ }
304
+ // Card receipts outlive their controls and in-memory Pending objects. Never
305
+ // reinterpret a late reply as a new task in the currently selected DM topic.
306
+ if (reply?.from?.is_bot && String(reply.from.id) === String(this.me!.id)) {
307
+ const source = this.route(reply.chat, reply.message_thread_id);
308
+ if (source && physicalRouteKey(source) === physicalRouteKey(input.route) &&
309
+ this.options.store.getMeta(this.cardKey(source, String(reply.message_id))) !== null) return;
310
+ }
311
+ // Unregistered old approval replies must not become ordinary agent input.
312
+ if (reply?.from?.is_bot && String(reply.from.id) === String(this.me!.id) &&
313
+ reply.reply_markup?.inline_keyboard.some(row => row.some(button => "callback_data" in button && /^omp:[a-f0-9]{24}:/.test(button.callback_data)))) return;
314
+ for (const file of input.attachments) this.options.store.setMeta(this.fileKey(input.route, file.id), this.fileIdentity(file));
315
+ await this.handlers!.message(input);
316
+ }
317
+
318
+ private assertRoute(route: Route): void {
319
+ if (!this.me || route.platform !== "telegram" || route.accountId !== String(this.me.id) || route.authorityId !== this.options.ownerId ||
320
+ (route.guildId === null ? route.channelId !== this.options.ownerId : route.guildId !== route.channelId || !this.chats.has(route.channelId)) ||
321
+ (route.threadId !== null && (!integer(route.threadId) || Number(route.threadId) <= 0)) ||
322
+ (route.topicId !== undefined && route.guildId !== null)) throw new DeliveryError("Telegram route is not authorized for this bot and owner", "rejected");
323
+ }
324
+
325
+ private async destination(route: Route): Promise<Chat> {
326
+ this.assertRoute(route);
327
+ const chat = await this.api.getChat(route.channelId);
328
+ const actual = this.route(chat, route.threadId === null ? undefined : Number(route.threadId));
329
+ if (!actual || physicalRouteKey(actual) !== physicalRouteKey(route)) throw new DeliveryError("Telegram destination identity changed", "rejected");
330
+ return chat;
331
+ }
332
+
333
+ private thread(route: Route): { message_thread_id?: number } { return route.threadId === null ? {} : { message_thread_id: Number(route.threadId) }; }
334
+ private assertReceipt(message: Message, route: Route, messageId?: string): void {
335
+ const actual = this.route(message.chat, message.message_thread_id);
336
+ if (!actual || physicalRouteKey(actual) !== physicalRouteKey(route) || String(message.from?.id) !== String(this.me!.id) || !message.from?.is_bot ||
337
+ !Number.isSafeInteger(message.message_id) || message.message_id <= 0 || (messageId && String(message.message_id) !== messageId)) {
338
+ throw new DeliveryError("Telegram mutation returned an unexpected message identity", "uncertain");
339
+ }
340
+ }
341
+
342
+ async send(output: OutputRecord): Promise<string> {
343
+ try {
344
+ await this.destination(output.route);
345
+ const bytes = Buffer.byteLength(output.text, "utf8");
346
+ if (bytes > UPLOAD_LIMIT) throw new DeliveryError("Telegram text document exceeds the 50 MiB upload limit", "rejected");
347
+ const message = output.text.length <= TEXT_LIMIT ? await this.api.sendMessage(output.route.channelId, output.text || "(empty output)", {
348
+ ...this.thread(output.route), link_preview_options: { is_disabled: true }, allow_paid_broadcast: false,
349
+ }) : await this.api.sendDocument(output.route.channelId, new InputFile(Buffer.from(output.text, "utf8"), `omp-${hash(output.id)}.txt`), {
350
+ ...this.thread(output.route), caption: "Full output is attached.", allow_paid_broadcast: false,
351
+ });
352
+ this.assertReceipt(message, output.route);
353
+ return String(message.message_id);
354
+ } catch (error) { throw telegramDeliveryError(error); }
355
+ }
356
+
357
+ async setActivity(message: MessageReference, activity: MessageActivity): Promise<void> {
358
+ try {
359
+ const messageId = this.messageId(message.messageId);
360
+ await this.destination(message.route);
361
+ await this.api.setMessageReaction(message.route.channelId, messageId, [{ type: "emoji", emoji: activity === "thinking" ? "\u{1F914}" : "\u{1F440}" }]);
362
+ } catch (error) { throw telegramDeliveryError(error); }
363
+ }
364
+
365
+ private save(pending: Pending): void {
366
+ const { messageId, attempted, active, question, answers, selected, customInput, lastUpdate, answerRequest } = pending;
367
+ // Partial ask answers are needed only while the dialog remains live.
368
+ this.options.store.setMeta(this.stateKey(pending.token), JSON.stringify({ messageId, attempted, active,
369
+ question: active ? question : 0, answers: active ? answers : [], selected: active ? selected : [],
370
+ ...(active && customInput !== undefined ? { customInput } : {}), lastUpdate, answerRequest } satisfies Progress));
371
+ }
372
+ private button(pending: Pending, action: string, text: string): InlineKeyboardButton {
373
+ const callback_data = `omp:${pending.token}:${action}`;
374
+ if (Buffer.byteLength(callback_data, "utf8") > 64) throw new DeliveryError("Telegram callback exceeds 64 bytes", "rejected");
375
+ return { text, callback_data };
376
+ }
377
+ private view(pending: Pending): CardView {
378
+ const dialog = pending.dialog;
379
+ let text: string;
380
+ const rows: InlineKeyboardButton[][] = [];
381
+ if (dialog.method === "confirm") {
382
+ text = `${dialog.title}\n\n${dialog.message}`;
383
+ rows.push([this.button(pending, "yes", "Confirm"), this.button(pending, "no", "Decline")]);
384
+ } else if (dialog.method === "input" || dialog.method === "editor") {
385
+ text = `${dialog.title}\nReply directly to THIS card with your complete response (not secret).${dialog.placeholder ? `\n${dialog.placeholder}` : ""}${dialog.prefill !== undefined ? `\nCurrent content:\n${dialog.prefill}` : ""}`;
386
+ } else if (dialog.method === "select") {
387
+ text = `${dialog.title}\nChoose one row; marked selections are OMP's current state.\n` + dialog.options.map((label, index) => {
388
+ const marker = index < dialog.markableCount && dialog.marker ? (dialog.marker === "checkbox" ? (dialog.checked.includes(index) ? "[x] " : "[ ] ") : "( ) ") : "";
389
+ rows.push([this.button(pending, `pick-${index}`, `${index + 1}. ${marker}${label}`)]);
390
+ return `${index + 1}. ${marker}${label}${index === dialog.initialIndex ? " (initial focus)" : ""}${dialog.details[index] ? ` — ${dialog.details[index]}` : ""}`;
391
+ }).join("\n");
392
+ } else {
393
+ const question = dialog.questions[pending.question]!;
394
+ text = `Question ${pending.question + 1}/${dialog.questions.length}${question.header ? ` — ${question.header}` : ""}\n${question.question}\n${question.multi ? "Toggle multiple choices and/or reply directly to THIS card with free text." : "Choose one option OR reply directly to THIS card with free text."}\n`;
395
+ text += question.options.map((option, index) => {
396
+ rows.push([this.button(pending, `q${pending.question}-${index}`, `${pending.selected.includes(option.label) ? "[x] " : ""}${index + 1}. ${option.label}`)]);
397
+ return `${index + 1}. ${option.label}${index === question.recommended ? " (recommended, not preselected)" : ""}${option.description ? ` — ${option.description}` : ""}${option.preview ? `\n${option.preview}` : ""}`;
398
+ }).join("\n");
399
+ if (pending.customInput !== undefined) text += `\nFree text received: ${pending.customInput.length} characters (stored in full).`;
400
+ rows.push([this.button(pending, `next-${pending.question}`, pending.question + 1 === dialog.questions.length ? "Submit all answers" : "Next question")]);
401
+ }
402
+ rows.push([this.button(pending, "cancel", "Cancel")]);
403
+ // A fresh activation stamp forces a real authoritative edit response on
404
+ // restart; Telegram has no getMessage API. Never fake a cached readback.
405
+ text += `\n\nOMP card ${pending.stamp}`;
406
+ if (text.length > TEXT_LIMIT || rows.length > 100 || rows.flat().some(button => button.text.length > 64)) {
407
+ throw new DeliveryError("Dialog exceeds Telegram card limits; use the local OMP interface", "rejected");
408
+ }
409
+ return { text, reply_markup: { inline_keyboard: rows } };
410
+ }
411
+
412
+ async showApproval(approval: Approval): Promise<string> {
413
+ const token = approvalCardToken(approval);
414
+ const existing = this.approvalFlights.get(token);
415
+ if (existing) return existing;
416
+ const flight = this.approvalCard(approval);
417
+ this.approvalFlights.set(token, flight);
418
+ try { return await flight; }
419
+ finally { this.approvalFlights.delete(token); }
420
+ }
421
+
422
+ private async approvalCard(approval: Approval): Promise<string> {
423
+ this.assertRoute(approval.route);
424
+ if (!this.handlers || approval.state !== "pending") throw new DeliveryError("Telegram approval is not pending on an active messenger", "rejected");
425
+ const token = approvalCardToken(approval);
426
+ const existing = this.pending.get(token);
427
+ if (existing?.active && existing.verified && existing.messageId) {
428
+ if (approval.remoteId && approval.remoteId !== existing.messageId) throw new DeliveryError("Telegram approval receipt conflict", "rejected");
429
+ return existing.messageId;
430
+ }
431
+ let pending: Pending;
432
+ let view: CardView;
433
+ try {
434
+ const dialog = parseDialog(approval.request);
435
+ const saved = this.options.store.getMeta(this.stateKey(token));
436
+ const progress: Progress = saved ? JSON.parse(saved) as Progress : { messageId: null, attempted: false, active: true, question: 0, answers: [], selected: [] };
437
+ if (approval.remoteId && progress.messageId && approval.remoteId !== progress.messageId) throw new DeliveryError("Telegram approval receipt conflict", "rejected");
438
+ if (saved && !progress.active && (progress.attempted || progress.messageId)) {
439
+ // Native reconciliation precedes Gateway replay. Keep the exact answered
440
+ // card closed while its durably admitted response awaits the replacement
441
+ // head; rejecting here would cancel the native request before replay.
442
+ // Neither an ordinary closed tombstone nor an ambiguous remote mutation
443
+ // is authority to rehydrate a request, and no response body is retained.
444
+ if (progress.messageId && progress.answerRequest === hash(JSON.stringify(approval.request)) &&
445
+ this.options.store.hasPendingAnswer?.(approval.id, approval.route)) return progress.messageId;
446
+ throw new DeliveryError("Telegram approval has already been answered or has an unresolved outcome", "uncertain");
447
+ }
448
+ const messageId = approval.remoteId ?? progress.messageId;
449
+ if (messageId && this.options.store.getMeta(this.cardKey(approval.route, messageId)) === "closed") {
450
+ throw new DeliveryError("Telegram approval receipt is closed", "uncertain");
451
+ }
452
+ pending = { ...progress, messageId: approval.remoteId ?? progress.messageId, approval: { ...approval, route: { ...approval.route } }, token, dialog,
453
+ stamp: randomBytes(6).toString("hex"), busy: false, verified: false };
454
+ if (pending.attempted && !pending.messageId) throw new DeliveryError("Telegram approval send outcome is unknown; refusing to resend", "uncertain");
455
+ view = this.view(pending);
456
+ } catch (error) {
457
+ if (error instanceof DeliveryError && error.message !== "Dialog exceeds Telegram card limits; use the local OMP interface") throw error;
458
+ // Never echo the request/title/prefill or parser errors (especially secret input).
459
+ const notice = "Request cancelled: this dialog cannot safely be represented in Telegram. Use the local OMP interface.";
460
+ try {
461
+ await this.destination(approval.route);
462
+ const message = approval.remoteId ? await this.api.editMessageText(approval.route.channelId, this.messageId(approval.remoteId), notice, { reply_markup: { inline_keyboard: [] }, link_preview_options: { is_disabled: true } }) :
463
+ await this.api.sendMessage(approval.route.channelId, notice, { ...this.thread(approval.route), link_preview_options: { is_disabled: true }, allow_paid_broadcast: false });
464
+ if (message === true) throw new DeliveryError("Telegram returned no authoritative card identity", "uncertain");
465
+ this.assertReceipt(message, approval.route, approval.remoteId ?? undefined);
466
+ this.options.store.setMeta(this.cardKey(approval.route, String(message.message_id)), "closed");
467
+ await this.handlers.answer(approval.id, { cancelled: true }, approval.route);
468
+ return String(message.message_id);
469
+ } catch (failure) { throw telegramDeliveryError(failure); }
470
+ }
471
+ this.pending.set(token, pending);
472
+ try {
473
+ await this.destination(approval.route);
474
+ pending.attempted = true;
475
+ this.save(pending);
476
+ const message = pending.messageId ? await this.api.editMessageText(approval.route.channelId, this.messageId(pending.messageId), view.text, {
477
+ reply_markup: view.reply_markup, link_preview_options: { is_disabled: true },
478
+ }) : await this.api.sendMessage(approval.route.channelId, view.text, {
479
+ ...this.thread(approval.route), reply_markup: view.reply_markup, link_preview_options: { is_disabled: true }, allow_paid_broadcast: false,
480
+ });
481
+ if (message === true) throw new DeliveryError("Telegram returned no authoritative card identity", "uncertain");
482
+ this.assertReceipt(message, approval.route, pending.messageId ?? undefined);
483
+ if (!this.matchesControls(pending, message)) throw new DeliveryError("Telegram card response has unexpected controls", "uncertain");
484
+ pending.messageId = String(message.message_id);
485
+ this.options.store.setMeta(this.cardKey(approval.route, pending.messageId), "card");
486
+ if (this.pending.get(token) !== pending || !pending.active) {
487
+ this.save(pending);
488
+ await this.dismissApproval({ ...approval, remoteId: pending.messageId });
489
+ return pending.messageId;
490
+ }
491
+ pending.active = true; pending.verified = true; this.save(pending);
492
+ return pending.messageId;
493
+ } catch (error) {
494
+ const safe = telegramDeliveryError(error);
495
+ pending.active = false;
496
+ // A known rejected initial send can be explicitly retried; an ambiguous
497
+ // send or ANY edit failure must never fall back to a new message.
498
+ if (!pending.messageId && safe.certainty === "rejected") { pending.attempted = false; pending.active = true; }
499
+ this.save(pending); this.pending.delete(token);
500
+ throw safe;
501
+ }
502
+ }
503
+
504
+ private messageId(id: string): number {
505
+ if (!integer(id) || Number(id) <= 0) throw new DeliveryError("Invalid Telegram message ID", "rejected");
506
+ return Number(id);
507
+ }
508
+ private matchesControls(pending: Pending, message: Message): boolean {
509
+ const buttons = message.reply_markup?.inline_keyboard.flat() ?? [];
510
+ return buttons.length > 0 && buttons.every(button => "callback_data" in button && button.callback_data.startsWith(`omp:${pending.token}:`));
511
+ }
512
+ private matchesCard(pending: Pending, message: Message): boolean {
513
+ try { this.assertReceipt(message, pending.approval.route, pending.messageId ?? undefined); }
514
+ catch { return false; }
515
+ return this.matchesControls(pending, message);
516
+ }
517
+ private async refresh(pending: Pending): Promise<void> {
518
+ if (!pending.active || !pending.messageId) return;
519
+ const view = this.view(pending);
520
+ try {
521
+ const message = await this.api.editMessageText(pending.approval.route.channelId, this.messageId(pending.messageId), view.text, {
522
+ reply_markup: view.reply_markup, link_preview_options: { is_disabled: true },
523
+ });
524
+ if (message === true || !this.matchesCard(pending, message)) throw new DeliveryError("Telegram returned an unexpected edited card", "uncertain");
525
+ } catch (error) { if (!notModified(error)) throw telegramDeliveryError(error); }
526
+ }
527
+ private async finish(pending: Pending, response: DialogResponse, eventId: string): Promise<void> {
528
+ validateDecisionResponse(pending.approval, response);
529
+ pending.active = false; pending.lastUpdate = eventId;
530
+ pending.answerRequest = hash(JSON.stringify(pending.approval.request)); this.save(pending);
531
+ try { await this.handlers!.answer(pending.approval.id, response, pending.approval.route); }
532
+ finally { await this.dismissApproval({ ...pending.approval, remoteId: pending.messageId }); }
533
+ }
534
+
535
+ private async callback(query: CallbackQuery): Promise<void> {
536
+ const parsed = /^omp:([a-f0-9]{24}):([a-z]+[0-9]*(?:-[0-9]+)?)$/.exec(query.data ?? "");
537
+ const pending = parsed ? this.pending.get(parsed[1]!) : undefined;
538
+ const reject = async (text = "This request is expired, unauthorized, or already being handled.") => {
539
+ try { await this.api.answerCallbackQuery(query.id, { text }); }
540
+ catch (error) { this.report(telegramDeliveryError(error)); }
541
+ };
542
+ if (!parsed || query.from.is_bot || String(query.from.id) !== this.options.ownerId || !pending?.active || !pending.verified || pending.busy || !this.handlers ||
543
+ !query.message || !("date" in query.message) || query.message.date === 0 || !this.matchesCard(pending, query.message as Message)) { await reject(); return; }
544
+ this.assertRoute(pending.approval.route);
545
+ const eventId = `callback:${query.id}`;
546
+ if (pending.lastUpdate === eventId) { await reject(); return; }
547
+ pending.busy = true;
548
+ try {
549
+ const action = parsed[2]!;
550
+ const dialog = pending.dialog;
551
+ if (action === "cancel") await this.finish(pending, { cancelled: true }, eventId);
552
+ else if (dialog.method === "confirm" && (action === "yes" || action === "no")) await this.finish(pending, { confirmed: action === "yes" }, eventId);
553
+ else if (dialog.method === "select" && /^pick-[0-9]+$/.test(action)) {
554
+ const option = dialog.options[Number(action.slice(5))];
555
+ if (option === undefined) { await reject(); return; }
556
+ await this.finish(pending, { value: option }, eventId);
557
+ } else if (dialog.method === "ask") {
558
+ const question = dialog.questions[pending.question]!;
559
+ const choice = new RegExp(`^q${pending.question}-([0-9]+)$`).exec(action);
560
+ if (choice) {
561
+ const option = question.options[Number(choice[1])];
562
+ if (!option) { await reject(); return; }
563
+ pending.selected = question.multi ? (pending.selected.includes(option.label) ? pending.selected.filter(value => value !== option.label) : [...pending.selected, option.label]) : [option.label];
564
+ if (!question.multi) pending.customInput = undefined;
565
+ } else if (action === `next-${pending.question}`) {
566
+ const answer = { id: question.id, selectedOptions: [...pending.selected], ...(pending.customInput !== undefined ? { customInput: pending.customInput } : {}) };
567
+ if (pending.approval.decision) {
568
+ try { validateDecisionAnswer(question, answer); }
569
+ catch (error) {
570
+ if (!(error instanceof DeliveryError) || error.certainty !== "rejected") throw error;
571
+ // Definitive rejection is a consumed callback, not a polling
572
+ // failure: retain the draft while allowing the next update.
573
+ await reject("Choose an option or enter an answer before continuing.");
574
+ return;
575
+ }
576
+ }
577
+ pending.answers.push(answer);
578
+ pending.question++; pending.selected = []; pending.customInput = undefined;
579
+ if (pending.question === dialog.questions.length) { await this.finish(pending, { answers: pending.answers }, eventId); return; }
580
+ } else { await reject(); return; }
581
+ pending.lastUpdate = eventId; this.save(pending); await this.refresh(pending);
582
+ } else { await reject(); return; }
583
+ // Spinner acknowledgement follows durable/native processing, never before.
584
+ try { await this.api.answerCallbackQuery(query.id); } catch (error) { this.report(telegramDeliveryError(error)); }
585
+ } finally { pending.busy = false; }
586
+ }
587
+
588
+ async dismissApproval(approval: Approval): Promise<void> {
589
+ this.assertRoute(approval.route);
590
+ const token = approvalCardToken(approval);
591
+ const pending = this.pending.get(token);
592
+ if (pending) { pending.active = false; this.save(pending); }
593
+ // save() already erased partial answers for the in-memory card.
594
+ const saved = pending ? null : this.options.store.getMeta(this.stateKey(token));
595
+ const progress = saved ? JSON.parse(saved) as Progress : undefined;
596
+ const id = approval.remoteId ?? pending?.messageId ?? progress?.messageId;
597
+ if (id) this.options.store.setMeta(this.cardKey(approval.route, id), "closed");
598
+ if (progress) this.options.store.setMeta(this.stateKey(token), JSON.stringify({ ...progress, active: false, question: 0, answers: [], selected: [], customInput: undefined }));
599
+ try {
600
+ if (id) await this.api.editMessageReplyMarkup(approval.route.channelId, this.messageId(id), { reply_markup: { inline_keyboard: [] } });
601
+ } catch (error) {
602
+ if (!notModified(error) && !(code(error) === 400 && String(record(error).description).includes("message to edit not found"))) throw telegramDeliveryError(error);
603
+ } finally { this.pending.delete(token); }
604
+ }
605
+
606
+ /** Telegram exposes topic mode and administrator rights through read APIs. */
607
+ async canCreateThread(route: Route): Promise<boolean> {
608
+ this.assertRoute(route);
609
+ if (route.threadId !== null) return false;
610
+ try {
611
+ const chat = await this.destination(route);
612
+ // https://core.telegram.org/bots/api/methods/createforumtopic.md
613
+ // https://core.telegram.org/bots/api/types/user.md
614
+ if (chat.type === "private") {
615
+ const me = await this.api.getMe();
616
+ if (!me.is_bot || me.id !== this.me!.id) throw new DeliveryError("Telegram bot identity changed", "rejected");
617
+ this.me = me;
618
+ return me.has_topics_enabled === true;
619
+ }
620
+ if (chat.type !== "supergroup" || !chat.is_forum) return false;
621
+ const member = await this.api.getChatMember(route.channelId, this.me!.id);
622
+ if (member.user.id !== this.me!.id || !member.user.is_bot) throw new DeliveryError("Telegram topic administrator identity changed", "rejected");
623
+ return member.status === "administrator" && member.can_manage_topics === true;
624
+ } catch (error) { throw telegramDeliveryError(error); }
625
+ }
626
+
627
+ async createThread(route: Route, title: string, _sourceMessageId?: string): Promise<Route> {
628
+ try {
629
+ this.assertRoute(route);
630
+ if (route.threadId !== null) throw new DeliveryError("Telegram cannot nest forum topics", "rejected");
631
+ if (!title.trim() || [...title].length > 128) throw new DeliveryError("Telegram forum topic title must contain 1–128 characters", "rejected");
632
+ const chat = await this.destination(route);
633
+ if (!(chat.type === "supergroup" && chat.is_forum) && !(chat.type === "private" && this.me!.has_topics_enabled)) {
634
+ throw new DeliveryError("Telegram destination does not support forum topics", "rejected");
635
+ }
636
+ const topic = await this.api.createForumTopic(route.channelId, title);
637
+ if (!Number.isSafeInteger(topic.message_thread_id) || topic.message_thread_id <= 0) throw new DeliveryError("Telegram created an invalid forum topic identity", "uncertain");
638
+ const { topicId: _topic, ...physical } = route;
639
+ return { ...physical, threadId: String(topic.message_thread_id) };
640
+ } catch (error) { throw telegramDeliveryError(error); }
641
+ }
642
+
643
+ /** No arbitrary history API: recovery is the durable offset (upstream retains at most 24 hours). */
644
+ async fetchAfter(route: Route, _messageId: string): Promise<null> { this.assertRoute(route); return null; }
645
+
646
+ async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
647
+ try {
648
+ this.assertRoute(route);
649
+ if (!/^[A-Za-z0-9_-]+$/.test(attachment.id) || attachment.url !== `telegram-file:${attachment.id}` ||
650
+ (attachment.size !== null && (typeof attachment.size !== "number" || !Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > DOWNLOAD_LIMIT)) ||
651
+ this.options.store.getMeta(this.fileKey(route, attachment.id)) !== this.fileIdentity(attachment)) {
652
+ throw new DeliveryError("Telegram attachment does not belong to an admitted message on this route", "rejected");
653
+ }
654
+ const file = await withTelegramSignal(signal, sdkSignal => this.api.getFile(attachment.id, sdkSignal));
655
+ const path = file.file_path;
656
+ if (file.file_id !== attachment.id || (file.file_size !== undefined &&
657
+ (typeof file.file_size !== "number" || !Number.isSafeInteger(file.file_size) || file.file_size < 0 || file.file_size > DOWNLOAD_LIMIT)) || !path ||
658
+ !/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_.-]+)+$/.test(path) || path.split("/").some(segment => segment === "." || segment === "..")) {
659
+ throw new DeliveryError("Telegram returned an unsafe or oversized file resource", "rejected");
660
+ }
661
+ // Token exists only in this immediate HTTPS request; never in ledger/errors.
662
+ const url = `https://api.telegram.org/file/bot${this.options.token}/${path}`;
663
+ const response = await this.http(url, { signal, redirect: "error" });
664
+ if (response.redirected || (response.url && response.url !== url) || (response.status >= 300 && response.status < 400)) {
665
+ throw new DeliveryError("Telegram file redirects or origin substitutions are forbidden", "rejected");
666
+ }
667
+ return response;
668
+ } catch (error) { throw telegramDeliveryError(error); }
669
+ }
670
+
671
+ async stop(): Promise<void> {
672
+ this.abort?.abort();
673
+ await this.polling;
674
+ this.polling = null; this.abort = null; this.handlers = null;
675
+ this.pending.clear(); this.me = null;
676
+ }
677
+ }