@theokit/gateway-telegram 0.5.0 → 0.6.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/CHANGELOG.md CHANGED
@@ -1,5 +1,92 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 458c34c: Wire channels from descriptors, and keep the channels that connect when another cannot.
8
+
9
+ `@theokit/gateway` exports `createChannels` and the types `ChannelDescriptor`,
10
+ `ChannelConfigField`, `ChannelWebhook`, `WebhookRequest`, `IngestResult`, `ChannelEntry`,
11
+ `ChannelRejection` and `CreateChannelsResult`. `createChannels(entries)` builds an adapter per
12
+ entry and returns `{ adapters, rejected }`: an entry whose required field is absent, `null` or
13
+ `""` is rejected with a `GatewayConfigurationError` coded `missing_required_config` naming the
14
+ keys, and a configuration error thrown by the descriptor's `create` is rejected the same way. Any
15
+ other error propagates. It connects nothing and makes no network call.
16
+
17
+ `GatewayRunner` accepts `connectFailure: "rollback" | "isolate"` (exported as `ConnectFailure`),
18
+ and `StartResult` is exported.
19
+ The default, `"rollback"`, is unchanged: one failed connect disconnects the adapters that did
20
+ connect and rejects `start()`. Under `"isolate"`, `start()` connects every adapter, wires inbound
21
+ only for the ones that connected, and reports the rest with a redacted reason.
22
+
23
+ `start()` now resolves a `StartResult` (`{ connected, failed }`) instead of `void`, under both
24
+ values. This is a type change: code that awaits `start()` and ignores the value is unaffected,
25
+ but a structural type declaring `start(): Promise<void>` that a `GatewayRunner` is assigned to
26
+ fails with TS2322, and a subclass overriding `start()` with that signature fails with TS2416.
27
+
28
+ `@theokit/gateway-telegram` exports `telegramChannel`, a socket channel whose config has a
29
+ required, secret `token` and an optional `allowedUsers`, and a `ConfigurationError` (a
30
+ `GatewayConfigurationError` with the `gateway-telegram` prefix). Called directly,
31
+ `telegramChannel.create` refuses a token that is not a string or is empty, and an `allowedUsers`
32
+ that is not an array of strings; through `createChannels`, an absent or empty token is rejected
33
+ first, as `missing_required_config`.
34
+
35
+ `@theokit/gateway-line` exports `lineChannel`, a webhook channel whose `webhook.verify` checks the
36
+ `x-line-signature` header against the raw body and whose `webhook.ingest` dispatches a verified
37
+ payload through `dispatchWebhookBody`, so a reply uses the cached reply token, or answers
38
+ `"malformed"` without dispatching. It answers `"no_handler"` (a member of `IngestResult`) when the
39
+ payload holds a text message for the handler and none is subscribed: before the runner started,
40
+ after it stopped, or when LINE's connect failed under `"isolate"`. Before, such a request answered
41
+ `"delivered"`, a route acknowledged it, and LINE did not redeliver the lost message.
42
+ `lineChannel.create` checks field types before the adapter's constructor.
43
+
44
+ `LineAdapter.dispatchWebhookBody` now resolves `"ok" | "no_handler"` instead of `void`. It answers
45
+ `"no_handler"`, dispatching nothing and caching no reply token, for a batch holding a text message
46
+ that passes the mention guard while no handler is subscribed; an empty or follow-only batch still
47
+ answers `"ok"`. It reads the handler once per batch, so a handler that unsubscribes while handling
48
+ one event still receives the rest of the batch. Code that ignores the value is unaffected; a
49
+ subclass overriding the method with `Promise<void>` fails with TS2416. `createWebhookServer` is
50
+ unchanged and still answers 200 before it dispatches.
51
+
52
+ Both descriptors are typed locally and import nothing `@theokit/gateway` 0.9.0 lacks, so the peer
53
+ range stays `>=0.9.0 <1.0.0`.
54
+
55
+ - 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
56
+
57
+ `@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
58
+ `filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
59
+ carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
60
+ `supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
61
+ field. The runner and the router refuse an outbound carrying attachments as
62
+ `attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
63
+ `supportsAttachments`.
64
+
65
+ `@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
66
+ `sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
67
+ when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
68
+ than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
69
+
70
+ Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
71
+ with `attachments_unsupported` and makes no platform call, instead of sending the text and
72
+ dropping the image.
73
+
74
+ The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
75
+ throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
76
+ as a handler error is. Dispatch still does not throw.
77
+
78
+ - 782e448: Carry voice in both directions. The inbound event gains an optional `audio` field, an
79
+ `InboundAudio` with the voice note's bytes, media type and duration in seconds, and
80
+ `OutboundAttachment` gains an `audio` member beside `image`. The Telegram adapter reads a polled
81
+ voice note through `getFile` and a download bounded at 20 MiB and 30 seconds, delivering the
82
+ message without `audio` and one stderr line when it cannot, and sends an audio attachment through
83
+ `sendVoice` with the reply text as its caption. Every other adapter refuses audio as it refuses an
84
+ image. Code that switches exhaustively on `OutboundAttachment["kind"]` gains a case.
85
+
86
+ ### Patch Changes
87
+
88
+ - 17c0713: Keep Markdown table rows whole when Discord, Slack, Teams, Telegram, WhatsApp and Mattermost split a long reply. A cut that fell inside a table row now moves back to the start of that row when the row fits in a part, so each row reaches the platform byte-identical. `chunkText` gains the opt-in `keepTableRows` option; text with no table row splits into the same chunks as before.
89
+
3
90
  ## 0.5.0
4
91
 
5
92
  ### Minor Changes
package/README.md CHANGED
@@ -41,6 +41,46 @@ const runner = new GatewayRunner({
41
41
  await runner.start();
42
42
  ```
43
43
 
44
+ ## Sending an image
45
+
46
+ `ctx.reply(text, { attachments })` sends each image through `sendPhoto`, one request per image, in
47
+ order, and the adapter reports `supportsAttachments` as `true`. The text becomes the first photo's
48
+ caption when it is 1 to 1024 UTF-16 units long, Telegram's caption limit. A longer text gets no
49
+ caption and is sent after the last photo, split as any text send is, in the same topic and without
50
+ the reply target, so none of it is cut. An empty text sends the photos alone.
51
+
52
+ Every attachment is checked before the first request: an `attachments` value that is not a list,
53
+ more than 10 images, or an image with no bytes or over 10 MiB (Telegram's photo limit) is refused
54
+ as `invalid_attachment`, and a `kind` other than `image` as `attachments_unsupported`, with no
55
+ request. On success the returned `messageId` is the last message sent. A photo Telegram refuses
56
+ ends the send with the mapped error and no `messageId`, and the photos before it stay delivered,
57
+ so retrying the whole send after a `rate_limited` or `network_error` sends those photos again.
58
+ An edit carrying attachments is refused as `attachments_unsupported`.
59
+
60
+ ## Voice notes
61
+
62
+ **Reading.** A voice note that arrives by polling reaches the handler with `event.audio` set: the
63
+ adapter calls `getFile` for its path and downloads it from Telegram's file server with the bot
64
+ token. The download is bounded at 20 MiB (Telegram's `getFile` limit; a voice whose declared
65
+ `file_size` is larger is not fetched at all), and the whole read, `getFile` and download with its
66
+ body, at 30 seconds. `mediaType` is the
67
+ voice's `mime_type`, `audio/ogg` when it has none, and `durationSeconds` its `duration`, 0 when it
68
+ is not a number. A blocked sender or a message without a voice triggers no request. A voice that
69
+ cannot be read (`getFile` fails, the download answers an error status, times out, passes 20 MiB,
70
+ or the voice has no `file_id`) is delivered without `audio`, as before this release, with one
71
+ stderr line `[telegram] voice not read: <reason>`; the line never carries the download URL, which
72
+ holds the token. A voice delivered through a webhook (`parseInbound`) is not read.
73
+
74
+ **Sending.** An attachment with `kind: "audio"` goes out through `sendVoice`, in the same path and
75
+ order as images: the text is the caption of the first attachment whatever its kind, under the
76
+ same 1024-unit rule, and an audio-only reply with empty text sends the clip alone. Audio must have
77
+ bytes, be at most 50 MiB (the Bot API upload limit) and declare an `audio/*` media type (any case,
78
+ parameters allowed), or the send is refused as `invalid_attachment` before any request. Telegram
79
+ shows OGG/Opus, MP3 and M4A as a voice bubble; other audio is delivered as a file.
80
+
81
+ Attachments need `@theokit/gateway` 0.13.0 or later: an older core's `ctx.reply` does not carry
82
+ them to the adapter, so install both together.
83
+
44
84
  ## Channel descriptor
45
85
 
46
86
  `telegramChannel` describes this channel as data, for `createChannels` in `@theokit/gateway`:
package/dist/index.cjs CHANGED
@@ -84,6 +84,101 @@ function parseInbound(payload) {
84
84
  );
85
85
  }
86
86
 
87
+ // src/read-voice.ts
88
+ var MAX_VOICE_BYTES = 20 * 1024 * 1024;
89
+ var READ_TIMEOUT_MS = 3e4;
90
+ var DEFAULT_MEDIA_TYPE = "audio/ogg";
91
+ async function readVoice(ctx, token, fetchImpl = fetch) {
92
+ const voice = ctx.message?.voice ?? {};
93
+ if (typeof voice.file_id !== "string") return { reason: "no_file_id" };
94
+ if (typeof voice.file_size === "number" && voice.file_size > MAX_VOICE_BYTES) {
95
+ return { reason: "too_large" };
96
+ }
97
+ const controller = new AbortController();
98
+ const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);
99
+ try {
100
+ const path = await filePath(ctx, controller.signal);
101
+ if (typeof path !== "string") return path;
102
+ const url = `https://api.telegram.org/file/bot${token}/${path}`;
103
+ const bytes = await download(url, fetchImpl, controller.signal);
104
+ if (!(bytes instanceof Uint8Array)) return bytes;
105
+ return { audio: { data: bytes, ...voiceDetails(voice) } };
106
+ } finally {
107
+ clearTimeout(timer);
108
+ }
109
+ }
110
+ function voiceDetails(voice) {
111
+ const duration = voice.duration;
112
+ return {
113
+ mediaType: typeof voice.mime_type === "string" ? voice.mime_type : DEFAULT_MEDIA_TYPE,
114
+ durationSeconds: typeof duration === "number" && Number.isFinite(duration) ? duration : 0
115
+ };
116
+ }
117
+ async function filePath(ctx, signal) {
118
+ let file;
119
+ try {
120
+ file = await ctx.getFile(signal);
121
+ } catch {
122
+ return { reason: signal.aborted ? "timeout" : "get_file_failed" };
123
+ }
124
+ return file.file_path ?? { reason: "no_file_path" };
125
+ }
126
+ async function download(url, fetchImpl, signal) {
127
+ try {
128
+ const response = await fetchImpl(url, { signal });
129
+ if (!response.ok) return { reason: `download_status_${response.status}` };
130
+ if (response.body === null) return { reason: "download_failed" };
131
+ return await readBounded(response.body, signal);
132
+ } catch {
133
+ return { reason: signal.aborted ? "timeout" : "download_failed" };
134
+ }
135
+ }
136
+ async function readBounded(body, signal) {
137
+ const reader = body.getReader();
138
+ const cancel = () => void reader.cancel().catch(() => void 0);
139
+ signal.addEventListener("abort", cancel, { once: true });
140
+ try {
141
+ const chunks = await readChunks(reader);
142
+ if (signal.aborted) return { reason: "timeout" };
143
+ return chunks ?? { reason: "too_large" };
144
+ } finally {
145
+ signal.removeEventListener("abort", cancel);
146
+ }
147
+ }
148
+ async function readChunks(reader) {
149
+ const chunks = [];
150
+ let total = 0;
151
+ for (; ; ) {
152
+ const { done, value } = await reader.read();
153
+ if (done) break;
154
+ total += value.length;
155
+ if (total > MAX_VOICE_BYTES) {
156
+ await reader.cancel();
157
+ return void 0;
158
+ }
159
+ chunks.push(value);
160
+ }
161
+ const bytes = new Uint8Array(total);
162
+ let offset = 0;
163
+ for (const chunk of chunks) {
164
+ bytes.set(chunk, offset);
165
+ offset += chunk.length;
166
+ }
167
+ return bytes;
168
+ }
169
+
170
+ // src/refuse-attachments.ts
171
+ function refuseAttachments(out) {
172
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
173
+ return {
174
+ ok: false,
175
+ error: {
176
+ code: "attachments_unsupported",
177
+ message: "telegram adapter cannot attach to an edit"
178
+ }
179
+ };
180
+ }
181
+
87
182
  // src/split.ts
88
183
  var TELEGRAM_MAX_MESSAGE = 4096;
89
184
  var SAFE_CHUNK = 4e3;
@@ -96,40 +191,261 @@ function splitForTelegram(text) {
96
191
  parts.push(remaining);
97
192
  break;
98
193
  }
99
- let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
100
- if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
101
- if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;
194
+ let boundary = findBoundary(remaining);
195
+ const afterRow = takeRowSafe(parts, remaining, boundary);
196
+ if (afterRow !== void 0) {
197
+ remaining = afterRow;
198
+ continue;
199
+ }
102
200
  const rawChunk = remaining.slice(0, boundary);
103
201
  const balanced = balanceMarkdownPairs(rawChunk);
104
202
  const chunk = balanced.length > 0 ? balanced : rawChunk;
105
203
  boundary = chunk.length;
106
- parts.push(chunk);
107
- remaining = remaining.slice(boundary).replace(/^\n+/, "");
204
+ const [piece, reopen] = closeFence(chunk);
205
+ parts.push(piece);
206
+ remaining = reopen + remaining.slice(boundary).replace(/^\n+/, "");
108
207
  }
109
208
  return parts;
110
209
  }
210
+ function findBoundary(remaining) {
211
+ let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
212
+ if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
213
+ return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;
214
+ }
215
+ function takeRowSafe(parts, remaining, boundary) {
216
+ const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);
217
+ if (moved === void 0) return void 0;
218
+ const [piece, reopen] = closeFence(remaining.slice(0, moved.end));
219
+ parts.push(piece);
220
+ return reopen + remaining.slice(moved.start);
221
+ }
222
+ var isLineEnd = (ch) => ch === "\n" || ch === "\r";
223
+ function rowSafeCut(text, cut, window) {
224
+ const start = tableRowStart(text, cut);
225
+ if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
226
+ let end = start;
227
+ while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
228
+ return end > 0 ? { end, start } : void 0;
229
+ }
230
+ function tableRowStart(text, cut) {
231
+ if (cut >= text.length || isLineEnd(text[cut])) return void 0;
232
+ let start = cut;
233
+ while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
234
+ return start > 0 && /^[^\S\r\n]*\|/.test(text.slice(start, cut + 1)) ? start : void 0;
235
+ }
236
+ function rowLength(text, start, cut, window) {
237
+ let rowEnd = cut;
238
+ while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
239
+ return rowEnd - start;
240
+ }
241
+ var FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
242
+ var MAX_INFO = 40;
243
+ function fencedRanges(text) {
244
+ const ranges = [];
245
+ let open;
246
+ let pos = 0;
247
+ for (const line of text.split("\n")) {
248
+ open = stepFence(open, line, pos, ranges);
249
+ pos += line.length + 1;
250
+ }
251
+ if (open !== void 0) ranges.push([open.start, text.length]);
252
+ return ranges;
253
+ }
254
+ function stepFence(open, line, pos, ranges) {
255
+ const m = FENCE_LINE.exec(line.replace(/\r$/, ""));
256
+ const marker = m?.[1];
257
+ if (marker === void 0) return open;
258
+ if (open === void 0) return { fence: { marker, info: (m?.[2] ?? "").trim() }, start: pos };
259
+ if (!closesFence(open.fence, marker, m?.[2] ?? "")) return open;
260
+ ranges.push([open.start, pos + line.length]);
261
+ return void 0;
262
+ }
263
+ function closesFence(fence, marker, rest) {
264
+ return marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === "";
265
+ }
266
+ function openFenceAt(text) {
267
+ const last = fencedRanges(text).at(-1);
268
+ if (last === void 0 || last[1] !== text.length) return void 0;
269
+ const lines = text.slice(last[0]).split("\n");
270
+ const opener = FENCE_LINE.exec(lines[0] ?? "");
271
+ const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? "").replace(/\r$/, "")) : null;
272
+ if (opener?.[1] === void 0) return void 0;
273
+ const fence = { marker: opener[1], info: (opener[2] ?? "").trim().slice(0, MAX_INFO) };
274
+ if (closer?.[1] !== void 0 && closesFence(fence, closer[1], closer[2] ?? "")) return void 0;
275
+ return fence;
276
+ }
277
+ function closeFence(chunk) {
278
+ const open = openFenceAt(chunk);
279
+ if (open === void 0) return [chunk, ""];
280
+ return [`${chunk}
281
+ ${open.marker}`, `${open.marker}${open.info}
282
+ `];
283
+ }
111
284
  function balanceMarkdownPairs(chunk) {
112
285
  const markers = ["**", "__", "~~", "`"];
113
286
  let out = chunk;
114
287
  for (const m of markers) {
115
- const count = countOccurrences(out, m);
116
- if (count % 2 === 1) {
117
- const lastIdx = out.lastIndexOf(m);
118
- out = out.slice(0, lastIdx).trimEnd();
288
+ const outside = markerIndexes(out, m);
289
+ if (outside.length % 2 === 1) {
290
+ out = out.slice(0, outside[outside.length - 1]).trimEnd();
119
291
  }
120
292
  }
121
293
  return out;
122
294
  }
123
- function countOccurrences(haystack, needle) {
124
- let count = 0;
295
+ function markerIndexes(text, needle) {
296
+ const ranges = fencedRanges(text);
297
+ const found = [];
125
298
  let pos = 0;
126
299
  while (true) {
127
- const found = haystack.indexOf(needle, pos);
128
- if (found === -1) break;
129
- count += 1;
130
- pos = found + needle.length;
300
+ const at = text.indexOf(needle, pos);
301
+ if (at === -1) break;
302
+ pos = at + needle.length;
303
+ if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);
304
+ }
305
+ return found;
306
+ }
307
+
308
+ // src/send-photos.ts
309
+ var CAPTION_LIMIT = 1024;
310
+ var MAX_PHOTO_BYTES = 10 * 1024 * 1024;
311
+ var MAX_AUDIO_BYTES = 50 * 1024 * 1024;
312
+ var KIND_LIMITS = {
313
+ image: { maxBytes: MAX_PHOTO_BYTES, label: "an image", bound: "10 MiB" },
314
+ audio: { maxBytes: MAX_AUDIO_BYTES, label: "an audio", bound: "50 MiB" }
315
+ };
316
+ var MAX_PHOTOS_PER_SEND = 10;
317
+ function hasAttachments(out) {
318
+ return out.attachments != null && out.attachments.length !== 0;
319
+ }
320
+ async function sendPhotos(api, out) {
321
+ const chatId = Number(out.channel.id);
322
+ if (Number.isNaN(chatId)) {
323
+ return {
324
+ ok: false,
325
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
326
+ };
327
+ }
328
+ const refusal = validateAttachments(out.attachments);
329
+ if (refusal !== void 0) return refusal;
330
+ const shared = sharedOptions(out);
331
+ try {
332
+ let lastId = await sendEachAttachment(api, chatId, out, shared);
333
+ if (out.text.length > CAPTION_LIMIT) {
334
+ for (const chunk of splitForTelegram(out.text)) {
335
+ lastId = (await api.sendMessage(chatId, chunk, shared)).message_id;
336
+ }
337
+ }
338
+ return { ok: true, messageId: String(lastId) };
339
+ } catch (err) {
340
+ return mapSendError(err);
341
+ }
342
+ }
343
+ async function sendEachAttachment(api, chatId, out, shared) {
344
+ const attachments = out.attachments;
345
+ const caption = captionOf(out.text);
346
+ let lastId = 0;
347
+ for (const [index, attachment] of attachments.entries()) {
348
+ const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
349
+ const file = new grammy.InputFile(attachment.data, attachment.filename);
350
+ const msg = attachment.kind === "audio" ? await api.sendVoice(chatId, file, options) : await api.sendPhoto(chatId, file, options);
351
+ lastId = msg.message_id;
352
+ }
353
+ return lastId;
354
+ }
355
+ function captionOf(text) {
356
+ return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : void 0;
357
+ }
358
+ function firstPhotoOptions(out, caption) {
359
+ return {
360
+ ...caption !== void 0 ? { caption } : {},
361
+ ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
362
+ };
363
+ }
364
+ function sharedOptions(out) {
365
+ const parseMode = mapFormat(out.format);
366
+ const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
367
+ return {
368
+ ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
369
+ ...threadId !== void 0 ? { message_thread_id: threadId } : {}
370
+ };
371
+ }
372
+ function validateAttachments(attachments) {
373
+ if (!Array.isArray(attachments)) {
374
+ return refuse("invalid_attachment", "attachments is not a list");
375
+ }
376
+ if (attachments.length > MAX_PHOTOS_PER_SEND) {
377
+ return refuse(
378
+ "invalid_attachment",
379
+ `telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`
380
+ );
381
+ }
382
+ for (const attachment of attachments) {
383
+ const refusal = validateAttachment(attachment);
384
+ if (refusal !== void 0) return refusal;
385
+ }
386
+ return void 0;
387
+ }
388
+ function validateAttachment(attachment) {
389
+ if (typeof attachment !== "object" || attachment === null) {
390
+ return refuse("invalid_attachment", "an attachment is not an object");
391
+ }
392
+ if (attachment.kind !== "image" && attachment.kind !== "audio") {
393
+ return refuse(
394
+ "attachments_unsupported",
395
+ "telegram adapter sends only image and audio attachments"
396
+ );
397
+ }
398
+ const limit = KIND_LIMITS[attachment.kind];
399
+ if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {
400
+ return refuse("invalid_attachment", `${limit.label} attachment has no bytes`);
401
+ }
402
+ if (attachment.data.length > limit.maxBytes) {
403
+ return refuse(
404
+ "invalid_attachment",
405
+ `${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`
406
+ );
407
+ }
408
+ return mediaTypeRefusal(attachment);
409
+ }
410
+ function mediaTypeRefusal(attachment) {
411
+ if (attachment.kind !== "audio") return void 0;
412
+ const mediaType = typeof attachment.mediaType === "string" ? attachment.mediaType : "";
413
+ if (mediaType.toLowerCase().startsWith("audio/")) return void 0;
414
+ return refuse("invalid_attachment", `an audio attachment has media type "${mediaType}"`);
415
+ }
416
+ function refuse(code, message) {
417
+ return { ok: false, error: { code, message } };
418
+ }
419
+ function mapFormat(format) {
420
+ if (format === "markdown") return "Markdown";
421
+ if (format === "html") return "HTML";
422
+ return void 0;
423
+ }
424
+ function parseModeOptions(format) {
425
+ const parseMode = mapFormat(format);
426
+ return parseMode !== void 0 ? { parse_mode: parseMode } : {};
427
+ }
428
+ function mapSendError(err) {
429
+ if (err instanceof grammy.GrammyError) {
430
+ const description = err.description.toLowerCase();
431
+ if (description.includes("rate limit") || err.error_code === 429) {
432
+ return { ok: false, error: { code: "rate_limited", message: err.description } };
433
+ }
434
+ if (description.includes("forbidden") || err.error_code === 403) {
435
+ return { ok: false, error: { code: "no_permission", message: err.description } };
436
+ }
437
+ if (description.includes("parse")) {
438
+ return { ok: false, error: { code: "markdown_error", message: err.description } };
439
+ }
440
+ return {
441
+ ok: false,
442
+ error: { code: `telegram_${err.error_code}`, message: err.description }
443
+ };
444
+ }
445
+ if (err instanceof grammy.HttpError) {
446
+ return { ok: false, error: { code: "network_error", message: err.message } };
131
447
  }
132
- return count;
448
+ return { ok: false, error: { code: "unknown", message: err.message } };
133
449
  }
134
450
 
135
451
  // src/adapter.ts
@@ -194,8 +510,9 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
194
510
  this.startPromise = void 0;
195
511
  }
196
512
  }
197
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.
513
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: photo dispatch (send-photos.ts) + validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.
198
514
  async sendMessage(out) {
515
+ if (hasAttachments(out)) return sendPhotos(this.bot.api, out);
199
516
  if (out.text.length === 0) {
200
517
  return { ok: false, error: { code: "empty_text", message: "text is empty" } };
201
518
  }
@@ -224,18 +541,25 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
224
541
  }
225
542
  return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
226
543
  }
544
+ /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
545
+ supportsAttachments = true;
227
546
  /** Telegram edits a sent message's text through `editMessageText`. */
228
547
  supportsEdit = true;
229
548
  /**
230
549
  * Replace the text of a message this bot sent, through `editMessageText`.
231
550
  *
232
- * Refuses, with no request, empty text, a message id that is not a safe positive integer, and
233
- * a non-numeric channel, in that order; the first and last are `sendMessage`'s own checks. A text `splitForTelegram` would cut in
234
- * two is refused as `edit_too_long`: an edit replaces one message. Telegram's "message is not
235
- * modified" refusal is answered as a success, because the message already shows the text; a
236
- * caller that treated it as a failure would send the same text again as a second message.
551
+ * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no
552
+ * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,
553
+ * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own
554
+ * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit
555
+ * replaces one message. Telegram's "message is not modified" refusal is answered as a success,
556
+ * because the message already shows the text; a caller that treated it as a failure would send
557
+ * the same text again as a second message.
237
558
  */
238
559
  async editMessage(messageId, out) {
560
+ return refuseAttachments(out) ?? this.editText(messageId, out);
561
+ }
562
+ async editText(messageId, out) {
239
563
  if (out.text.length === 0) {
240
564
  return { ok: false, error: { code: "empty_text", message: "text is empty" } };
241
565
  }
@@ -293,7 +617,21 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
293
617
  }
294
618
  const event = normalizeEvent(ctx);
295
619
  if (event === void 0) return;
296
- await this.dispatchEvent(event);
620
+ await this.dispatchEvent(await this.withVoice(ctx, event));
621
+ }
622
+ /**
623
+ * The event with the voice note's audio when the message has one (B-715, ADR D1).
624
+ *
625
+ * An unreadable voice leaves the event as it was and writes the reason to stderr: the message is
626
+ * delivered either way, as it was before voice notes were read.
627
+ */
628
+ async withVoice(ctx, event) {
629
+ if (ctx.message?.voice === void 0) return event;
630
+ const read = await readVoice(ctx, this.bot.token);
631
+ if ("audio" in read) return { ...event, audio: read.audio };
632
+ process.stderr.write(`[telegram] voice not read: ${read.reason}
633
+ `);
634
+ return event;
297
635
  }
298
636
  /**
299
637
  * Dispatch a pre-built event to the current handler, honouring EC-H replace
@@ -335,15 +673,6 @@ function normalizeEvent(ctx) {
335
673
  if (chat === void 0 || msg === void 0) return void 0;
336
674
  return buildEvent(chat, msg, ctx.from, ctx);
337
675
  }
338
- function mapFormat(format) {
339
- if (format === "markdown") return "Markdown";
340
- if (format === "html") return "HTML";
341
- return void 0;
342
- }
343
- function parseModeOptions(format) {
344
- const parseMode = mapFormat(format);
345
- return parseMode !== void 0 ? { parse_mode: parseMode } : {};
346
- }
347
676
  function parseMessageId(messageId) {
348
677
  if (!/^\d+$/.test(messageId)) return void 0;
349
678
  const id = Number(messageId);
@@ -364,28 +693,6 @@ function editPartsRefusal(partCount) {
364
693
  }
365
694
  return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
366
695
  }
367
- function mapSendError(err) {
368
- if (err instanceof grammy.GrammyError) {
369
- const description = err.description.toLowerCase();
370
- if (description.includes("rate limit") || err.error_code === 429) {
371
- return { ok: false, error: { code: "rate_limited", message: err.description } };
372
- }
373
- if (description.includes("forbidden") || err.error_code === 403) {
374
- return { ok: false, error: { code: "no_permission", message: err.description } };
375
- }
376
- if (description.includes("parse")) {
377
- return { ok: false, error: { code: "markdown_error", message: err.description } };
378
- }
379
- return {
380
- ok: false,
381
- error: { code: `telegram_${err.error_code}`, message: err.description }
382
- };
383
- }
384
- if (err instanceof grammy.HttpError) {
385
- return { ok: false, error: { code: "network_error", message: err.message } };
386
- }
387
- return { ok: false, error: { code: "unknown", message: err.message } };
388
- }
389
696
  var ConfigurationError = class extends gateway.GatewayConfigurationError {
390
697
  name = "ConfigurationError";
391
698
  constructor(opts) {