@theokit/gateway-telegram 0.9.0 → 0.10.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,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2831ca3: Report `capabilities.maxMessageChars` from the splitter limit, and `capabilities.threads` (true for Discord, Telegram and Slack).
8
+
3
9
  ## 0.9.0
4
10
 
5
11
  ### Minor Changes
package/README.md CHANGED
@@ -124,7 +124,8 @@ strings, with this package's `ConfigurationError` (also a `GatewayConfigurationE
124
124
  ## Capabilities
125
125
 
126
126
  `adapter.capabilities` reports `edit`, `typing` and `reactions` as `true` and
127
- `attachments: ["image", "audio"]`. See `@theokit/gateway` for the field meanings.
127
+ `attachments: ["image", "audio"]`. It also reports `maxMessageChars: 4096` (the splitter limit)
128
+ and `threads: true`. See `@theokit/gateway` for the field meanings.
128
129
 
129
130
  ## Helpers
130
131
 
package/dist/index.cjs CHANGED
@@ -504,6 +504,9 @@ function policyInput(event) {
504
504
  };
505
505
  }
506
506
  var TelegramAdapter = class extends gateway.BasePlatformAdapter {
507
+ get capabilities() {
508
+ return { ...super.capabilities, maxMessageChars: TELEGRAM_MAX_MESSAGE, threads: true };
509
+ }
507
510
  platform = "telegram";
508
511
  bot;
509
512
  allowedUsers;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/group-policy.ts","../src/parse-inbound.ts","../src/read-voice.ts","../src/refuse-attachments.ts","../src/split.ts","../src/send-photos.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts"],"names":["InputFile","GrammyError","HttpError","BasePlatformAdapter","Bot","GatewayConfigurationError"],"mappings":";;;;;;;;AAuCO,SAAS,aAAA,CAAc,OAAoB,MAAA,EAAgC;AAChF,EAAA,IAAI,KAAA,CAAM,QAAA,KAAa,SAAA,EAAW,OAAO,IAAA;AACzC,EAAA,IAAI,KAAA,C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AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa;AAAA,GACf;AAAA,EACA;AAAA,IACE,GAAA,EAAK,gBAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EACE;AAAA;AAEN,CAAA;AAUO,IAAM,eAAA,GAAkB;AAAA,EAC7B,QAAA,EAAU,UAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAA4D;AACjE,IAAA,MAAM,KAAA,GAAQ,UAAU,MAAM,CAAA;AAC9B,IAAA,MAAM,YAAA,GAAe,iBAAiB,MAAM,CAAA;AAC5C,IAAA,MAAM,cAAA,GAAiB,mBAAmB,MAAM,CAAA;AAChD,IAAA,OAAO,IAAI,eAAA,CAAgB;AAAA,MACzB,KAAA;AAAA,MACA,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,YAAA,EAAa;AAAA,MACrD,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA;AAAe,KAC1D,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/** The message facts the policy reads, as plain values (no grammy `Context`). */\nexport interface PolicyInput {\n /** Telegram chat type: `private`, `group`, `supergroup` or `channel`. */\n readonly chatType: string;\n /** Message text or caption; empty when there is none. */\n readonly text: string;\n /** Id of the sender of the message being replied to, when it is a reply. */\n readonly replyToFromId?: number | undefined;\n}\n\n/**\n * Decide from plain values whether the bot should respond. Works without a grammy `Context`.\n * @public\n */\nexport function shouldRespond(input: PolicyInput, policy: PolicyContext): boolean {\n if (input.chatType === \"private\") return true;\n if (input.text.startsWith(\"/\")) return true;\n if (input.replyToFromId !== undefined && input.replyToFromId === policy.botId) return true;\n return input.text.toLowerCase().includes(`@${policy.botUsername.toLowerCase()}`);\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n return shouldRespond(\n {\n chatType: chat.type,\n text: ctx.message?.text ?? ctx.message?.caption ?? \"\",\n replyToFromId: ctx.message?.reply_to_message?.from?.id,\n },\n policy,\n );\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n","/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Read the audio of a polled voice note (B-715, ADR D1).\n *\n * Telegram sends a voice note as a file id. The bytes take two requests: `getFile` for the file's\n * path, then a download from `https://api.telegram.org/file/bot<token>/<path>`. Only the polled\n * path holds the token, so the webhook `parseInbound` does not read voice notes.\n *\n * A failure is returned as a reason, never thrown: the caller delivers the event without audio and\n * writes the reason to stderr, so an unreadable voice leaves today's behaviour. No reason carries\n * the download URL, which contains the bot token.\n */\n\nimport type { InboundAudio } from \"@theokit/gateway\";\nimport type { Context } from \"grammy\";\n\n/** The largest voice read: Bot API `getFile` serves files of at most 20 MB. */\nconst MAX_VOICE_BYTES = 20 * 1024 * 1024;\n\n/** How long the whole read, `getFile` and download, may take before it is abandoned. */\nconst READ_TIMEOUT_MS = 30_000;\n\nconst DEFAULT_MEDIA_TYPE = \"audio/ogg\";\n\n/** What a read produced: the audio, or why there is none. */\ntype VoiceRead = { readonly audio: InboundAudio } | { readonly reason: string };\n\n/** The `fetch` this module calls; injected in tests so nothing reaches api.telegram.org. */\ntype FetchLike = (url: string, init: { signal: AbortSignal }) => Promise<Response>;\n\n/**\n * The voice object of the message, as far as this module reads it. Every field is `unknown`: a\n * hand-built update or a change on Telegram's side may send any of them in another shape (EC-2).\n */\ninterface VoiceFields {\n readonly file_id?: unknown;\n readonly duration?: unknown;\n readonly mime_type?: unknown;\n readonly file_size?: unknown;\n}\n\n/** A failure, named by the reason the caller writes to stderr. */\ntype Failure = { readonly reason: string };\n\n/**\n * Read the voice note of `ctx.message`. The caller calls this only when the message has a `voice`.\n */\nexport async function readVoice(\n ctx: Context,\n token: string,\n fetchImpl: FetchLike = fetch,\n): Promise<VoiceRead> {\n const voice = (ctx.message?.voice ?? {}) as VoiceFields;\n if (typeof voice.file_id !== \"string\") return { reason: \"no_file_id\" };\n if (typeof voice.file_size === \"number\" && voice.file_size > MAX_VOICE_BYTES) {\n return { reason: \"too_large\" };\n }\n // One deadline over both requests: a stalled getFile holds the polling handler, and every\n // later update, as surely as a stalled download (NFR-006).\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);\n try {\n const path = await filePath(ctx, controller.signal);\n if (typeof path !== \"string\") return path;\n const url = `https://api.telegram.org/file/bot${token}/${path}`;\n const bytes = await download(url, fetchImpl, controller.signal);\n if (!(bytes instanceof Uint8Array)) return bytes;\n return { audio: { data: bytes, ...voiceDetails(voice) } };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The media type and duration, each replaced by its default when it is not of its type. */\nfunction voiceDetails(voice: VoiceFields): { mediaType: string; durationSeconds: number } {\n const duration = voice.duration;\n return {\n mediaType: typeof voice.mime_type === \"string\" ? voice.mime_type : DEFAULT_MEDIA_TYPE,\n durationSeconds: typeof duration === \"number\" && Number.isFinite(duration) ? duration : 0,\n };\n}\n\n/** The file's path on Telegram's file server, or the reason it is not known. */\nasync function filePath(ctx: Context, signal: AbortSignal): Promise<string | Failure> {\n let file: { file_path?: string };\n try {\n // grammy types the signal with the abort-controller polyfill; a native one is what it reads.\n file = await ctx.getFile(signal as Parameters<Context[\"getFile\"]>[0]);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"get_file_failed\" };\n }\n return file.file_path ?? { reason: \"no_file_path\" };\n}\n\n/**\n * The downloaded bytes, or the reason the download failed.\n *\n * `signal` covers the body read too, not only the headers: a body that stalls after the headers\n * would otherwise hold the polling handler, and every later update, for good (EC-1).\n */\nasync function download(\n url: string,\n fetchImpl: FetchLike,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n try {\n const response = await fetchImpl(url, { signal });\n if (!response.ok) return { reason: `download_status_${response.status}` };\n if (response.body === null) return { reason: \"download_failed\" };\n return await readBounded(response.body, signal);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"download_failed\" };\n }\n}\n\n/** The whole body, `too_large` as soon as it passes the bound, or `timeout` when `signal` aborts. */\nasync function readBounded(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n const reader = body.getReader();\n const cancel = (): void => void reader.cancel().catch(() => undefined);\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n const chunks = await readChunks(reader);\n if (signal.aborted) return { reason: \"timeout\" };\n return chunks ?? { reason: \"too_large\" };\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\n/** The chunks joined into one array, or `undefined` once more than the bound has arrived. */\nasync function readChunks(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Promise<Uint8Array | undefined> {\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > MAX_VOICE_BYTES) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * Used by `editMessage` only: Telegram has no call that adds an image to a sent message, so an edit carrying one is refused rather than applied as text alone. `sendMessage` sends attachments through `send-photos.ts`.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"telegram adapter cannot attach to an edit\",\n },\n };\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\nconst TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = findBoundary(remaining);\n // B-556: a cut inside a table row that fits a chunk moves back to the row's start.\n const afterRow = takeRowSafe(parts, remaining, boundary);\n if (afterRow !== undefined) {\n remaining = afterRow;\n continue;\n }\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n const [piece, reopen] = closeFence(chunk);\n parts.push(piece);\n remaining = reopen + remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/** The paragraph, then line, then hard boundary within the safe window. */\nfunction findBoundary(remaining: string): number {\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;\n}\n\n/**\n * When `boundary` falls inside a table row that fits a chunk, pushes the part before the row and\n * returns the text from the row on; undefined otherwise.\n */\nfunction takeRowSafe(parts: string[], remaining: string, boundary: number): string | undefined {\n const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);\n if (moved === undefined) return undefined;\n const [piece, reopen] = closeFence(remaining.slice(0, moved.end));\n parts.push(piece);\n return reopen + remaining.slice(moved.start);\n}\n\n/** `\\n`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nconst isLineEnd = (ch: string | undefined): boolean => ch === \"\\n\" || ch === \"\\r\";\n\n/**\n * Where to cut instead of `cut` so a Markdown table row (a line whose first non-blank character is\n * `|`) it falls inside stays whole: `start` is the row's first character, `end` where the chunk\n * ends with its trailing line endings dropped. Undefined when `cut` is not inside a row, the row\n * opens the chunk, or the row is longer than `window`. The same rule is in core `chunkText`\n * (`keepTableRows`); this package keeps its own copy because it peers core `>=0.9.0`.\n */\nfunction rowSafeCut(\n text: string,\n cut: number,\n window: number,\n): { readonly end: number; readonly start: number } | undefined {\n const start = tableRowStart(text, cut);\n if (start === undefined || rowLength(text, start, cut, window) > window) return undefined;\n let end = start;\n while (end > 0 && isLineEnd(text[end - 1])) end -= 1;\n return end > 0 ? { end, start } : undefined;\n}\n\n/** Start of the table row `cut` falls inside, or undefined (not in a row, or the row opens the text). */\nfunction tableRowStart(text: string, cut: number): number | undefined {\n if (cut >= text.length || isLineEnd(text[cut])) return undefined;\n let start = cut;\n while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;\n return start > 0 && /^[^\\S\\r\\n]*\\|/.test(text.slice(start, cut + 1)) ? start : undefined;\n}\n\n/** Length of the row from `start`, scanning no further than `window` past it. */\nfunction rowLength(text: string, start: number, cut: number, window: number): number {\n let rowEnd = cut;\n while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;\n return rowEnd - start;\n}\n\n/** A fenced code line: 3+ backticks or tildes, up to 3 spaces of indent, then the info string. */\nconst FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;\n\ninterface Fence {\n readonly marker: string;\n readonly info: string;\n}\n\n/** Longest info string a reopened fence repeats, so the reopening cannot eat the chunk's headroom. */\nconst MAX_INFO = 40;\n\n/** The `[start, end)` ranges of `text` that lie inside fenced code, fence lines included. */\nfunction fencedRanges(text: string): Array<readonly [number, number]> {\n const ranges: Array<readonly [number, number]> = [];\n let open: OpenFence | undefined;\n let pos = 0;\n for (const line of text.split(\"\\n\")) {\n open = stepFence(open, line, pos, ranges);\n pos += line.length + 1;\n }\n if (open !== undefined) ranges.push([open.start, text.length]);\n return ranges;\n}\n\ninterface OpenFence {\n readonly fence: Fence;\n readonly start: number;\n}\n\n/** Folds one line into the fence state; a fence that closes on it is added to `ranges`. */\nfunction stepFence(\n open: OpenFence | undefined,\n line: string,\n pos: number,\n ranges: Array<readonly [number, number]>,\n): OpenFence | undefined {\n const m = FENCE_LINE.exec(line.replace(/\\r$/, \"\"));\n const marker = m?.[1];\n if (marker === undefined) return open;\n if (open === undefined) return { fence: { marker, info: (m?.[2] ?? \"\").trim() }, start: pos };\n if (!closesFence(open.fence, marker, m?.[2] ?? \"\")) return open;\n ranges.push([open.start, pos + line.length]);\n return undefined;\n}\n\nfunction closesFence(fence: Fence, marker: string, rest: string): boolean {\n return (\n marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === \"\"\n );\n}\n\n/** The fence still open at the end of `text`, if any. */\nfunction openFenceAt(text: string): Fence | undefined {\n const last = fencedRanges(text).at(-1);\n if (last === undefined || last[1] !== text.length) return undefined;\n const lines = text.slice(last[0]).split(\"\\n\");\n const opener = FENCE_LINE.exec(lines[0] ?? \"\");\n const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? \"\").replace(/\\r$/, \"\")) : null;\n if (opener?.[1] === undefined) return undefined;\n const fence = { marker: opener[1], info: (opener[2] ?? \"\").trim().slice(0, MAX_INFO) };\n if (closer?.[1] !== undefined && closesFence(fence, closer[1], closer[2] ?? \"\")) return undefined;\n return fence;\n}\n\n/**\n * B-526: a cut inside a fenced code block closes the fence at the end of the chunk and reopens it\n * at the start of the next. Returns the chunk and the text to put before the rest.\n */\nfunction closeFence(chunk: string): [string, string] {\n const open = openFenceAt(chunk);\n if (open === undefined) return [chunk, \"\"];\n return [`${chunk}\\n${open.marker}`, `${open.marker}${open.info}\\n`];\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing. Markers inside fenced code are not counted:\n * the fence is the chunk's business, not the markers within it.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const outside = markerIndexes(out, m);\n if (outside.length % 2 === 1) {\n out = out.slice(0, outside[outside.length - 1]).trimEnd();\n }\n }\n return out;\n}\n\n/** Indexes of `needle` in `text`, non-overlapping, skipping those inside fenced code. */\nfunction markerIndexes(text: string, needle: string): number[] {\n const ranges = fencedRanges(text);\n const found: number[] = [];\n let pos = 0;\n while (true) {\n const at = text.indexOf(needle, pos);\n if (at === -1) break;\n pos = at + needle.length;\n if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);\n }\n return found;\n}\n","/**\n * The attachment path of `TelegramAdapter.sendMessage`: one `sendPhoto` per image (B-674) and one\n * `sendVoice` per audio clip (B-715, ADR D2). The module keeps its photo name: one path for both\n * kinds means one caption rule, and a module of its own for voice would import the caption helpers\n * from here while this one imports it, a cycle.\n *\n * The text rides as the first attachment's caption when it is 1 to 1024 UTF-16 units. A longer text\n * gets no caption and follows the last photo through the same split as a text send, so nothing of\n * it is cut. Every attachment is checked before the first request, so a refusal makes no call.\n *\n * The module also holds how a send maps a declared format and a thrown grammy error, which\n * `TelegramAdapter` imports from here: both paths must answer them the same way, and keeping them\n * here rather than in `adapter.ts` avoids an import cycle.\n */\n\nimport type { OutboundAttachment, OutboundMessage, SendResult } from \"@theokit/gateway\";\nimport { type Api, GrammyError, HttpError, InputFile } from \"grammy\";\nimport { splitForTelegram } from \"./split.js\";\n\n/** Telegram's limit on a photo caption, in UTF-16 units (Bot API `sendPhoto`). */\nconst CAPTION_LIMIT = 1024;\n\n/** Telegram's limit on an uploaded photo: \"The photo must be at most 10 MB\" (Bot API `sendPhoto`). */\nconst MAX_PHOTO_BYTES = 10 * 1024 * 1024;\n\n/** Telegram's limit on a file a bot uploads, voice included: 50 MB (Bot API \"Sending files\"). */\nconst MAX_AUDIO_BYTES = 50 * 1024 * 1024;\n\n/** The bound on each kind's bytes, and the word a refusal uses for it. */\nconst KIND_LIMITS = {\n image: { maxBytes: MAX_PHOTO_BYTES, label: \"an image\", bound: \"10 MiB\" },\n audio: { maxBytes: MAX_AUDIO_BYTES, label: \"an audio\", bound: \"50 MiB\" },\n} as const;\n\n/**\n * The most images one send takes. Each image is a request, and a group chat takes about 20\n * messages a minute before Telegram answers 429; ten, the size of a `sendMediaGroup` album, leaves\n * room for the text that follows. A longer list is refused whole rather than cut off part way.\n */\nconst MAX_PHOTOS_PER_SEND = 10;\n\n/** Options every request of one send shares: the parse mode and the forum topic. */\ninterface SharedOptions {\n parse_mode?: \"Markdown\" | \"HTML\";\n message_thread_id?: number;\n}\n\n/**\n * Whether an outbound carries attachments to send. Absent, `null` and an empty list do not. `!== 0`,\n * not `> 0`: any other non-array value has no numeric length and is taken down the photo path,\n * where it is refused rather than dropped (EC-1).\n */\nexport function hasAttachments(out: OutboundMessage): boolean {\n return out.attachments != null && out.attachments.length !== 0;\n}\n\n/**\n * Send the images of `out` as photos, then the text when it is too long for a caption.\n *\n * Returns the id of the last message sent. A failure on photo k returns the mapped error at once,\n * and photos 1 to k-1 stay delivered: Telegram has no way to take them back as one unit.\n */\nexport async function sendPhotos(api: Api, out: OutboundMessage): Promise<SendResult> {\n const chatId = Number(out.channel.id);\n if (Number.isNaN(chatId)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const refusal = validateAttachments(out.attachments);\n if (refusal !== undefined) return refusal;\n const shared = sharedOptions(out);\n try {\n let lastId = await sendEachAttachment(api, chatId, out, shared);\n if (out.text.length > CAPTION_LIMIT) {\n for (const chunk of splitForTelegram(out.text)) {\n lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts)))\n .message_id;\n }\n }\n return { ok: true, messageId: String(lastId) };\n } catch (err) {\n return mapSendError(err);\n }\n}\n\n/**\n * One `sendPhoto` per image and one `sendVoice` per audio clip, in order; the caption and reply\n * target go on the first only, whatever its kind.\n */\nasync function sendEachAttachment(\n api: Api,\n chatId: number,\n out: OutboundMessage,\n shared: SharedOptions,\n): Promise<number> {\n const attachments = out.attachments as ReadonlyArray<OutboundAttachment>;\n const caption = captionOf(out.text);\n let lastId = 0;\n for (const [index, attachment] of attachments.entries()) {\n const options = { ...shared, ...(index === 0 ? firstPhotoOptions(out, caption) : {}) };\n const msg = await withPlainFallback<typeof options, { message_id: number }>(options, (opts) => {\n const file = new InputFile(attachment.data, attachment.filename);\n return attachment.kind === \"audio\"\n ? api.sendVoice(chatId, file, opts)\n : api.sendPhoto(chatId, file, opts);\n });\n lastId = msg.message_id;\n }\n return lastId;\n}\n\n/**\n * Run `send` with `options`. When Telegram refuses the legacy Markdown (`markdown_error`), write\n * one diagnostic line and run `send` once more without `parse_mode`. Any other failure, and a\n * failure of the resend, is rethrown for the caller's `mapSendError`.\n */\nexport async function withPlainFallback<O extends { parse_mode?: \"Markdown\" | \"HTML\" }, R>(\n options: O,\n send: (options: O) => Promise<R>,\n): Promise<R> {\n try {\n return await send(options);\n } catch (err) {\n if (options.parse_mode === undefined) throw err;\n const mapped = mapSendError(err);\n if (mapped.ok || mapped.error?.code !== \"markdown_error\") throw err;\n process.stderr.write(\n `[theokit-gateway-telegram] ${mapped.error.message}; resending as plain text\\n`,\n );\n const { parse_mode: _dropped, ...plain } = options;\n return send(plain as O);\n }\n}\n\n/** The text as a caption when it fits in 1 to 1024 units, otherwise none. */\nfunction captionOf(text: string): string | undefined {\n return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : undefined;\n}\n\n/** What only the first attachment carries: the caption and the message it replies to. */\nfunction firstPhotoOptions(\n out: OutboundMessage,\n caption: string | undefined,\n): { caption?: string; reply_parameters?: { message_id: number } } {\n return {\n ...(caption !== undefined ? { caption } : {}),\n ...(out.replyTo !== undefined ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}),\n };\n}\n\n/** The parse mode and the forum topic, applied to every request of the send. */\nfunction sharedOptions(out: OutboundMessage): SharedOptions {\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n return {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n };\n}\n\n/**\n * The refusal for an attachment list Telegram cannot send, or `undefined`.\n *\n * Not an array, more than ten attachments, an entry with no bytes or over its kind's bound (10 MiB\n * for an image, 50 MiB for audio), or audio whose media type is not `audio/*`:\n * `invalid_attachment`. A kind other than `image` or `audio`: `attachments_unsupported`, the code\n * every adapter answers for what it cannot attach. Every entry is checked before the first request,\n * so a refusal makes no call and never leaves part of the list delivered.\n */\nfunction validateAttachments(attachments: unknown): SendResult | undefined {\n if (!Array.isArray(attachments)) {\n return refuse(\"invalid_attachment\", \"attachments is not a list\");\n }\n if (attachments.length > MAX_PHOTOS_PER_SEND) {\n return refuse(\n \"invalid_attachment\",\n `telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`,\n );\n }\n for (const attachment of attachments as ReadonlyArray<OutboundAttachment | null>) {\n const refusal = validateAttachment(attachment);\n if (refusal !== undefined) return refusal;\n }\n return undefined;\n}\n\n/** The refusal for one entry of the list, or `undefined` when Telegram can send it. */\nfunction validateAttachment(attachment: OutboundAttachment | null): SendResult | undefined {\n if (typeof attachment !== \"object\" || attachment === null) {\n return refuse(\"invalid_attachment\", \"an attachment is not an object\");\n }\n if (attachment.kind !== \"image\" && attachment.kind !== \"audio\") {\n return refuse(\n \"attachments_unsupported\",\n \"telegram adapter sends only image and audio attachments\",\n );\n }\n const limit = KIND_LIMITS[attachment.kind];\n if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {\n return refuse(\"invalid_attachment\", `${limit.label} attachment has no bytes`);\n }\n if (attachment.data.length > limit.maxBytes) {\n return refuse(\n \"invalid_attachment\",\n `${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`,\n );\n }\n return mediaTypeRefusal(attachment);\n}\n\n/** Audio must declare an `audio/*` media type, in any case; an image's is not checked (B-674). */\nfunction mediaTypeRefusal(attachment: OutboundAttachment): SendResult | undefined {\n if (attachment.kind !== \"audio\") return undefined;\n const mediaType = typeof attachment.mediaType === \"string\" ? attachment.mediaType : \"\";\n if (mediaType.toLowerCase().startsWith(\"audio/\")) return undefined;\n return refuse(\"invalid_attachment\", `an audio attachment has media type \"${mediaType}\"`);\n}\n\nfunction refuse(code: string, message: string): SendResult {\n return { ok: false, error: { code, message } };\n}\n\n/** The `parse_mode` grammy takes for a declared format, or `undefined` for plain text. */\nexport function mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\n/** The `parse_mode` option for a declared format, or no option. */\nexport function parseModeOptions(format: OutboundMessage[\"format\"]): {\n parse_mode?: \"Markdown\" | \"HTML\";\n} {\n const parseMode = mapFormat(format);\n return parseMode !== undefined ? { parse_mode: parseMode } : {};\n}\n\nfunction mapGrammyError(err: GrammyError): SendResult {\n // A proxy or a non Bot API body can leave `description` undefined.\n const message = err.description ?? err.message;\n const description = message.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message } };\n }\n return { ok: false, error: { code: `telegram_${err.error_code ?? \"unknown\"}`, message } };\n}\n\n/** A thrown grammy error as a `SendResult`; never rethrows. */\nexport function mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) return mapGrammyError(err);\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError } from \"grammy\";\nimport { type PolicyInput, shouldRespond } from \"./group-policy.js\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { readVoice } from \"./read-voice.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport {\n hasAttachments,\n mapFormat,\n mapSendError,\n parseModeOptions,\n sendPhotos,\n withPlainFallback,\n} from \"./send-photos.js\";\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n /**\n * How updates arrive. `\"polling\"` (default) pulls them with long polling; `\"webhook\"` only marks\n * the adapter connected, and updates arrive through `deliver()`.\n */\n readonly inbound?: \"polling\" | \"webhook\";\n /**\n * When true, a group or supergroup message reaches the handler only if it mentions the bot,\n * replies to one of the bot's messages, or is a slash command. Private chats always pass.\n * Default false (today's behaviour).\n */\n readonly requireMention?: boolean;\n}\n\nfunction isObj(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null;\n}\n\n/** The message facts the policy reads, from an event whose `raw` is a Context or an update. */\nfunction policyInput(event: GatewayMessageEvent): PolicyInput {\n const raw = (event as { telegram?: { raw?: unknown } }).telegram?.raw;\n const msg = isObj(raw) && isObj(raw.message) ? raw.message : undefined;\n const replyTo =\n msg !== undefined && isObj(msg.reply_to_message) ? msg.reply_to_message : undefined;\n const from = replyTo !== undefined && isObj(replyTo.from) ? replyTo.from : undefined;\n return {\n chatType: event.channel.type === \"dm\" ? \"private\" : \"group\",\n text: event.text,\n replyToFromId: typeof from?.id === \"number\" ? from.id : undefined,\n };\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates by default, so inbound needs no public URL.\n * With `inbound: \"webhook\"` it does not poll; updates arrive through `deliver()`.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private readonly inbound: \"polling\" | \"webhook\";\n private readonly requireMention: boolean;\n private warnedNoIdentity = false;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.inbound = opts.inbound ?? \"polling\";\n this.requireMention = opts.requireMention === true;\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n if (this.inbound === \"polling\")\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n if (this.inbound === \"webhook\") return;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // 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.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (hasAttachments(out)) return sendPhotos(this.bot.api, out);\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await withPlainFallback(\n {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n },\n (opts) => this.bot.api.sendMessage(chatIdNum, chunk, opts),\n );\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */\n override readonly supportsAttachments = true;\n\n /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */\n protected override readonly attachmentKinds = [\"image\", \"audio\"] as const;\n\n /** Telegram edits a sent message's text through `editMessageText`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, through `editMessageText`.\n *\n * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no\n * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,\n * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own\n * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit\n * replaces one message. Telegram's \"message is not modified\" refusal is answered as a success,\n * because the message already shows the text; a caller that treated it as a failure would send\n * the same text again as a second message.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const id = parseMessageId(messageId);\n if (id === undefined) {\n return {\n ok: false,\n error: {\n code: \"invalid_message_id\",\n message: `message id \"${messageId}\" is not a positive integer`,\n },\n };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parts = splitForTelegram(out.text);\n if (parts.length !== 1) return editPartsRefusal(parts.length);\n try {\n await this.bot.api.editMessageText(\n chatIdNum,\n id,\n parts[0] as string,\n parseModeOptions(out.format),\n );\n } catch (err) {\n if (!isNotModified(err)) return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n const chatId = Number(channelId);\n const id = parseMessageId(messageId);\n if (Number.isNaN(chatId) || id === undefined || emoji.length === 0) {\n return {\n ok: false,\n error: {\n code: \"invalid_reaction\",\n message: \"numeric channel, message id and emoji needed\",\n },\n };\n }\n try {\n // The emoji must be one of Telegram's allowed reactions; the API refuses others.\n await this.bot.api.setMessageReaction(chatId, id, [\n { type: \"emoji\", emoji } as unknown as Parameters<\n typeof this.bot.api.setMessageReaction\n >[2][number],\n ]);\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(await this.withVoice(ctx, event));\n }\n\n /** The `requireMention` gate, shared by the polled and webhook paths. */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (!this.requireMention || event.channel.type === \"dm\") return true;\n let me: { id: number; username?: string } | undefined;\n try {\n me = this.bot.botInfo;\n } catch {\n me = undefined;\n }\n if (me?.username === undefined) {\n if (!this.warnedNoIdentity) {\n this.warnedNoIdentity = true;\n process.stderr.write(\n \"[telegram] requireMention: bot identity not known yet; dropping group message\\n\",\n );\n }\n return false;\n }\n return shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });\n }\n\n /**\n * The event with the voice note's audio when the message has one (B-715, ADR D1).\n *\n * An unreadable voice leaves the event as it was and writes the reason to stderr: the message is\n * delivered either way, as it was before voice notes were read.\n */\n private async withVoice(\n ctx: Context,\n event: TelegramMessageEvent,\n ): Promise<TelegramMessageEvent> {\n if (ctx.message?.voice === undefined) return event;\n const read = await readVoice(ctx, this.bot.token);\n if (\"audio\" in read) return { ...event, audio: read.audio };\n process.stderr.write(`[telegram] voice not read: ${read.reason}\\n`);\n return event;\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\n/**\n * The numeric id `editMessageText` takes, or `undefined` for one Telegram cannot have issued.\n *\n * Digits only, then a safe positive integer: `Number()` alone accepts `\" 42\"` and `\"0x10\"`, turns\n * `\"abc\"` into `NaN`, and rounds a digit string above 2^53 - 1 to a different id.\n */\nfunction parseMessageId(messageId: string): number | undefined {\n if (!/^\\d+$/.test(messageId)) return undefined;\n const id = Number(messageId);\n return Number.isSafeInteger(id) && id > 0 ? id : undefined;\n}\n\n/** Did Telegram refuse the edit because the message already shows this text? */\nfunction isNotModified(err: unknown): boolean {\n return (\n err instanceof GrammyError &&\n (err.description ?? \"\").toLowerCase().includes(\"message is not modified\")\n );\n}\n\n/**\n * The refusal for a text that is not exactly one Telegram message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForTelegram`\n * returns `[text]` for any text up to 4096 characters and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Telegram messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n","/**\n * Typed errors for `@theokit/gateway-telegram`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway\n * package's does, so `createChannels` reports a refused Telegram config as a rejected channel\n * rather than rethrowing it as a defect.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/**\n * Misconfiguration of the Telegram channel, raised before any network call.\n *\n * Carries a structured `code` the caller can branch on and, for a refused field, the field's key\n * in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it\n * is never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: GatewayConfigurationErrorOptions) {\n super(\"gateway-telegram\", opts);\n }\n}\n","/**\n * `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { TelegramAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-telegram: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\nfunction readToken(config: Readonly<Record<string, unknown>>): string {\n const token = config.token;\n if (typeof token !== \"string\") throw invalid(\"token\", \"a string\");\n if (token.length === 0) {\n // grammy's own `new Bot(\"\")` throws a plain Error, which `createChannels` would rethrow as a\n // defect instead of reporting the channel as rejected.\n throw new ConfigurationError({\n code: \"token_required\",\n message: \"gateway-telegram: config.token is empty\",\n detail: \"token\",\n });\n }\n return token;\n}\n\nfunction readAllowedUsers(config: Readonly<Record<string, unknown>>): string[] | undefined {\n const value = config.allowedUsers;\n if (value === undefined || value === null) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw invalid(\"allowedUsers\", \"an array of user id strings\");\n }\n return value;\n}\n\nfunction readRequireMention(config: Readonly<Record<string, unknown>>): boolean | undefined {\n const value = config.requireMention;\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"boolean\") throw invalid(\"requireMention\", \"a boolean\");\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"token\",\n required: true,\n secret: true,\n description: \"The bot token BotFather issued for this bot.\",\n },\n {\n key: \"allowedUsers\",\n required: false,\n secret: false,\n description: \"Telegram user ids allowed to reach the handler; absent or empty allows everyone.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description:\n \"When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false.\",\n },\n];\n\n/**\n * The Telegram channel: a long-polling bot, so it needs no webhook route.\n *\n * `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is\n * not an array of strings, with this package's `ConfigurationError`; it performs no network call.\n *\n * @public\n */\nexport const telegramChannel = {\n platform: \"telegram\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n const requireMention = readRequireMention(config);\n return new TelegramAdapter({\n token,\n ...(allowedUsers === undefined ? {} : { allowedUsers }),\n ...(requireMention === undefined ? {} : { requireMention }),\n });\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/group-policy.ts","../src/parse-inbound.ts","../src/read-voice.ts","../src/refuse-attachments.ts","../src/split.ts","../src/send-photos.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts"],"names":["InputFile","GrammyError","HttpError","BasePlatformAdapter","Bot","GatewayConfigurationError"],"mappings":";;;;;;;;AAuCO,SAAS,aAAA,CAAc,OAAoB,MAAA,EAAgC;AAChF,EAAA,IAAI,KAAA,CAAM,QAAA,KAAa,SAAA,EAAW,OAAO,IAAA;AACzC,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,UAAA,CAAW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AAA;AAAA,IACV,MAAA,EAAQ,IAAA;AAAA,IACR,WAAA,EAAa;AAAA,GACf;AAAA,EACA;AAAA,IACE,GAAA,EAAK,cAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EAAa;AAAA,GACf;AAAA,EACA;AAAA,IACE,GAAA,EAAK,gBAAA;AAAA,IACL,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,KAAA;AAAA,IACR,WAAA,EACE;AAAA;AAEN,CAAA;AAUO,IAAM,eAAA,GAAkB;AAAA,EAC7B,QAAA,EAAU,UAAA;AAAA,EACV,SAAA,EAAW,QAAA;AAAA,EACX,cAAA,EAAgB,eAAA;AAAA,EAChB,MAAA,EAAQ,MAAA;AAAA,EACR,OAAO,MAAA,EAA4D;AACjE,IAAA,MAAM,KAAA,GAAQ,UAAU,MAAM,CAAA;AAC9B,IAAA,MAAM,YAAA,GAAe,iBAAiB,MAAM,CAAA;AAC5C,IAAA,MAAM,cAAA,GAAiB,mBAAmB,MAAM,CAAA;AAChD,IAAA,OAAO,IAAI,eAAA,CAAgB;AAAA,MACzB,KAAA;AAAA,MACA,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,YAAA,EAAa;AAAA,MACrD,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA;AAAe,KAC1D,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/** The message facts the policy reads, as plain values (no grammy `Context`). */\nexport interface PolicyInput {\n /** Telegram chat type: `private`, `group`, `supergroup` or `channel`. */\n readonly chatType: string;\n /** Message text or caption; empty when there is none. */\n readonly text: string;\n /** Id of the sender of the message being replied to, when it is a reply. */\n readonly replyToFromId?: number | undefined;\n}\n\n/**\n * Decide from plain values whether the bot should respond. Works without a grammy `Context`.\n * @public\n */\nexport function shouldRespond(input: PolicyInput, policy: PolicyContext): boolean {\n if (input.chatType === \"private\") return true;\n if (input.text.startsWith(\"/\")) return true;\n if (input.replyToFromId !== undefined && input.replyToFromId === policy.botId) return true;\n return input.text.toLowerCase().includes(`@${policy.botUsername.toLowerCase()}`);\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n return shouldRespond(\n {\n chatType: chat.type,\n text: ctx.message?.text ?? ctx.message?.caption ?? \"\",\n replyToFromId: ctx.message?.reply_to_message?.from?.id,\n },\n policy,\n );\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n","/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Read the audio of a polled voice note (B-715, ADR D1).\n *\n * Telegram sends a voice note as a file id. The bytes take two requests: `getFile` for the file's\n * path, then a download from `https://api.telegram.org/file/bot<token>/<path>`. Only the polled\n * path holds the token, so the webhook `parseInbound` does not read voice notes.\n *\n * A failure is returned as a reason, never thrown: the caller delivers the event without audio and\n * writes the reason to stderr, so an unreadable voice leaves today's behaviour. No reason carries\n * the download URL, which contains the bot token.\n */\n\nimport type { InboundAudio } from \"@theokit/gateway\";\nimport type { Context } from \"grammy\";\n\n/** The largest voice read: Bot API `getFile` serves files of at most 20 MB. */\nconst MAX_VOICE_BYTES = 20 * 1024 * 1024;\n\n/** How long the whole read, `getFile` and download, may take before it is abandoned. */\nconst READ_TIMEOUT_MS = 30_000;\n\nconst DEFAULT_MEDIA_TYPE = \"audio/ogg\";\n\n/** What a read produced: the audio, or why there is none. */\ntype VoiceRead = { readonly audio: InboundAudio } | { readonly reason: string };\n\n/** The `fetch` this module calls; injected in tests so nothing reaches api.telegram.org. */\ntype FetchLike = (url: string, init: { signal: AbortSignal }) => Promise<Response>;\n\n/**\n * The voice object of the message, as far as this module reads it. Every field is `unknown`: a\n * hand-built update or a change on Telegram's side may send any of them in another shape (EC-2).\n */\ninterface VoiceFields {\n readonly file_id?: unknown;\n readonly duration?: unknown;\n readonly mime_type?: unknown;\n readonly file_size?: unknown;\n}\n\n/** A failure, named by the reason the caller writes to stderr. */\ntype Failure = { readonly reason: string };\n\n/**\n * Read the voice note of `ctx.message`. The caller calls this only when the message has a `voice`.\n */\nexport async function readVoice(\n ctx: Context,\n token: string,\n fetchImpl: FetchLike = fetch,\n): Promise<VoiceRead> {\n const voice = (ctx.message?.voice ?? {}) as VoiceFields;\n if (typeof voice.file_id !== \"string\") return { reason: \"no_file_id\" };\n if (typeof voice.file_size === \"number\" && voice.file_size > MAX_VOICE_BYTES) {\n return { reason: \"too_large\" };\n }\n // One deadline over both requests: a stalled getFile holds the polling handler, and every\n // later update, as surely as a stalled download (NFR-006).\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);\n try {\n const path = await filePath(ctx, controller.signal);\n if (typeof path !== \"string\") return path;\n const url = `https://api.telegram.org/file/bot${token}/${path}`;\n const bytes = await download(url, fetchImpl, controller.signal);\n if (!(bytes instanceof Uint8Array)) return bytes;\n return { audio: { data: bytes, ...voiceDetails(voice) } };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The media type and duration, each replaced by its default when it is not of its type. */\nfunction voiceDetails(voice: VoiceFields): { mediaType: string; durationSeconds: number } {\n const duration = voice.duration;\n return {\n mediaType: typeof voice.mime_type === \"string\" ? voice.mime_type : DEFAULT_MEDIA_TYPE,\n durationSeconds: typeof duration === \"number\" && Number.isFinite(duration) ? duration : 0,\n };\n}\n\n/** The file's path on Telegram's file server, or the reason it is not known. */\nasync function filePath(ctx: Context, signal: AbortSignal): Promise<string | Failure> {\n let file: { file_path?: string };\n try {\n // grammy types the signal with the abort-controller polyfill; a native one is what it reads.\n file = await ctx.getFile(signal as Parameters<Context[\"getFile\"]>[0]);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"get_file_failed\" };\n }\n return file.file_path ?? { reason: \"no_file_path\" };\n}\n\n/**\n * The downloaded bytes, or the reason the download failed.\n *\n * `signal` covers the body read too, not only the headers: a body that stalls after the headers\n * would otherwise hold the polling handler, and every later update, for good (EC-1).\n */\nasync function download(\n url: string,\n fetchImpl: FetchLike,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n try {\n const response = await fetchImpl(url, { signal });\n if (!response.ok) return { reason: `download_status_${response.status}` };\n if (response.body === null) return { reason: \"download_failed\" };\n return await readBounded(response.body, signal);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"download_failed\" };\n }\n}\n\n/** The whole body, `too_large` as soon as it passes the bound, or `timeout` when `signal` aborts. */\nasync function readBounded(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n const reader = body.getReader();\n const cancel = (): void => void reader.cancel().catch(() => undefined);\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n const chunks = await readChunks(reader);\n if (signal.aborted) return { reason: \"timeout\" };\n return chunks ?? { reason: \"too_large\" };\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\n/** The chunks joined into one array, or `undefined` once more than the bound has arrived. */\nasync function readChunks(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Promise<Uint8Array | undefined> {\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > MAX_VOICE_BYTES) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * Used by `editMessage` only: Telegram has no call that adds an image to a sent message, so an edit carrying one is refused rather than applied as text alone. `sendMessage` sends attachments through `send-photos.ts`.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"telegram adapter cannot attach to an edit\",\n },\n };\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\n/** The most characters one Telegram message carries; also the splitter window. */\nexport const TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = findBoundary(remaining);\n // B-556: a cut inside a table row that fits a chunk moves back to the row's start.\n const afterRow = takeRowSafe(parts, remaining, boundary);\n if (afterRow !== undefined) {\n remaining = afterRow;\n continue;\n }\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n const [piece, reopen] = closeFence(chunk);\n parts.push(piece);\n remaining = reopen + remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/** The paragraph, then line, then hard boundary within the safe window. */\nfunction findBoundary(remaining: string): number {\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;\n}\n\n/**\n * When `boundary` falls inside a table row that fits a chunk, pushes the part before the row and\n * returns the text from the row on; undefined otherwise.\n */\nfunction takeRowSafe(parts: string[], remaining: string, boundary: number): string | undefined {\n const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);\n if (moved === undefined) return undefined;\n const [piece, reopen] = closeFence(remaining.slice(0, moved.end));\n parts.push(piece);\n return reopen + remaining.slice(moved.start);\n}\n\n/** `\\n`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nconst isLineEnd = (ch: string | undefined): boolean => ch === \"\\n\" || ch === \"\\r\";\n\n/**\n * Where to cut instead of `cut` so a Markdown table row (a line whose first non-blank character is\n * `|`) it falls inside stays whole: `start` is the row's first character, `end` where the chunk\n * ends with its trailing line endings dropped. Undefined when `cut` is not inside a row, the row\n * opens the chunk, or the row is longer than `window`. The same rule is in core `chunkText`\n * (`keepTableRows`); this package keeps its own copy because it peers core `>=0.9.0`.\n */\nfunction rowSafeCut(\n text: string,\n cut: number,\n window: number,\n): { readonly end: number; readonly start: number } | undefined {\n const start = tableRowStart(text, cut);\n if (start === undefined || rowLength(text, start, cut, window) > window) return undefined;\n let end = start;\n while (end > 0 && isLineEnd(text[end - 1])) end -= 1;\n return end > 0 ? { end, start } : undefined;\n}\n\n/** Start of the table row `cut` falls inside, or undefined (not in a row, or the row opens the text). */\nfunction tableRowStart(text: string, cut: number): number | undefined {\n if (cut >= text.length || isLineEnd(text[cut])) return undefined;\n let start = cut;\n while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;\n return start > 0 && /^[^\\S\\r\\n]*\\|/.test(text.slice(start, cut + 1)) ? start : undefined;\n}\n\n/** Length of the row from `start`, scanning no further than `window` past it. */\nfunction rowLength(text: string, start: number, cut: number, window: number): number {\n let rowEnd = cut;\n while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;\n return rowEnd - start;\n}\n\n/** A fenced code line: 3+ backticks or tildes, up to 3 spaces of indent, then the info string. */\nconst FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;\n\ninterface Fence {\n readonly marker: string;\n readonly info: string;\n}\n\n/** Longest info string a reopened fence repeats, so the reopening cannot eat the chunk's headroom. */\nconst MAX_INFO = 40;\n\n/** The `[start, end)` ranges of `text` that lie inside fenced code, fence lines included. */\nfunction fencedRanges(text: string): Array<readonly [number, number]> {\n const ranges: Array<readonly [number, number]> = [];\n let open: OpenFence | undefined;\n let pos = 0;\n for (const line of text.split(\"\\n\")) {\n open = stepFence(open, line, pos, ranges);\n pos += line.length + 1;\n }\n if (open !== undefined) ranges.push([open.start, text.length]);\n return ranges;\n}\n\ninterface OpenFence {\n readonly fence: Fence;\n readonly start: number;\n}\n\n/** Folds one line into the fence state; a fence that closes on it is added to `ranges`. */\nfunction stepFence(\n open: OpenFence | undefined,\n line: string,\n pos: number,\n ranges: Array<readonly [number, number]>,\n): OpenFence | undefined {\n const m = FENCE_LINE.exec(line.replace(/\\r$/, \"\"));\n const marker = m?.[1];\n if (marker === undefined) return open;\n if (open === undefined) return { fence: { marker, info: (m?.[2] ?? \"\").trim() }, start: pos };\n if (!closesFence(open.fence, marker, m?.[2] ?? \"\")) return open;\n ranges.push([open.start, pos + line.length]);\n return undefined;\n}\n\nfunction closesFence(fence: Fence, marker: string, rest: string): boolean {\n return (\n marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === \"\"\n );\n}\n\n/** The fence still open at the end of `text`, if any. */\nfunction openFenceAt(text: string): Fence | undefined {\n const last = fencedRanges(text).at(-1);\n if (last === undefined || last[1] !== text.length) return undefined;\n const lines = text.slice(last[0]).split(\"\\n\");\n const opener = FENCE_LINE.exec(lines[0] ?? \"\");\n const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? \"\").replace(/\\r$/, \"\")) : null;\n if (opener?.[1] === undefined) return undefined;\n const fence = { marker: opener[1], info: (opener[2] ?? \"\").trim().slice(0, MAX_INFO) };\n if (closer?.[1] !== undefined && closesFence(fence, closer[1], closer[2] ?? \"\")) return undefined;\n return fence;\n}\n\n/**\n * B-526: a cut inside a fenced code block closes the fence at the end of the chunk and reopens it\n * at the start of the next. Returns the chunk and the text to put before the rest.\n */\nfunction closeFence(chunk: string): [string, string] {\n const open = openFenceAt(chunk);\n if (open === undefined) return [chunk, \"\"];\n return [`${chunk}\\n${open.marker}`, `${open.marker}${open.info}\\n`];\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing. Markers inside fenced code are not counted:\n * the fence is the chunk's business, not the markers within it.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const outside = markerIndexes(out, m);\n if (outside.length % 2 === 1) {\n out = out.slice(0, outside[outside.length - 1]).trimEnd();\n }\n }\n return out;\n}\n\n/** Indexes of `needle` in `text`, non-overlapping, skipping those inside fenced code. */\nfunction markerIndexes(text: string, needle: string): number[] {\n const ranges = fencedRanges(text);\n const found: number[] = [];\n let pos = 0;\n while (true) {\n const at = text.indexOf(needle, pos);\n if (at === -1) break;\n pos = at + needle.length;\n if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);\n }\n return found;\n}\n","/**\n * The attachment path of `TelegramAdapter.sendMessage`: one `sendPhoto` per image (B-674) and one\n * `sendVoice` per audio clip (B-715, ADR D2). The module keeps its photo name: one path for both\n * kinds means one caption rule, and a module of its own for voice would import the caption helpers\n * from here while this one imports it, a cycle.\n *\n * The text rides as the first attachment's caption when it is 1 to 1024 UTF-16 units. A longer text\n * gets no caption and follows the last photo through the same split as a text send, so nothing of\n * it is cut. Every attachment is checked before the first request, so a refusal makes no call.\n *\n * The module also holds how a send maps a declared format and a thrown grammy error, which\n * `TelegramAdapter` imports from here: both paths must answer them the same way, and keeping them\n * here rather than in `adapter.ts` avoids an import cycle.\n */\n\nimport type { OutboundAttachment, OutboundMessage, SendResult } from \"@theokit/gateway\";\nimport { type Api, GrammyError, HttpError, InputFile } from \"grammy\";\nimport { splitForTelegram } from \"./split.js\";\n\n/** Telegram's limit on a photo caption, in UTF-16 units (Bot API `sendPhoto`). */\nconst CAPTION_LIMIT = 1024;\n\n/** Telegram's limit on an uploaded photo: \"The photo must be at most 10 MB\" (Bot API `sendPhoto`). */\nconst MAX_PHOTO_BYTES = 10 * 1024 * 1024;\n\n/** Telegram's limit on a file a bot uploads, voice included: 50 MB (Bot API \"Sending files\"). */\nconst MAX_AUDIO_BYTES = 50 * 1024 * 1024;\n\n/** The bound on each kind's bytes, and the word a refusal uses for it. */\nconst KIND_LIMITS = {\n image: { maxBytes: MAX_PHOTO_BYTES, label: \"an image\", bound: \"10 MiB\" },\n audio: { maxBytes: MAX_AUDIO_BYTES, label: \"an audio\", bound: \"50 MiB\" },\n} as const;\n\n/**\n * The most images one send takes. Each image is a request, and a group chat takes about 20\n * messages a minute before Telegram answers 429; ten, the size of a `sendMediaGroup` album, leaves\n * room for the text that follows. A longer list is refused whole rather than cut off part way.\n */\nconst MAX_PHOTOS_PER_SEND = 10;\n\n/** Options every request of one send shares: the parse mode and the forum topic. */\ninterface SharedOptions {\n parse_mode?: \"Markdown\" | \"HTML\";\n message_thread_id?: number;\n}\n\n/**\n * Whether an outbound carries attachments to send. Absent, `null` and an empty list do not. `!== 0`,\n * not `> 0`: any other non-array value has no numeric length and is taken down the photo path,\n * where it is refused rather than dropped (EC-1).\n */\nexport function hasAttachments(out: OutboundMessage): boolean {\n return out.attachments != null && out.attachments.length !== 0;\n}\n\n/**\n * Send the images of `out` as photos, then the text when it is too long for a caption.\n *\n * Returns the id of the last message sent. A failure on photo k returns the mapped error at once,\n * and photos 1 to k-1 stay delivered: Telegram has no way to take them back as one unit.\n */\nexport async function sendPhotos(api: Api, out: OutboundMessage): Promise<SendResult> {\n const chatId = Number(out.channel.id);\n if (Number.isNaN(chatId)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const refusal = validateAttachments(out.attachments);\n if (refusal !== undefined) return refusal;\n const shared = sharedOptions(out);\n try {\n let lastId = await sendEachAttachment(api, chatId, out, shared);\n if (out.text.length > CAPTION_LIMIT) {\n for (const chunk of splitForTelegram(out.text)) {\n lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts)))\n .message_id;\n }\n }\n return { ok: true, messageId: String(lastId) };\n } catch (err) {\n return mapSendError(err);\n }\n}\n\n/**\n * One `sendPhoto` per image and one `sendVoice` per audio clip, in order; the caption and reply\n * target go on the first only, whatever its kind.\n */\nasync function sendEachAttachment(\n api: Api,\n chatId: number,\n out: OutboundMessage,\n shared: SharedOptions,\n): Promise<number> {\n const attachments = out.attachments as ReadonlyArray<OutboundAttachment>;\n const caption = captionOf(out.text);\n let lastId = 0;\n for (const [index, attachment] of attachments.entries()) {\n const options = { ...shared, ...(index === 0 ? firstPhotoOptions(out, caption) : {}) };\n const msg = await withPlainFallback<typeof options, { message_id: number }>(options, (opts) => {\n const file = new InputFile(attachment.data, attachment.filename);\n return attachment.kind === \"audio\"\n ? api.sendVoice(chatId, file, opts)\n : api.sendPhoto(chatId, file, opts);\n });\n lastId = msg.message_id;\n }\n return lastId;\n}\n\n/**\n * Run `send` with `options`. When Telegram refuses the legacy Markdown (`markdown_error`), write\n * one diagnostic line and run `send` once more without `parse_mode`. Any other failure, and a\n * failure of the resend, is rethrown for the caller's `mapSendError`.\n */\nexport async function withPlainFallback<O extends { parse_mode?: \"Markdown\" | \"HTML\" }, R>(\n options: O,\n send: (options: O) => Promise<R>,\n): Promise<R> {\n try {\n return await send(options);\n } catch (err) {\n if (options.parse_mode === undefined) throw err;\n const mapped = mapSendError(err);\n if (mapped.ok || mapped.error?.code !== \"markdown_error\") throw err;\n process.stderr.write(\n `[theokit-gateway-telegram] ${mapped.error.message}; resending as plain text\\n`,\n );\n const { parse_mode: _dropped, ...plain } = options;\n return send(plain as O);\n }\n}\n\n/** The text as a caption when it fits in 1 to 1024 units, otherwise none. */\nfunction captionOf(text: string): string | undefined {\n return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : undefined;\n}\n\n/** What only the first attachment carries: the caption and the message it replies to. */\nfunction firstPhotoOptions(\n out: OutboundMessage,\n caption: string | undefined,\n): { caption?: string; reply_parameters?: { message_id: number } } {\n return {\n ...(caption !== undefined ? { caption } : {}),\n ...(out.replyTo !== undefined ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}),\n };\n}\n\n/** The parse mode and the forum topic, applied to every request of the send. */\nfunction sharedOptions(out: OutboundMessage): SharedOptions {\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n return {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n };\n}\n\n/**\n * The refusal for an attachment list Telegram cannot send, or `undefined`.\n *\n * Not an array, more than ten attachments, an entry with no bytes or over its kind's bound (10 MiB\n * for an image, 50 MiB for audio), or audio whose media type is not `audio/*`:\n * `invalid_attachment`. A kind other than `image` or `audio`: `attachments_unsupported`, the code\n * every adapter answers for what it cannot attach. Every entry is checked before the first request,\n * so a refusal makes no call and never leaves part of the list delivered.\n */\nfunction validateAttachments(attachments: unknown): SendResult | undefined {\n if (!Array.isArray(attachments)) {\n return refuse(\"invalid_attachment\", \"attachments is not a list\");\n }\n if (attachments.length > MAX_PHOTOS_PER_SEND) {\n return refuse(\n \"invalid_attachment\",\n `telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`,\n );\n }\n for (const attachment of attachments as ReadonlyArray<OutboundAttachment | null>) {\n const refusal = validateAttachment(attachment);\n if (refusal !== undefined) return refusal;\n }\n return undefined;\n}\n\n/** The refusal for one entry of the list, or `undefined` when Telegram can send it. */\nfunction validateAttachment(attachment: OutboundAttachment | null): SendResult | undefined {\n if (typeof attachment !== \"object\" || attachment === null) {\n return refuse(\"invalid_attachment\", \"an attachment is not an object\");\n }\n if (attachment.kind !== \"image\" && attachment.kind !== \"audio\") {\n return refuse(\n \"attachments_unsupported\",\n \"telegram adapter sends only image and audio attachments\",\n );\n }\n const limit = KIND_LIMITS[attachment.kind];\n if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {\n return refuse(\"invalid_attachment\", `${limit.label} attachment has no bytes`);\n }\n if (attachment.data.length > limit.maxBytes) {\n return refuse(\n \"invalid_attachment\",\n `${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`,\n );\n }\n return mediaTypeRefusal(attachment);\n}\n\n/** Audio must declare an `audio/*` media type, in any case; an image's is not checked (B-674). */\nfunction mediaTypeRefusal(attachment: OutboundAttachment): SendResult | undefined {\n if (attachment.kind !== \"audio\") return undefined;\n const mediaType = typeof attachment.mediaType === \"string\" ? attachment.mediaType : \"\";\n if (mediaType.toLowerCase().startsWith(\"audio/\")) return undefined;\n return refuse(\"invalid_attachment\", `an audio attachment has media type \"${mediaType}\"`);\n}\n\nfunction refuse(code: string, message: string): SendResult {\n return { ok: false, error: { code, message } };\n}\n\n/** The `parse_mode` grammy takes for a declared format, or `undefined` for plain text. */\nexport function mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\n/** The `parse_mode` option for a declared format, or no option. */\nexport function parseModeOptions(format: OutboundMessage[\"format\"]): {\n parse_mode?: \"Markdown\" | \"HTML\";\n} {\n const parseMode = mapFormat(format);\n return parseMode !== undefined ? { parse_mode: parseMode } : {};\n}\n\nfunction mapGrammyError(err: GrammyError): SendResult {\n // A proxy or a non Bot API body can leave `description` undefined.\n const message = err.description ?? err.message;\n const description = message.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message } };\n }\n return { ok: false, error: { code: `telegram_${err.error_code ?? \"unknown\"}`, message } };\n}\n\n/** A thrown grammy error as a `SendResult`; never rethrows. */\nexport function mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) return mapGrammyError(err);\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError } from \"grammy\";\nimport { type PolicyInput, shouldRespond } from \"./group-policy.js\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { readVoice } from \"./read-voice.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport {\n hasAttachments,\n mapFormat,\n mapSendError,\n parseModeOptions,\n sendPhotos,\n withPlainFallback,\n} from \"./send-photos.js\";\nimport { splitForTelegram, TELEGRAM_MAX_MESSAGE } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n /**\n * How updates arrive. `\"polling\"` (default) pulls them with long polling; `\"webhook\"` only marks\n * the adapter connected, and updates arrive through `deliver()`.\n */\n readonly inbound?: \"polling\" | \"webhook\";\n /**\n * When true, a group or supergroup message reaches the handler only if it mentions the bot,\n * replies to one of the bot's messages, or is a slash command. Private chats always pass.\n * Default false (today's behaviour).\n */\n readonly requireMention?: boolean;\n}\n\nfunction isObj(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null;\n}\n\n/** The message facts the policy reads, from an event whose `raw` is a Context or an update. */\nfunction policyInput(event: GatewayMessageEvent): PolicyInput {\n const raw = (event as { telegram?: { raw?: unknown } }).telegram?.raw;\n const msg = isObj(raw) && isObj(raw.message) ? raw.message : undefined;\n const replyTo =\n msg !== undefined && isObj(msg.reply_to_message) ? msg.reply_to_message : undefined;\n const from = replyTo !== undefined && isObj(replyTo.from) ? replyTo.from : undefined;\n return {\n chatType: event.channel.type === \"dm\" ? \"private\" : \"group\",\n text: event.text,\n replyToFromId: typeof from?.id === \"number\" ? from.id : undefined,\n };\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates by default, so inbound needs no public URL.\n * With `inbound: \"webhook\"` it does not poll; updates arrive through `deliver()`.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: TELEGRAM_MAX_MESSAGE, threads: true };\n }\n\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private readonly inbound: \"polling\" | \"webhook\";\n private readonly requireMention: boolean;\n private warnedNoIdentity = false;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.inbound = opts.inbound ?? \"polling\";\n this.requireMention = opts.requireMention === true;\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n if (this.inbound === \"polling\")\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n if (this.inbound === \"webhook\") return;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // 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.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (hasAttachments(out)) return sendPhotos(this.bot.api, out);\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await withPlainFallback(\n {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n },\n (opts) => this.bot.api.sendMessage(chatIdNum, chunk, opts),\n );\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */\n override readonly supportsAttachments = true;\n\n /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */\n protected override readonly attachmentKinds = [\"image\", \"audio\"] as const;\n\n /** Telegram edits a sent message's text through `editMessageText`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, through `editMessageText`.\n *\n * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no\n * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,\n * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own\n * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit\n * replaces one message. Telegram's \"message is not modified\" refusal is answered as a success,\n * because the message already shows the text; a caller that treated it as a failure would send\n * the same text again as a second message.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const id = parseMessageId(messageId);\n if (id === undefined) {\n return {\n ok: false,\n error: {\n code: \"invalid_message_id\",\n message: `message id \"${messageId}\" is not a positive integer`,\n },\n };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parts = splitForTelegram(out.text);\n if (parts.length !== 1) return editPartsRefusal(parts.length);\n try {\n await this.bot.api.editMessageText(\n chatIdNum,\n id,\n parts[0] as string,\n parseModeOptions(out.format),\n );\n } catch (err) {\n if (!isNotModified(err)) return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n const chatId = Number(channelId);\n const id = parseMessageId(messageId);\n if (Number.isNaN(chatId) || id === undefined || emoji.length === 0) {\n return {\n ok: false,\n error: {\n code: \"invalid_reaction\",\n message: \"numeric channel, message id and emoji needed\",\n },\n };\n }\n try {\n // The emoji must be one of Telegram's allowed reactions; the API refuses others.\n await this.bot.api.setMessageReaction(chatId, id, [\n { type: \"emoji\", emoji } as unknown as Parameters<\n typeof this.bot.api.setMessageReaction\n >[2][number],\n ]);\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(await this.withVoice(ctx, event));\n }\n\n /** The `requireMention` gate, shared by the polled and webhook paths. */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (!this.requireMention || event.channel.type === \"dm\") return true;\n let me: { id: number; username?: string } | undefined;\n try {\n me = this.bot.botInfo;\n } catch {\n me = undefined;\n }\n if (me?.username === undefined) {\n if (!this.warnedNoIdentity) {\n this.warnedNoIdentity = true;\n process.stderr.write(\n \"[telegram] requireMention: bot identity not known yet; dropping group message\\n\",\n );\n }\n return false;\n }\n return shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });\n }\n\n /**\n * The event with the voice note's audio when the message has one (B-715, ADR D1).\n *\n * An unreadable voice leaves the event as it was and writes the reason to stderr: the message is\n * delivered either way, as it was before voice notes were read.\n */\n private async withVoice(\n ctx: Context,\n event: TelegramMessageEvent,\n ): Promise<TelegramMessageEvent> {\n if (ctx.message?.voice === undefined) return event;\n const read = await readVoice(ctx, this.bot.token);\n if (\"audio\" in read) return { ...event, audio: read.audio };\n process.stderr.write(`[telegram] voice not read: ${read.reason}\\n`);\n return event;\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\n/**\n * The numeric id `editMessageText` takes, or `undefined` for one Telegram cannot have issued.\n *\n * Digits only, then a safe positive integer: `Number()` alone accepts `\" 42\"` and `\"0x10\"`, turns\n * `\"abc\"` into `NaN`, and rounds a digit string above 2^53 - 1 to a different id.\n */\nfunction parseMessageId(messageId: string): number | undefined {\n if (!/^\\d+$/.test(messageId)) return undefined;\n const id = Number(messageId);\n return Number.isSafeInteger(id) && id > 0 ? id : undefined;\n}\n\n/** Did Telegram refuse the edit because the message already shows this text? */\nfunction isNotModified(err: unknown): boolean {\n return (\n err instanceof GrammyError &&\n (err.description ?? \"\").toLowerCase().includes(\"message is not modified\")\n );\n}\n\n/**\n * The refusal for a text that is not exactly one Telegram message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForTelegram`\n * returns `[text]` for any text up to 4096 characters and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Telegram messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n","/**\n * Typed errors for `@theokit/gateway-telegram`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway\n * package's does, so `createChannels` reports a refused Telegram config as a rejected channel\n * rather than rethrowing it as a defect.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/**\n * Misconfiguration of the Telegram channel, raised before any network call.\n *\n * Carries a structured `code` the caller can branch on and, for a refused field, the field's key\n * in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it\n * is never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: GatewayConfigurationErrorOptions) {\n super(\"gateway-telegram\", opts);\n }\n}\n","/**\n * `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { TelegramAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-telegram: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\nfunction readToken(config: Readonly<Record<string, unknown>>): string {\n const token = config.token;\n if (typeof token !== \"string\") throw invalid(\"token\", \"a string\");\n if (token.length === 0) {\n // grammy's own `new Bot(\"\")` throws a plain Error, which `createChannels` would rethrow as a\n // defect instead of reporting the channel as rejected.\n throw new ConfigurationError({\n code: \"token_required\",\n message: \"gateway-telegram: config.token is empty\",\n detail: \"token\",\n });\n }\n return token;\n}\n\nfunction readAllowedUsers(config: Readonly<Record<string, unknown>>): string[] | undefined {\n const value = config.allowedUsers;\n if (value === undefined || value === null) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw invalid(\"allowedUsers\", \"an array of user id strings\");\n }\n return value;\n}\n\nfunction readRequireMention(config: Readonly<Record<string, unknown>>): boolean | undefined {\n const value = config.requireMention;\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"boolean\") throw invalid(\"requireMention\", \"a boolean\");\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"token\",\n required: true,\n secret: true,\n description: \"The bot token BotFather issued for this bot.\",\n },\n {\n key: \"allowedUsers\",\n required: false,\n secret: false,\n description: \"Telegram user ids allowed to reach the handler; absent or empty allows everyone.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description:\n \"When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false.\",\n },\n];\n\n/**\n * The Telegram channel: a long-polling bot, so it needs no webhook route.\n *\n * `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is\n * not an array of strings, with this package's `ConfigurationError`; it performs no network call.\n *\n * @public\n */\nexport const telegramChannel = {\n platform: \"telegram\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n const requireMention = readRequireMention(config);\n return new TelegramAdapter({\n token,\n ...(allowedUsers === undefined ? {} : { allowedUsers }),\n ...(requireMention === undefined ? {} : { requireMention }),\n });\n },\n};\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from '@theokit/gateway';
2
2
  import { Bot, Context } from 'grammy';
3
3
 
4
4
  /**
@@ -48,6 +48,7 @@ interface TelegramAdapterOptions {
48
48
  * id therefore has to come from an inbound message, never from the token.
49
49
  */
50
50
  declare class TelegramAdapter extends BasePlatformAdapter {
51
+ get capabilities(): AdapterCapabilities;
51
52
  readonly platform: "telegram";
52
53
  private readonly bot;
53
54
  private readonly allowedUsers;
@@ -236,10 +237,6 @@ declare function stripBotMention(text: string, botUsername: string): string;
236
237
  */
237
238
  declare function parseInbound(payload: unknown): TelegramMessageEvent | null;
238
239
 
239
- /**
240
- * Telegram's 4096-char per-message cap. Split agent responses on safe
241
- * boundaries before sending (T5.1, with EC-J markdown-pair preservation).
242
- */
243
240
  /**
244
241
  * Split a long text into Telegram-sized chunks, preferring paragraph,
245
242
  * line, then hard boundaries. EC-J: when a chunk ends in the middle of
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from '@theokit/gateway';
1
+ import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from '@theokit/gateway';
2
2
  import { Bot, Context } from 'grammy';
3
3
 
4
4
  /**
@@ -48,6 +48,7 @@ interface TelegramAdapterOptions {
48
48
  * id therefore has to come from an inbound message, never from the token.
49
49
  */
50
50
  declare class TelegramAdapter extends BasePlatformAdapter {
51
+ get capabilities(): AdapterCapabilities;
51
52
  readonly platform: "telegram";
52
53
  private readonly bot;
53
54
  private readonly allowedUsers;
@@ -236,10 +237,6 @@ declare function stripBotMention(text: string, botUsername: string): string;
236
237
  */
237
238
  declare function parseInbound(payload: unknown): TelegramMessageEvent | null;
238
239
 
239
- /**
240
- * Telegram's 4096-char per-message cap. Split agent responses on safe
241
- * boundaries before sending (T5.1, with EC-J markdown-pair preservation).
242
- */
243
240
  /**
244
241
  * Split a long text into Telegram-sized chunks, preferring paragraph,
245
242
  * line, then hard boundaries. EC-J: when a chunk ends in the middle of
package/dist/index.js CHANGED
@@ -502,6 +502,9 @@ function policyInput(event) {
502
502
  };
503
503
  }
504
504
  var TelegramAdapter = class extends BasePlatformAdapter {
505
+ get capabilities() {
506
+ return { ...super.capabilities, maxMessageChars: TELEGRAM_MAX_MESSAGE, threads: true };
507
+ }
505
508
  platform = "telegram";
506
509
  bot;
507
510
  allowedUsers;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/group-policy.ts","../src/parse-inbound.ts","../src/read-voice.ts","../src/refuse-attachments.ts","../src/split.ts","../src/send-photos.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts"],"names":["GrammyError"],"mappings":";;;;;;AAuCO,SAAS,aAAA,CAAc,OAAoB,MAAA,EAAgC;AAChF,EAAA,IAAI,KAAA,CAAM,QAAA,KAAa,SAAA,EAAW,OAAO,IAAA;AACzC,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,UAAA,CAAW,GAAG,GAAG,OAAO,IAAA;AACvC,EAAA,IAAI,MAAM,aAAA,KAAkB,MAAA,IAAa,MAAM,aAAA,KAAkB,MAAA,CAAO,OAAO,OAAO,IAAA;AACtF,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,WAAA,EAAY,CAAE,QAAA,CAAS,IAAI,MAAA,CAAO,WAAA,CAAY,WAAA,EAAa,CAAA,CAAE,CAAA;AACjF;AAMO,SAAS,mBAAA,CAAoB,KAAc,MAAA,EAAgC;AAChF,EAAA,MAAM,OAAO,GAAA,CAAI,IAAA;AACjB,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,KAAA;AAC/B,EAAA,OA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CAAA;AAC9B,IAAA,MAAM,YAAA,GAAe,iBAAiB,MAAM,CAAA;AAC5C,IAAA,MAAM,cAAA,GAAiB,mBAAmB,MAAM,CAAA;AAChD,IAAA,OAAO,IAAI,eAAA,CAAgB;AAAA,MACzB,KAAA;AAAA,MACA,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,YAAA,EAAa;AAAA,MACrD,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA;AAAe,KAC1D,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/** The message facts the policy reads, as plain values (no grammy `Context`). */\nexport interface PolicyInput {\n /** Telegram chat type: `private`, `group`, `supergroup` or `channel`. */\n readonly chatType: string;\n /** Message text or caption; empty when there is none. */\n readonly text: string;\n /** Id of the sender of the message being replied to, when it is a reply. */\n readonly replyToFromId?: number | undefined;\n}\n\n/**\n * Decide from plain values whether the bot should respond. Works without a grammy `Context`.\n * @public\n */\nexport function shouldRespond(input: PolicyInput, policy: PolicyContext): boolean {\n if (input.chatType === \"private\") return true;\n if (input.text.startsWith(\"/\")) return true;\n if (input.replyToFromId !== undefined && input.replyToFromId === policy.botId) return true;\n return input.text.toLowerCase().includes(`@${policy.botUsername.toLowerCase()}`);\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n return shouldRespond(\n {\n chatType: chat.type,\n text: ctx.message?.text ?? ctx.message?.caption ?? \"\",\n replyToFromId: ctx.message?.reply_to_message?.from?.id,\n },\n policy,\n );\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n","/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Read the audio of a polled voice note (B-715, ADR D1).\n *\n * Telegram sends a voice note as a file id. The bytes take two requests: `getFile` for the file's\n * path, then a download from `https://api.telegram.org/file/bot<token>/<path>`. Only the polled\n * path holds the token, so the webhook `parseInbound` does not read voice notes.\n *\n * A failure is returned as a reason, never thrown: the caller delivers the event without audio and\n * writes the reason to stderr, so an unreadable voice leaves today's behaviour. No reason carries\n * the download URL, which contains the bot token.\n */\n\nimport type { InboundAudio } from \"@theokit/gateway\";\nimport type { Context } from \"grammy\";\n\n/** The largest voice read: Bot API `getFile` serves files of at most 20 MB. */\nconst MAX_VOICE_BYTES = 20 * 1024 * 1024;\n\n/** How long the whole read, `getFile` and download, may take before it is abandoned. */\nconst READ_TIMEOUT_MS = 30_000;\n\nconst DEFAULT_MEDIA_TYPE = \"audio/ogg\";\n\n/** What a read produced: the audio, or why there is none. */\ntype VoiceRead = { readonly audio: InboundAudio } | { readonly reason: string };\n\n/** The `fetch` this module calls; injected in tests so nothing reaches api.telegram.org. */\ntype FetchLike = (url: string, init: { signal: AbortSignal }) => Promise<Response>;\n\n/**\n * The voice object of the message, as far as this module reads it. Every field is `unknown`: a\n * hand-built update or a change on Telegram's side may send any of them in another shape (EC-2).\n */\ninterface VoiceFields {\n readonly file_id?: unknown;\n readonly duration?: unknown;\n readonly mime_type?: unknown;\n readonly file_size?: unknown;\n}\n\n/** A failure, named by the reason the caller writes to stderr. */\ntype Failure = { readonly reason: string };\n\n/**\n * Read the voice note of `ctx.message`. The caller calls this only when the message has a `voice`.\n */\nexport async function readVoice(\n ctx: Context,\n token: string,\n fetchImpl: FetchLike = fetch,\n): Promise<VoiceRead> {\n const voice = (ctx.message?.voice ?? {}) as VoiceFields;\n if (typeof voice.file_id !== \"string\") return { reason: \"no_file_id\" };\n if (typeof voice.file_size === \"number\" && voice.file_size > MAX_VOICE_BYTES) {\n return { reason: \"too_large\" };\n }\n // One deadline over both requests: a stalled getFile holds the polling handler, and every\n // later update, as surely as a stalled download (NFR-006).\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);\n try {\n const path = await filePath(ctx, controller.signal);\n if (typeof path !== \"string\") return path;\n const url = `https://api.telegram.org/file/bot${token}/${path}`;\n const bytes = await download(url, fetchImpl, controller.signal);\n if (!(bytes instanceof Uint8Array)) return bytes;\n return { audio: { data: bytes, ...voiceDetails(voice) } };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The media type and duration, each replaced by its default when it is not of its type. */\nfunction voiceDetails(voice: VoiceFields): { mediaType: string; durationSeconds: number } {\n const duration = voice.duration;\n return {\n mediaType: typeof voice.mime_type === \"string\" ? voice.mime_type : DEFAULT_MEDIA_TYPE,\n durationSeconds: typeof duration === \"number\" && Number.isFinite(duration) ? duration : 0,\n };\n}\n\n/** The file's path on Telegram's file server, or the reason it is not known. */\nasync function filePath(ctx: Context, signal: AbortSignal): Promise<string | Failure> {\n let file: { file_path?: string };\n try {\n // grammy types the signal with the abort-controller polyfill; a native one is what it reads.\n file = await ctx.getFile(signal as Parameters<Context[\"getFile\"]>[0]);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"get_file_failed\" };\n }\n return file.file_path ?? { reason: \"no_file_path\" };\n}\n\n/**\n * The downloaded bytes, or the reason the download failed.\n *\n * `signal` covers the body read too, not only the headers: a body that stalls after the headers\n * would otherwise hold the polling handler, and every later update, for good (EC-1).\n */\nasync function download(\n url: string,\n fetchImpl: FetchLike,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n try {\n const response = await fetchImpl(url, { signal });\n if (!response.ok) return { reason: `download_status_${response.status}` };\n if (response.body === null) return { reason: \"download_failed\" };\n return await readBounded(response.body, signal);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"download_failed\" };\n }\n}\n\n/** The whole body, `too_large` as soon as it passes the bound, or `timeout` when `signal` aborts. */\nasync function readBounded(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n const reader = body.getReader();\n const cancel = (): void => void reader.cancel().catch(() => undefined);\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n const chunks = await readChunks(reader);\n if (signal.aborted) return { reason: \"timeout\" };\n return chunks ?? { reason: \"too_large\" };\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\n/** The chunks joined into one array, or `undefined` once more than the bound has arrived. */\nasync function readChunks(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Promise<Uint8Array | undefined> {\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > MAX_VOICE_BYTES) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * Used by `editMessage` only: Telegram has no call that adds an image to a sent message, so an edit carrying one is refused rather than applied as text alone. `sendMessage` sends attachments through `send-photos.ts`.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"telegram adapter cannot attach to an edit\",\n },\n };\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\nconst TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = findBoundary(remaining);\n // B-556: a cut inside a table row that fits a chunk moves back to the row's start.\n const afterRow = takeRowSafe(parts, remaining, boundary);\n if (afterRow !== undefined) {\n remaining = afterRow;\n continue;\n }\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n const [piece, reopen] = closeFence(chunk);\n parts.push(piece);\n remaining = reopen + remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/** The paragraph, then line, then hard boundary within the safe window. */\nfunction findBoundary(remaining: string): number {\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;\n}\n\n/**\n * When `boundary` falls inside a table row that fits a chunk, pushes the part before the row and\n * returns the text from the row on; undefined otherwise.\n */\nfunction takeRowSafe(parts: string[], remaining: string, boundary: number): string | undefined {\n const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);\n if (moved === undefined) return undefined;\n const [piece, reopen] = closeFence(remaining.slice(0, moved.end));\n parts.push(piece);\n return reopen + remaining.slice(moved.start);\n}\n\n/** `\\n`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nconst isLineEnd = (ch: string | undefined): boolean => ch === \"\\n\" || ch === \"\\r\";\n\n/**\n * Where to cut instead of `cut` so a Markdown table row (a line whose first non-blank character is\n * `|`) it falls inside stays whole: `start` is the row's first character, `end` where the chunk\n * ends with its trailing line endings dropped. Undefined when `cut` is not inside a row, the row\n * opens the chunk, or the row is longer than `window`. The same rule is in core `chunkText`\n * (`keepTableRows`); this package keeps its own copy because it peers core `>=0.9.0`.\n */\nfunction rowSafeCut(\n text: string,\n cut: number,\n window: number,\n): { readonly end: number; readonly start: number } | undefined {\n const start = tableRowStart(text, cut);\n if (start === undefined || rowLength(text, start, cut, window) > window) return undefined;\n let end = start;\n while (end > 0 && isLineEnd(text[end - 1])) end -= 1;\n return end > 0 ? { end, start } : undefined;\n}\n\n/** Start of the table row `cut` falls inside, or undefined (not in a row, or the row opens the text). */\nfunction tableRowStart(text: string, cut: number): number | undefined {\n if (cut >= text.length || isLineEnd(text[cut])) return undefined;\n let start = cut;\n while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;\n return start > 0 && /^[^\\S\\r\\n]*\\|/.test(text.slice(start, cut + 1)) ? start : undefined;\n}\n\n/** Length of the row from `start`, scanning no further than `window` past it. */\nfunction rowLength(text: string, start: number, cut: number, window: number): number {\n let rowEnd = cut;\n while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;\n return rowEnd - start;\n}\n\n/** A fenced code line: 3+ backticks or tildes, up to 3 spaces of indent, then the info string. */\nconst FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;\n\ninterface Fence {\n readonly marker: string;\n readonly info: string;\n}\n\n/** Longest info string a reopened fence repeats, so the reopening cannot eat the chunk's headroom. */\nconst MAX_INFO = 40;\n\n/** The `[start, end)` ranges of `text` that lie inside fenced code, fence lines included. */\nfunction fencedRanges(text: string): Array<readonly [number, number]> {\n const ranges: Array<readonly [number, number]> = [];\n let open: OpenFence | undefined;\n let pos = 0;\n for (const line of text.split(\"\\n\")) {\n open = stepFence(open, line, pos, ranges);\n pos += line.length + 1;\n }\n if (open !== undefined) ranges.push([open.start, text.length]);\n return ranges;\n}\n\ninterface OpenFence {\n readonly fence: Fence;\n readonly start: number;\n}\n\n/** Folds one line into the fence state; a fence that closes on it is added to `ranges`. */\nfunction stepFence(\n open: OpenFence | undefined,\n line: string,\n pos: number,\n ranges: Array<readonly [number, number]>,\n): OpenFence | undefined {\n const m = FENCE_LINE.exec(line.replace(/\\r$/, \"\"));\n const marker = m?.[1];\n if (marker === undefined) return open;\n if (open === undefined) return { fence: { marker, info: (m?.[2] ?? \"\").trim() }, start: pos };\n if (!closesFence(open.fence, marker, m?.[2] ?? \"\")) return open;\n ranges.push([open.start, pos + line.length]);\n return undefined;\n}\n\nfunction closesFence(fence: Fence, marker: string, rest: string): boolean {\n return (\n marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === \"\"\n );\n}\n\n/** The fence still open at the end of `text`, if any. */\nfunction openFenceAt(text: string): Fence | undefined {\n const last = fencedRanges(text).at(-1);\n if (last === undefined || last[1] !== text.length) return undefined;\n const lines = text.slice(last[0]).split(\"\\n\");\n const opener = FENCE_LINE.exec(lines[0] ?? \"\");\n const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? \"\").replace(/\\r$/, \"\")) : null;\n if (opener?.[1] === undefined) return undefined;\n const fence = { marker: opener[1], info: (opener[2] ?? \"\").trim().slice(0, MAX_INFO) };\n if (closer?.[1] !== undefined && closesFence(fence, closer[1], closer[2] ?? \"\")) return undefined;\n return fence;\n}\n\n/**\n * B-526: a cut inside a fenced code block closes the fence at the end of the chunk and reopens it\n * at the start of the next. Returns the chunk and the text to put before the rest.\n */\nfunction closeFence(chunk: string): [string, string] {\n const open = openFenceAt(chunk);\n if (open === undefined) return [chunk, \"\"];\n return [`${chunk}\\n${open.marker}`, `${open.marker}${open.info}\\n`];\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing. Markers inside fenced code are not counted:\n * the fence is the chunk's business, not the markers within it.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const outside = markerIndexes(out, m);\n if (outside.length % 2 === 1) {\n out = out.slice(0, outside[outside.length - 1]).trimEnd();\n }\n }\n return out;\n}\n\n/** Indexes of `needle` in `text`, non-overlapping, skipping those inside fenced code. */\nfunction markerIndexes(text: string, needle: string): number[] {\n const ranges = fencedRanges(text);\n const found: number[] = [];\n let pos = 0;\n while (true) {\n const at = text.indexOf(needle, pos);\n if (at === -1) break;\n pos = at + needle.length;\n if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);\n }\n return found;\n}\n","/**\n * The attachment path of `TelegramAdapter.sendMessage`: one `sendPhoto` per image (B-674) and one\n * `sendVoice` per audio clip (B-715, ADR D2). The module keeps its photo name: one path for both\n * kinds means one caption rule, and a module of its own for voice would import the caption helpers\n * from here while this one imports it, a cycle.\n *\n * The text rides as the first attachment's caption when it is 1 to 1024 UTF-16 units. A longer text\n * gets no caption and follows the last photo through the same split as a text send, so nothing of\n * it is cut. Every attachment is checked before the first request, so a refusal makes no call.\n *\n * The module also holds how a send maps a declared format and a thrown grammy error, which\n * `TelegramAdapter` imports from here: both paths must answer them the same way, and keeping them\n * here rather than in `adapter.ts` avoids an import cycle.\n */\n\nimport type { OutboundAttachment, OutboundMessage, SendResult } from \"@theokit/gateway\";\nimport { type Api, GrammyError, HttpError, InputFile } from \"grammy\";\nimport { splitForTelegram } from \"./split.js\";\n\n/** Telegram's limit on a photo caption, in UTF-16 units (Bot API `sendPhoto`). */\nconst CAPTION_LIMIT = 1024;\n\n/** Telegram's limit on an uploaded photo: \"The photo must be at most 10 MB\" (Bot API `sendPhoto`). */\nconst MAX_PHOTO_BYTES = 10 * 1024 * 1024;\n\n/** Telegram's limit on a file a bot uploads, voice included: 50 MB (Bot API \"Sending files\"). */\nconst MAX_AUDIO_BYTES = 50 * 1024 * 1024;\n\n/** The bound on each kind's bytes, and the word a refusal uses for it. */\nconst KIND_LIMITS = {\n image: { maxBytes: MAX_PHOTO_BYTES, label: \"an image\", bound: \"10 MiB\" },\n audio: { maxBytes: MAX_AUDIO_BYTES, label: \"an audio\", bound: \"50 MiB\" },\n} as const;\n\n/**\n * The most images one send takes. Each image is a request, and a group chat takes about 20\n * messages a minute before Telegram answers 429; ten, the size of a `sendMediaGroup` album, leaves\n * room for the text that follows. A longer list is refused whole rather than cut off part way.\n */\nconst MAX_PHOTOS_PER_SEND = 10;\n\n/** Options every request of one send shares: the parse mode and the forum topic. */\ninterface SharedOptions {\n parse_mode?: \"Markdown\" | \"HTML\";\n message_thread_id?: number;\n}\n\n/**\n * Whether an outbound carries attachments to send. Absent, `null` and an empty list do not. `!== 0`,\n * not `> 0`: any other non-array value has no numeric length and is taken down the photo path,\n * where it is refused rather than dropped (EC-1).\n */\nexport function hasAttachments(out: OutboundMessage): boolean {\n return out.attachments != null && out.attachments.length !== 0;\n}\n\n/**\n * Send the images of `out` as photos, then the text when it is too long for a caption.\n *\n * Returns the id of the last message sent. A failure on photo k returns the mapped error at once,\n * and photos 1 to k-1 stay delivered: Telegram has no way to take them back as one unit.\n */\nexport async function sendPhotos(api: Api, out: OutboundMessage): Promise<SendResult> {\n const chatId = Number(out.channel.id);\n if (Number.isNaN(chatId)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const refusal = validateAttachments(out.attachments);\n if (refusal !== undefined) return refusal;\n const shared = sharedOptions(out);\n try {\n let lastId = await sendEachAttachment(api, chatId, out, shared);\n if (out.text.length > CAPTION_LIMIT) {\n for (const chunk of splitForTelegram(out.text)) {\n lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts)))\n .message_id;\n }\n }\n return { ok: true, messageId: String(lastId) };\n } catch (err) {\n return mapSendError(err);\n }\n}\n\n/**\n * One `sendPhoto` per image and one `sendVoice` per audio clip, in order; the caption and reply\n * target go on the first only, whatever its kind.\n */\nasync function sendEachAttachment(\n api: Api,\n chatId: number,\n out: OutboundMessage,\n shared: SharedOptions,\n): Promise<number> {\n const attachments = out.attachments as ReadonlyArray<OutboundAttachment>;\n const caption = captionOf(out.text);\n let lastId = 0;\n for (const [index, attachment] of attachments.entries()) {\n const options = { ...shared, ...(index === 0 ? firstPhotoOptions(out, caption) : {}) };\n const msg = await withPlainFallback<typeof options, { message_id: number }>(options, (opts) => {\n const file = new InputFile(attachment.data, attachment.filename);\n return attachment.kind === \"audio\"\n ? api.sendVoice(chatId, file, opts)\n : api.sendPhoto(chatId, file, opts);\n });\n lastId = msg.message_id;\n }\n return lastId;\n}\n\n/**\n * Run `send` with `options`. When Telegram refuses the legacy Markdown (`markdown_error`), write\n * one diagnostic line and run `send` once more without `parse_mode`. Any other failure, and a\n * failure of the resend, is rethrown for the caller's `mapSendError`.\n */\nexport async function withPlainFallback<O extends { parse_mode?: \"Markdown\" | \"HTML\" }, R>(\n options: O,\n send: (options: O) => Promise<R>,\n): Promise<R> {\n try {\n return await send(options);\n } catch (err) {\n if (options.parse_mode === undefined) throw err;\n const mapped = mapSendError(err);\n if (mapped.ok || mapped.error?.code !== \"markdown_error\") throw err;\n process.stderr.write(\n `[theokit-gateway-telegram] ${mapped.error.message}; resending as plain text\\n`,\n );\n const { parse_mode: _dropped, ...plain } = options;\n return send(plain as O);\n }\n}\n\n/** The text as a caption when it fits in 1 to 1024 units, otherwise none. */\nfunction captionOf(text: string): string | undefined {\n return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : undefined;\n}\n\n/** What only the first attachment carries: the caption and the message it replies to. */\nfunction firstPhotoOptions(\n out: OutboundMessage,\n caption: string | undefined,\n): { caption?: string; reply_parameters?: { message_id: number } } {\n return {\n ...(caption !== undefined ? { caption } : {}),\n ...(out.replyTo !== undefined ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}),\n };\n}\n\n/** The parse mode and the forum topic, applied to every request of the send. */\nfunction sharedOptions(out: OutboundMessage): SharedOptions {\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n return {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n };\n}\n\n/**\n * The refusal for an attachment list Telegram cannot send, or `undefined`.\n *\n * Not an array, more than ten attachments, an entry with no bytes or over its kind's bound (10 MiB\n * for an image, 50 MiB for audio), or audio whose media type is not `audio/*`:\n * `invalid_attachment`. A kind other than `image` or `audio`: `attachments_unsupported`, the code\n * every adapter answers for what it cannot attach. Every entry is checked before the first request,\n * so a refusal makes no call and never leaves part of the list delivered.\n */\nfunction validateAttachments(attachments: unknown): SendResult | undefined {\n if (!Array.isArray(attachments)) {\n return refuse(\"invalid_attachment\", \"attachments is not a list\");\n }\n if (attachments.length > MAX_PHOTOS_PER_SEND) {\n return refuse(\n \"invalid_attachment\",\n `telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`,\n );\n }\n for (const attachment of attachments as ReadonlyArray<OutboundAttachment | null>) {\n const refusal = validateAttachment(attachment);\n if (refusal !== undefined) return refusal;\n }\n return undefined;\n}\n\n/** The refusal for one entry of the list, or `undefined` when Telegram can send it. */\nfunction validateAttachment(attachment: OutboundAttachment | null): SendResult | undefined {\n if (typeof attachment !== \"object\" || attachment === null) {\n return refuse(\"invalid_attachment\", \"an attachment is not an object\");\n }\n if (attachment.kind !== \"image\" && attachment.kind !== \"audio\") {\n return refuse(\n \"attachments_unsupported\",\n \"telegram adapter sends only image and audio attachments\",\n );\n }\n const limit = KIND_LIMITS[attachment.kind];\n if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {\n return refuse(\"invalid_attachment\", `${limit.label} attachment has no bytes`);\n }\n if (attachment.data.length > limit.maxBytes) {\n return refuse(\n \"invalid_attachment\",\n `${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`,\n );\n }\n return mediaTypeRefusal(attachment);\n}\n\n/** Audio must declare an `audio/*` media type, in any case; an image's is not checked (B-674). */\nfunction mediaTypeRefusal(attachment: OutboundAttachment): SendResult | undefined {\n if (attachment.kind !== \"audio\") return undefined;\n const mediaType = typeof attachment.mediaType === \"string\" ? attachment.mediaType : \"\";\n if (mediaType.toLowerCase().startsWith(\"audio/\")) return undefined;\n return refuse(\"invalid_attachment\", `an audio attachment has media type \"${mediaType}\"`);\n}\n\nfunction refuse(code: string, message: string): SendResult {\n return { ok: false, error: { code, message } };\n}\n\n/** The `parse_mode` grammy takes for a declared format, or `undefined` for plain text. */\nexport function mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\n/** The `parse_mode` option for a declared format, or no option. */\nexport function parseModeOptions(format: OutboundMessage[\"format\"]): {\n parse_mode?: \"Markdown\" | \"HTML\";\n} {\n const parseMode = mapFormat(format);\n return parseMode !== undefined ? { parse_mode: parseMode } : {};\n}\n\nfunction mapGrammyError(err: GrammyError): SendResult {\n // A proxy or a non Bot API body can leave `description` undefined.\n const message = err.description ?? err.message;\n const description = message.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message } };\n }\n return { ok: false, error: { code: `telegram_${err.error_code ?? \"unknown\"}`, message } };\n}\n\n/** A thrown grammy error as a `SendResult`; never rethrows. */\nexport function mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) return mapGrammyError(err);\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError } from \"grammy\";\nimport { type PolicyInput, shouldRespond } from \"./group-policy.js\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { readVoice } from \"./read-voice.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport {\n hasAttachments,\n mapFormat,\n mapSendError,\n parseModeOptions,\n sendPhotos,\n withPlainFallback,\n} from \"./send-photos.js\";\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n /**\n * How updates arrive. `\"polling\"` (default) pulls them with long polling; `\"webhook\"` only marks\n * the adapter connected, and updates arrive through `deliver()`.\n */\n readonly inbound?: \"polling\" | \"webhook\";\n /**\n * When true, a group or supergroup message reaches the handler only if it mentions the bot,\n * replies to one of the bot's messages, or is a slash command. Private chats always pass.\n * Default false (today's behaviour).\n */\n readonly requireMention?: boolean;\n}\n\nfunction isObj(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null;\n}\n\n/** The message facts the policy reads, from an event whose `raw` is a Context or an update. */\nfunction policyInput(event: GatewayMessageEvent): PolicyInput {\n const raw = (event as { telegram?: { raw?: unknown } }).telegram?.raw;\n const msg = isObj(raw) && isObj(raw.message) ? raw.message : undefined;\n const replyTo =\n msg !== undefined && isObj(msg.reply_to_message) ? msg.reply_to_message : undefined;\n const from = replyTo !== undefined && isObj(replyTo.from) ? replyTo.from : undefined;\n return {\n chatType: event.channel.type === \"dm\" ? \"private\" : \"group\",\n text: event.text,\n replyToFromId: typeof from?.id === \"number\" ? from.id : undefined,\n };\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates by default, so inbound needs no public URL.\n * With `inbound: \"webhook\"` it does not poll; updates arrive through `deliver()`.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private readonly inbound: \"polling\" | \"webhook\";\n private readonly requireMention: boolean;\n private warnedNoIdentity = false;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.inbound = opts.inbound ?? \"polling\";\n this.requireMention = opts.requireMention === true;\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n if (this.inbound === \"polling\")\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n if (this.inbound === \"webhook\") return;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // 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.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (hasAttachments(out)) return sendPhotos(this.bot.api, out);\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await withPlainFallback(\n {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n },\n (opts) => this.bot.api.sendMessage(chatIdNum, chunk, opts),\n );\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */\n override readonly supportsAttachments = true;\n\n /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */\n protected override readonly attachmentKinds = [\"image\", \"audio\"] as const;\n\n /** Telegram edits a sent message's text through `editMessageText`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, through `editMessageText`.\n *\n * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no\n * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,\n * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own\n * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit\n * replaces one message. Telegram's \"message is not modified\" refusal is answered as a success,\n * because the message already shows the text; a caller that treated it as a failure would send\n * the same text again as a second message.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const id = parseMessageId(messageId);\n if (id === undefined) {\n return {\n ok: false,\n error: {\n code: \"invalid_message_id\",\n message: `message id \"${messageId}\" is not a positive integer`,\n },\n };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parts = splitForTelegram(out.text);\n if (parts.length !== 1) return editPartsRefusal(parts.length);\n try {\n await this.bot.api.editMessageText(\n chatIdNum,\n id,\n parts[0] as string,\n parseModeOptions(out.format),\n );\n } catch (err) {\n if (!isNotModified(err)) return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n const chatId = Number(channelId);\n const id = parseMessageId(messageId);\n if (Number.isNaN(chatId) || id === undefined || emoji.length === 0) {\n return {\n ok: false,\n error: {\n code: \"invalid_reaction\",\n message: \"numeric channel, message id and emoji needed\",\n },\n };\n }\n try {\n // The emoji must be one of Telegram's allowed reactions; the API refuses others.\n await this.bot.api.setMessageReaction(chatId, id, [\n { type: \"emoji\", emoji } as unknown as Parameters<\n typeof this.bot.api.setMessageReaction\n >[2][number],\n ]);\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(await this.withVoice(ctx, event));\n }\n\n /** The `requireMention` gate, shared by the polled and webhook paths. */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (!this.requireMention || event.channel.type === \"dm\") return true;\n let me: { id: number; username?: string } | undefined;\n try {\n me = this.bot.botInfo;\n } catch {\n me = undefined;\n }\n if (me?.username === undefined) {\n if (!this.warnedNoIdentity) {\n this.warnedNoIdentity = true;\n process.stderr.write(\n \"[telegram] requireMention: bot identity not known yet; dropping group message\\n\",\n );\n }\n return false;\n }\n return shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });\n }\n\n /**\n * The event with the voice note's audio when the message has one (B-715, ADR D1).\n *\n * An unreadable voice leaves the event as it was and writes the reason to stderr: the message is\n * delivered either way, as it was before voice notes were read.\n */\n private async withVoice(\n ctx: Context,\n event: TelegramMessageEvent,\n ): Promise<TelegramMessageEvent> {\n if (ctx.message?.voice === undefined) return event;\n const read = await readVoice(ctx, this.bot.token);\n if (\"audio\" in read) return { ...event, audio: read.audio };\n process.stderr.write(`[telegram] voice not read: ${read.reason}\\n`);\n return event;\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\n/**\n * The numeric id `editMessageText` takes, or `undefined` for one Telegram cannot have issued.\n *\n * Digits only, then a safe positive integer: `Number()` alone accepts `\" 42\"` and `\"0x10\"`, turns\n * `\"abc\"` into `NaN`, and rounds a digit string above 2^53 - 1 to a different id.\n */\nfunction parseMessageId(messageId: string): number | undefined {\n if (!/^\\d+$/.test(messageId)) return undefined;\n const id = Number(messageId);\n return Number.isSafeInteger(id) && id > 0 ? id : undefined;\n}\n\n/** Did Telegram refuse the edit because the message already shows this text? */\nfunction isNotModified(err: unknown): boolean {\n return (\n err instanceof GrammyError &&\n (err.description ?? \"\").toLowerCase().includes(\"message is not modified\")\n );\n}\n\n/**\n * The refusal for a text that is not exactly one Telegram message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForTelegram`\n * returns `[text]` for any text up to 4096 characters and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Telegram messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n","/**\n * Typed errors for `@theokit/gateway-telegram`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway\n * package's does, so `createChannels` reports a refused Telegram config as a rejected channel\n * rather than rethrowing it as a defect.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/**\n * Misconfiguration of the Telegram channel, raised before any network call.\n *\n * Carries a structured `code` the caller can branch on and, for a refused field, the field's key\n * in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it\n * is never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: GatewayConfigurationErrorOptions) {\n super(\"gateway-telegram\", opts);\n }\n}\n","/**\n * `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { TelegramAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-telegram: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\nfunction readToken(config: Readonly<Record<string, unknown>>): string {\n const token = config.token;\n if (typeof token !== \"string\") throw invalid(\"token\", \"a string\");\n if (token.length === 0) {\n // grammy's own `new Bot(\"\")` throws a plain Error, which `createChannels` would rethrow as a\n // defect instead of reporting the channel as rejected.\n throw new ConfigurationError({\n code: \"token_required\",\n message: \"gateway-telegram: config.token is empty\",\n detail: \"token\",\n });\n }\n return token;\n}\n\nfunction readAllowedUsers(config: Readonly<Record<string, unknown>>): string[] | undefined {\n const value = config.allowedUsers;\n if (value === undefined || value === null) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw invalid(\"allowedUsers\", \"an array of user id strings\");\n }\n return value;\n}\n\nfunction readRequireMention(config: Readonly<Record<string, unknown>>): boolean | undefined {\n const value = config.requireMention;\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"boolean\") throw invalid(\"requireMention\", \"a boolean\");\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"token\",\n required: true,\n secret: true,\n description: \"The bot token BotFather issued for this bot.\",\n },\n {\n key: \"allowedUsers\",\n required: false,\n secret: false,\n description: \"Telegram user ids allowed to reach the handler; absent or empty allows everyone.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description:\n \"When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false.\",\n },\n];\n\n/**\n * The Telegram channel: a long-polling bot, so it needs no webhook route.\n *\n * `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is\n * not an array of strings, with this package's `ConfigurationError`; it performs no network call.\n *\n * @public\n */\nexport const telegramChannel = {\n platform: \"telegram\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n const requireMention = readRequireMention(config);\n return new TelegramAdapter({\n token,\n ...(allowedUsers === undefined ? {} : { allowedUsers }),\n ...(requireMention === undefined ? {} : { requireMention }),\n });\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/group-policy.ts","../src/parse-inbound.ts","../src/read-voice.ts","../src/refuse-attachments.ts","../src/split.ts","../src/send-photos.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts"],"names":["GrammyError"],"mappings":";;;;;;AAuCO,SAAS,aAAA,CAAc,OAAoB,MAAA,EAAgC;AAChF,EAAA,IAAI,KAAA,CAAM,QAAA,KAAa,SAAA,EAAW,OAAO,IAAA;AACzC,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,UAAA,CAAW,GAAG,GAAG,OAAO,IAAA;AACvC,EAAA,IAAI,MAAM,aAAA,KAAkB,MAAA,IAAa,MAAM,aAAA,KAAkB,MAAA,CAAO,OAAO,OAAO,IAAA;AACtF,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,WAAA,EAAY,CAAE,QAAA,CAAS,IAAI,MAAA,CAAO,WAAA,CAAY,WAAA,EAAa,CAAA,CAAE,CAAA;AACjF;AAMO,SAAS,mBAAA,CAAoB,KAAc,MAAA,EAAgC;AAChF,EAAA,MAAM,OAAO,GAAA,CAAI,IAAA;AACjB,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,KAAA;AAC/B,EAAA,OAAO,aAAA;AAAA,IACL;AAAA,MACE,UAAU,IAAA,CAAK,IAAA;AAAA,MACf,MAAM,GAAA,CAAI,OA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AA4D;AACjE,IAAA,MAAM,KAAA,GAAQ,UAAU,MAAM,CAAA;AAC9B,IAAA,MAAM,YAAA,GAAe,iBAAiB,MAAM,CAAA;AAC5C,IAAA,MAAM,cAAA,GAAiB,mBAAmB,MAAM,CAAA;AAChD,IAAA,OAAO,IAAI,eAAA,CAAgB;AAAA,MACzB,KAAA;AAAA,MACA,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,YAAA,EAAa;AAAA,MACrD,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAC,GAAI,EAAE,cAAA;AAAe,KAC1D,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/** The message facts the policy reads, as plain values (no grammy `Context`). */\nexport interface PolicyInput {\n /** Telegram chat type: `private`, `group`, `supergroup` or `channel`. */\n readonly chatType: string;\n /** Message text or caption; empty when there is none. */\n readonly text: string;\n /** Id of the sender of the message being replied to, when it is a reply. */\n readonly replyToFromId?: number | undefined;\n}\n\n/**\n * Decide from plain values whether the bot should respond. Works without a grammy `Context`.\n * @public\n */\nexport function shouldRespond(input: PolicyInput, policy: PolicyContext): boolean {\n if (input.chatType === \"private\") return true;\n if (input.text.startsWith(\"/\")) return true;\n if (input.replyToFromId !== undefined && input.replyToFromId === policy.botId) return true;\n return input.text.toLowerCase().includes(`@${policy.botUsername.toLowerCase()}`);\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n return shouldRespond(\n {\n chatType: chat.type,\n text: ctx.message?.text ?? ctx.message?.caption ?? \"\",\n replyToFromId: ctx.message?.reply_to_message?.from?.id,\n },\n policy,\n );\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n","/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Read the audio of a polled voice note (B-715, ADR D1).\n *\n * Telegram sends a voice note as a file id. The bytes take two requests: `getFile` for the file's\n * path, then a download from `https://api.telegram.org/file/bot<token>/<path>`. Only the polled\n * path holds the token, so the webhook `parseInbound` does not read voice notes.\n *\n * A failure is returned as a reason, never thrown: the caller delivers the event without audio and\n * writes the reason to stderr, so an unreadable voice leaves today's behaviour. No reason carries\n * the download URL, which contains the bot token.\n */\n\nimport type { InboundAudio } from \"@theokit/gateway\";\nimport type { Context } from \"grammy\";\n\n/** The largest voice read: Bot API `getFile` serves files of at most 20 MB. */\nconst MAX_VOICE_BYTES = 20 * 1024 * 1024;\n\n/** How long the whole read, `getFile` and download, may take before it is abandoned. */\nconst READ_TIMEOUT_MS = 30_000;\n\nconst DEFAULT_MEDIA_TYPE = \"audio/ogg\";\n\n/** What a read produced: the audio, or why there is none. */\ntype VoiceRead = { readonly audio: InboundAudio } | { readonly reason: string };\n\n/** The `fetch` this module calls; injected in tests so nothing reaches api.telegram.org. */\ntype FetchLike = (url: string, init: { signal: AbortSignal }) => Promise<Response>;\n\n/**\n * The voice object of the message, as far as this module reads it. Every field is `unknown`: a\n * hand-built update or a change on Telegram's side may send any of them in another shape (EC-2).\n */\ninterface VoiceFields {\n readonly file_id?: unknown;\n readonly duration?: unknown;\n readonly mime_type?: unknown;\n readonly file_size?: unknown;\n}\n\n/** A failure, named by the reason the caller writes to stderr. */\ntype Failure = { readonly reason: string };\n\n/**\n * Read the voice note of `ctx.message`. The caller calls this only when the message has a `voice`.\n */\nexport async function readVoice(\n ctx: Context,\n token: string,\n fetchImpl: FetchLike = fetch,\n): Promise<VoiceRead> {\n const voice = (ctx.message?.voice ?? {}) as VoiceFields;\n if (typeof voice.file_id !== \"string\") return { reason: \"no_file_id\" };\n if (typeof voice.file_size === \"number\" && voice.file_size > MAX_VOICE_BYTES) {\n return { reason: \"too_large\" };\n }\n // One deadline over both requests: a stalled getFile holds the polling handler, and every\n // later update, as surely as a stalled download (NFR-006).\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);\n try {\n const path = await filePath(ctx, controller.signal);\n if (typeof path !== \"string\") return path;\n const url = `https://api.telegram.org/file/bot${token}/${path}`;\n const bytes = await download(url, fetchImpl, controller.signal);\n if (!(bytes instanceof Uint8Array)) return bytes;\n return { audio: { data: bytes, ...voiceDetails(voice) } };\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The media type and duration, each replaced by its default when it is not of its type. */\nfunction voiceDetails(voice: VoiceFields): { mediaType: string; durationSeconds: number } {\n const duration = voice.duration;\n return {\n mediaType: typeof voice.mime_type === \"string\" ? voice.mime_type : DEFAULT_MEDIA_TYPE,\n durationSeconds: typeof duration === \"number\" && Number.isFinite(duration) ? duration : 0,\n };\n}\n\n/** The file's path on Telegram's file server, or the reason it is not known. */\nasync function filePath(ctx: Context, signal: AbortSignal): Promise<string | Failure> {\n let file: { file_path?: string };\n try {\n // grammy types the signal with the abort-controller polyfill; a native one is what it reads.\n file = await ctx.getFile(signal as Parameters<Context[\"getFile\"]>[0]);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"get_file_failed\" };\n }\n return file.file_path ?? { reason: \"no_file_path\" };\n}\n\n/**\n * The downloaded bytes, or the reason the download failed.\n *\n * `signal` covers the body read too, not only the headers: a body that stalls after the headers\n * would otherwise hold the polling handler, and every later update, for good (EC-1).\n */\nasync function download(\n url: string,\n fetchImpl: FetchLike,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n try {\n const response = await fetchImpl(url, { signal });\n if (!response.ok) return { reason: `download_status_${response.status}` };\n if (response.body === null) return { reason: \"download_failed\" };\n return await readBounded(response.body, signal);\n } catch {\n return { reason: signal.aborted ? \"timeout\" : \"download_failed\" };\n }\n}\n\n/** The whole body, `too_large` as soon as it passes the bound, or `timeout` when `signal` aborts. */\nasync function readBounded(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n): Promise<Uint8Array | Failure> {\n const reader = body.getReader();\n const cancel = (): void => void reader.cancel().catch(() => undefined);\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n const chunks = await readChunks(reader);\n if (signal.aborted) return { reason: \"timeout\" };\n return chunks ?? { reason: \"too_large\" };\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\n/** The chunks joined into one array, or `undefined` once more than the bound has arrived. */\nasync function readChunks(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): Promise<Uint8Array | undefined> {\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > MAX_VOICE_BYTES) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","/**\n * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * Used by `editMessage` only: Telegram has no call that adds an image to a sent message, so an edit carrying one is refused rather than applied as text alone. `sendMessage` sends attachments through `send-photos.ts`.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: {\n code: \"attachments_unsupported\",\n message: \"telegram adapter cannot attach to an edit\",\n },\n };\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\n/** The most characters one Telegram message carries; also the splitter window. */\nexport const TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = findBoundary(remaining);\n // B-556: a cut inside a table row that fits a chunk moves back to the row's start.\n const afterRow = takeRowSafe(parts, remaining, boundary);\n if (afterRow !== undefined) {\n remaining = afterRow;\n continue;\n }\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n const [piece, reopen] = closeFence(chunk);\n parts.push(piece);\n remaining = reopen + remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/** The paragraph, then line, then hard boundary within the safe window. */\nfunction findBoundary(remaining: string): number {\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;\n}\n\n/**\n * When `boundary` falls inside a table row that fits a chunk, pushes the part before the row and\n * returns the text from the row on; undefined otherwise.\n */\nfunction takeRowSafe(parts: string[], remaining: string, boundary: number): string | undefined {\n const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);\n if (moved === undefined) return undefined;\n const [piece, reopen] = closeFence(remaining.slice(0, moved.end));\n parts.push(piece);\n return reopen + remaining.slice(moved.start);\n}\n\n/** `\\n`, or `\\r` alone or before `\\n`: GFM reads a lone CR as a line ending too. */\nconst isLineEnd = (ch: string | undefined): boolean => ch === \"\\n\" || ch === \"\\r\";\n\n/**\n * Where to cut instead of `cut` so a Markdown table row (a line whose first non-blank character is\n * `|`) it falls inside stays whole: `start` is the row's first character, `end` where the chunk\n * ends with its trailing line endings dropped. Undefined when `cut` is not inside a row, the row\n * opens the chunk, or the row is longer than `window`. The same rule is in core `chunkText`\n * (`keepTableRows`); this package keeps its own copy because it peers core `>=0.9.0`.\n */\nfunction rowSafeCut(\n text: string,\n cut: number,\n window: number,\n): { readonly end: number; readonly start: number } | undefined {\n const start = tableRowStart(text, cut);\n if (start === undefined || rowLength(text, start, cut, window) > window) return undefined;\n let end = start;\n while (end > 0 && isLineEnd(text[end - 1])) end -= 1;\n return end > 0 ? { end, start } : undefined;\n}\n\n/** Start of the table row `cut` falls inside, or undefined (not in a row, or the row opens the text). */\nfunction tableRowStart(text: string, cut: number): number | undefined {\n if (cut >= text.length || isLineEnd(text[cut])) return undefined;\n let start = cut;\n while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;\n return start > 0 && /^[^\\S\\r\\n]*\\|/.test(text.slice(start, cut + 1)) ? start : undefined;\n}\n\n/** Length of the row from `start`, scanning no further than `window` past it. */\nfunction rowLength(text: string, start: number, cut: number, window: number): number {\n let rowEnd = cut;\n while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;\n return rowEnd - start;\n}\n\n/** A fenced code line: 3+ backticks or tildes, up to 3 spaces of indent, then the info string. */\nconst FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;\n\ninterface Fence {\n readonly marker: string;\n readonly info: string;\n}\n\n/** Longest info string a reopened fence repeats, so the reopening cannot eat the chunk's headroom. */\nconst MAX_INFO = 40;\n\n/** The `[start, end)` ranges of `text` that lie inside fenced code, fence lines included. */\nfunction fencedRanges(text: string): Array<readonly [number, number]> {\n const ranges: Array<readonly [number, number]> = [];\n let open: OpenFence | undefined;\n let pos = 0;\n for (const line of text.split(\"\\n\")) {\n open = stepFence(open, line, pos, ranges);\n pos += line.length + 1;\n }\n if (open !== undefined) ranges.push([open.start, text.length]);\n return ranges;\n}\n\ninterface OpenFence {\n readonly fence: Fence;\n readonly start: number;\n}\n\n/** Folds one line into the fence state; a fence that closes on it is added to `ranges`. */\nfunction stepFence(\n open: OpenFence | undefined,\n line: string,\n pos: number,\n ranges: Array<readonly [number, number]>,\n): OpenFence | undefined {\n const m = FENCE_LINE.exec(line.replace(/\\r$/, \"\"));\n const marker = m?.[1];\n if (marker === undefined) return open;\n if (open === undefined) return { fence: { marker, info: (m?.[2] ?? \"\").trim() }, start: pos };\n if (!closesFence(open.fence, marker, m?.[2] ?? \"\")) return open;\n ranges.push([open.start, pos + line.length]);\n return undefined;\n}\n\nfunction closesFence(fence: Fence, marker: string, rest: string): boolean {\n return (\n marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === \"\"\n );\n}\n\n/** The fence still open at the end of `text`, if any. */\nfunction openFenceAt(text: string): Fence | undefined {\n const last = fencedRanges(text).at(-1);\n if (last === undefined || last[1] !== text.length) return undefined;\n const lines = text.slice(last[0]).split(\"\\n\");\n const opener = FENCE_LINE.exec(lines[0] ?? \"\");\n const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? \"\").replace(/\\r$/, \"\")) : null;\n if (opener?.[1] === undefined) return undefined;\n const fence = { marker: opener[1], info: (opener[2] ?? \"\").trim().slice(0, MAX_INFO) };\n if (closer?.[1] !== undefined && closesFence(fence, closer[1], closer[2] ?? \"\")) return undefined;\n return fence;\n}\n\n/**\n * B-526: a cut inside a fenced code block closes the fence at the end of the chunk and reopens it\n * at the start of the next. Returns the chunk and the text to put before the rest.\n */\nfunction closeFence(chunk: string): [string, string] {\n const open = openFenceAt(chunk);\n if (open === undefined) return [chunk, \"\"];\n return [`${chunk}\\n${open.marker}`, `${open.marker}${open.info}\\n`];\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing. Markers inside fenced code are not counted:\n * the fence is the chunk's business, not the markers within it.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const outside = markerIndexes(out, m);\n if (outside.length % 2 === 1) {\n out = out.slice(0, outside[outside.length - 1]).trimEnd();\n }\n }\n return out;\n}\n\n/** Indexes of `needle` in `text`, non-overlapping, skipping those inside fenced code. */\nfunction markerIndexes(text: string, needle: string): number[] {\n const ranges = fencedRanges(text);\n const found: number[] = [];\n let pos = 0;\n while (true) {\n const at = text.indexOf(needle, pos);\n if (at === -1) break;\n pos = at + needle.length;\n if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);\n }\n return found;\n}\n","/**\n * The attachment path of `TelegramAdapter.sendMessage`: one `sendPhoto` per image (B-674) and one\n * `sendVoice` per audio clip (B-715, ADR D2). The module keeps its photo name: one path for both\n * kinds means one caption rule, and a module of its own for voice would import the caption helpers\n * from here while this one imports it, a cycle.\n *\n * The text rides as the first attachment's caption when it is 1 to 1024 UTF-16 units. A longer text\n * gets no caption and follows the last photo through the same split as a text send, so nothing of\n * it is cut. Every attachment is checked before the first request, so a refusal makes no call.\n *\n * The module also holds how a send maps a declared format and a thrown grammy error, which\n * `TelegramAdapter` imports from here: both paths must answer them the same way, and keeping them\n * here rather than in `adapter.ts` avoids an import cycle.\n */\n\nimport type { OutboundAttachment, OutboundMessage, SendResult } from \"@theokit/gateway\";\nimport { type Api, GrammyError, HttpError, InputFile } from \"grammy\";\nimport { splitForTelegram } from \"./split.js\";\n\n/** Telegram's limit on a photo caption, in UTF-16 units (Bot API `sendPhoto`). */\nconst CAPTION_LIMIT = 1024;\n\n/** Telegram's limit on an uploaded photo: \"The photo must be at most 10 MB\" (Bot API `sendPhoto`). */\nconst MAX_PHOTO_BYTES = 10 * 1024 * 1024;\n\n/** Telegram's limit on a file a bot uploads, voice included: 50 MB (Bot API \"Sending files\"). */\nconst MAX_AUDIO_BYTES = 50 * 1024 * 1024;\n\n/** The bound on each kind's bytes, and the word a refusal uses for it. */\nconst KIND_LIMITS = {\n image: { maxBytes: MAX_PHOTO_BYTES, label: \"an image\", bound: \"10 MiB\" },\n audio: { maxBytes: MAX_AUDIO_BYTES, label: \"an audio\", bound: \"50 MiB\" },\n} as const;\n\n/**\n * The most images one send takes. Each image is a request, and a group chat takes about 20\n * messages a minute before Telegram answers 429; ten, the size of a `sendMediaGroup` album, leaves\n * room for the text that follows. A longer list is refused whole rather than cut off part way.\n */\nconst MAX_PHOTOS_PER_SEND = 10;\n\n/** Options every request of one send shares: the parse mode and the forum topic. */\ninterface SharedOptions {\n parse_mode?: \"Markdown\" | \"HTML\";\n message_thread_id?: number;\n}\n\n/**\n * Whether an outbound carries attachments to send. Absent, `null` and an empty list do not. `!== 0`,\n * not `> 0`: any other non-array value has no numeric length and is taken down the photo path,\n * where it is refused rather than dropped (EC-1).\n */\nexport function hasAttachments(out: OutboundMessage): boolean {\n return out.attachments != null && out.attachments.length !== 0;\n}\n\n/**\n * Send the images of `out` as photos, then the text when it is too long for a caption.\n *\n * Returns the id of the last message sent. A failure on photo k returns the mapped error at once,\n * and photos 1 to k-1 stay delivered: Telegram has no way to take them back as one unit.\n */\nexport async function sendPhotos(api: Api, out: OutboundMessage): Promise<SendResult> {\n const chatId = Number(out.channel.id);\n if (Number.isNaN(chatId)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const refusal = validateAttachments(out.attachments);\n if (refusal !== undefined) return refusal;\n const shared = sharedOptions(out);\n try {\n let lastId = await sendEachAttachment(api, chatId, out, shared);\n if (out.text.length > CAPTION_LIMIT) {\n for (const chunk of splitForTelegram(out.text)) {\n lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts)))\n .message_id;\n }\n }\n return { ok: true, messageId: String(lastId) };\n } catch (err) {\n return mapSendError(err);\n }\n}\n\n/**\n * One `sendPhoto` per image and one `sendVoice` per audio clip, in order; the caption and reply\n * target go on the first only, whatever its kind.\n */\nasync function sendEachAttachment(\n api: Api,\n chatId: number,\n out: OutboundMessage,\n shared: SharedOptions,\n): Promise<number> {\n const attachments = out.attachments as ReadonlyArray<OutboundAttachment>;\n const caption = captionOf(out.text);\n let lastId = 0;\n for (const [index, attachment] of attachments.entries()) {\n const options = { ...shared, ...(index === 0 ? firstPhotoOptions(out, caption) : {}) };\n const msg = await withPlainFallback<typeof options, { message_id: number }>(options, (opts) => {\n const file = new InputFile(attachment.data, attachment.filename);\n return attachment.kind === \"audio\"\n ? api.sendVoice(chatId, file, opts)\n : api.sendPhoto(chatId, file, opts);\n });\n lastId = msg.message_id;\n }\n return lastId;\n}\n\n/**\n * Run `send` with `options`. When Telegram refuses the legacy Markdown (`markdown_error`), write\n * one diagnostic line and run `send` once more without `parse_mode`. Any other failure, and a\n * failure of the resend, is rethrown for the caller's `mapSendError`.\n */\nexport async function withPlainFallback<O extends { parse_mode?: \"Markdown\" | \"HTML\" }, R>(\n options: O,\n send: (options: O) => Promise<R>,\n): Promise<R> {\n try {\n return await send(options);\n } catch (err) {\n if (options.parse_mode === undefined) throw err;\n const mapped = mapSendError(err);\n if (mapped.ok || mapped.error?.code !== \"markdown_error\") throw err;\n process.stderr.write(\n `[theokit-gateway-telegram] ${mapped.error.message}; resending as plain text\\n`,\n );\n const { parse_mode: _dropped, ...plain } = options;\n return send(plain as O);\n }\n}\n\n/** The text as a caption when it fits in 1 to 1024 units, otherwise none. */\nfunction captionOf(text: string): string | undefined {\n return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : undefined;\n}\n\n/** What only the first attachment carries: the caption and the message it replies to. */\nfunction firstPhotoOptions(\n out: OutboundMessage,\n caption: string | undefined,\n): { caption?: string; reply_parameters?: { message_id: number } } {\n return {\n ...(caption !== undefined ? { caption } : {}),\n ...(out.replyTo !== undefined ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}),\n };\n}\n\n/** The parse mode and the forum topic, applied to every request of the send. */\nfunction sharedOptions(out: OutboundMessage): SharedOptions {\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n return {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n };\n}\n\n/**\n * The refusal for an attachment list Telegram cannot send, or `undefined`.\n *\n * Not an array, more than ten attachments, an entry with no bytes or over its kind's bound (10 MiB\n * for an image, 50 MiB for audio), or audio whose media type is not `audio/*`:\n * `invalid_attachment`. A kind other than `image` or `audio`: `attachments_unsupported`, the code\n * every adapter answers for what it cannot attach. Every entry is checked before the first request,\n * so a refusal makes no call and never leaves part of the list delivered.\n */\nfunction validateAttachments(attachments: unknown): SendResult | undefined {\n if (!Array.isArray(attachments)) {\n return refuse(\"invalid_attachment\", \"attachments is not a list\");\n }\n if (attachments.length > MAX_PHOTOS_PER_SEND) {\n return refuse(\n \"invalid_attachment\",\n `telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`,\n );\n }\n for (const attachment of attachments as ReadonlyArray<OutboundAttachment | null>) {\n const refusal = validateAttachment(attachment);\n if (refusal !== undefined) return refusal;\n }\n return undefined;\n}\n\n/** The refusal for one entry of the list, or `undefined` when Telegram can send it. */\nfunction validateAttachment(attachment: OutboundAttachment | null): SendResult | undefined {\n if (typeof attachment !== \"object\" || attachment === null) {\n return refuse(\"invalid_attachment\", \"an attachment is not an object\");\n }\n if (attachment.kind !== \"image\" && attachment.kind !== \"audio\") {\n return refuse(\n \"attachments_unsupported\",\n \"telegram adapter sends only image and audio attachments\",\n );\n }\n const limit = KIND_LIMITS[attachment.kind];\n if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {\n return refuse(\"invalid_attachment\", `${limit.label} attachment has no bytes`);\n }\n if (attachment.data.length > limit.maxBytes) {\n return refuse(\n \"invalid_attachment\",\n `${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`,\n );\n }\n return mediaTypeRefusal(attachment);\n}\n\n/** Audio must declare an `audio/*` media type, in any case; an image's is not checked (B-674). */\nfunction mediaTypeRefusal(attachment: OutboundAttachment): SendResult | undefined {\n if (attachment.kind !== \"audio\") return undefined;\n const mediaType = typeof attachment.mediaType === \"string\" ? attachment.mediaType : \"\";\n if (mediaType.toLowerCase().startsWith(\"audio/\")) return undefined;\n return refuse(\"invalid_attachment\", `an audio attachment has media type \"${mediaType}\"`);\n}\n\nfunction refuse(code: string, message: string): SendResult {\n return { ok: false, error: { code, message } };\n}\n\n/** The `parse_mode` grammy takes for a declared format, or `undefined` for plain text. */\nexport function mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\n/** The `parse_mode` option for a declared format, or no option. */\nexport function parseModeOptions(format: OutboundMessage[\"format\"]): {\n parse_mode?: \"Markdown\" | \"HTML\";\n} {\n const parseMode = mapFormat(format);\n return parseMode !== undefined ? { parse_mode: parseMode } : {};\n}\n\nfunction mapGrammyError(err: GrammyError): SendResult {\n // A proxy or a non Bot API body can leave `description` undefined.\n const message = err.description ?? err.message;\n const description = message.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message } };\n }\n return { ok: false, error: { code: `telegram_${err.error_code ?? \"unknown\"}`, message } };\n}\n\n/** A thrown grammy error as a `SendResult`; never rethrows. */\nexport function mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) return mapGrammyError(err);\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError } from \"grammy\";\nimport { type PolicyInput, shouldRespond } from \"./group-policy.js\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { readVoice } from \"./read-voice.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport {\n hasAttachments,\n mapFormat,\n mapSendError,\n parseModeOptions,\n sendPhotos,\n withPlainFallback,\n} from \"./send-photos.js\";\nimport { splitForTelegram, TELEGRAM_MAX_MESSAGE } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n /**\n * How updates arrive. `\"polling\"` (default) pulls them with long polling; `\"webhook\"` only marks\n * the adapter connected, and updates arrive through `deliver()`.\n */\n readonly inbound?: \"polling\" | \"webhook\";\n /**\n * When true, a group or supergroup message reaches the handler only if it mentions the bot,\n * replies to one of the bot's messages, or is a slash command. Private chats always pass.\n * Default false (today's behaviour).\n */\n readonly requireMention?: boolean;\n}\n\nfunction isObj(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null;\n}\n\n/** The message facts the policy reads, from an event whose `raw` is a Context or an update. */\nfunction policyInput(event: GatewayMessageEvent): PolicyInput {\n const raw = (event as { telegram?: { raw?: unknown } }).telegram?.raw;\n const msg = isObj(raw) && isObj(raw.message) ? raw.message : undefined;\n const replyTo =\n msg !== undefined && isObj(msg.reply_to_message) ? msg.reply_to_message : undefined;\n const from = replyTo !== undefined && isObj(replyTo.from) ? replyTo.from : undefined;\n return {\n chatType: event.channel.type === \"dm\" ? \"private\" : \"group\",\n text: event.text,\n replyToFromId: typeof from?.id === \"number\" ? from.id : undefined,\n };\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates by default, so inbound needs no public URL.\n * With `inbound: \"webhook\"` it does not poll; updates arrive through `deliver()`.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n override get capabilities(): AdapterCapabilities {\n return { ...super.capabilities, maxMessageChars: TELEGRAM_MAX_MESSAGE, threads: true };\n }\n\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private readonly inbound: \"polling\" | \"webhook\";\n private readonly requireMention: boolean;\n private warnedNoIdentity = false;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.inbound = opts.inbound ?? \"polling\";\n this.requireMention = opts.requireMention === true;\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n if (this.inbound === \"polling\")\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n if (this.inbound === \"webhook\") return;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // 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.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (hasAttachments(out)) return sendPhotos(this.bot.api, out);\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await withPlainFallback(\n {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n },\n (opts) => this.bot.api.sendMessage(chatIdNum, chunk, opts),\n );\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */\n override readonly supportsAttachments = true;\n\n /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */\n protected override readonly attachmentKinds = [\"image\", \"audio\"] as const;\n\n /** Telegram edits a sent message's text through `editMessageText`. */\n override readonly supportsEdit = true;\n\n /**\n * Replace the text of a message this bot sent, through `editMessageText`.\n *\n * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no\n * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,\n * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own\n * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit\n * replaces one message. Telegram's \"message is not modified\" refusal is answered as a success,\n * because the message already shows the text; a caller that treated it as a failure would send\n * the same text again as a second message.\n */\n override async editMessage(messageId: string, out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.editText(messageId, out);\n }\n\n private async editText(messageId: string, out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const id = parseMessageId(messageId);\n if (id === undefined) {\n return {\n ok: false,\n error: {\n code: \"invalid_message_id\",\n message: `message id \"${messageId}\" is not a positive integer`,\n },\n };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parts = splitForTelegram(out.text);\n if (parts.length !== 1) return editPartsRefusal(parts.length);\n try {\n await this.bot.api.editMessageText(\n chatIdNum,\n id,\n parts[0] as string,\n parseModeOptions(out.format),\n );\n } catch (err) {\n if (!isNotModified(err)) return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override async react(channelId: string, messageId: string, emoji: string): Promise<SendResult> {\n const chatId = Number(channelId);\n const id = parseMessageId(messageId);\n if (Number.isNaN(chatId) || id === undefined || emoji.length === 0) {\n return {\n ok: false,\n error: {\n code: \"invalid_reaction\",\n message: \"numeric channel, message id and emoji needed\",\n },\n };\n }\n try {\n // The emoji must be one of Telegram's allowed reactions; the API refuses others.\n await this.bot.api.setMessageReaction(chatId, id, [\n { type: \"emoji\", emoji } as unknown as Parameters<\n typeof this.bot.api.setMessageReaction\n >[2][number],\n ]);\n } catch (err) {\n return mapSendError(err);\n }\n return { ok: true, messageId };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n if (!this.passesMentionGate(event)) return;\n await this.dispatchEvent(await this.withVoice(ctx, event));\n }\n\n /** The `requireMention` gate, shared by the polled and webhook paths. */\n private passesMentionGate(event: GatewayMessageEvent): boolean {\n if (!this.requireMention || event.channel.type === \"dm\") return true;\n let me: { id: number; username?: string } | undefined;\n try {\n me = this.bot.botInfo;\n } catch {\n me = undefined;\n }\n if (me?.username === undefined) {\n if (!this.warnedNoIdentity) {\n this.warnedNoIdentity = true;\n process.stderr.write(\n \"[telegram] requireMention: bot identity not known yet; dropping group message\\n\",\n );\n }\n return false;\n }\n return shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });\n }\n\n /**\n * The event with the voice note's audio when the message has one (B-715, ADR D1).\n *\n * An unreadable voice leaves the event as it was and writes the reason to stderr: the message is\n * delivered either way, as it was before voice notes were read.\n */\n private async withVoice(\n ctx: Context,\n event: TelegramMessageEvent,\n ): Promise<TelegramMessageEvent> {\n if (ctx.message?.voice === undefined) return event;\n const read = await readVoice(ctx, this.bot.token);\n if (\"audio\" in read) return { ...event, audio: read.audio };\n process.stderr.write(`[telegram] voice not read: ${read.reason}\\n`);\n return event;\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (!this.passesMentionGate(event)) return \"ok\";\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\n/**\n * The numeric id `editMessageText` takes, or `undefined` for one Telegram cannot have issued.\n *\n * Digits only, then a safe positive integer: `Number()` alone accepts `\" 42\"` and `\"0x10\"`, turns\n * `\"abc\"` into `NaN`, and rounds a digit string above 2^53 - 1 to a different id.\n */\nfunction parseMessageId(messageId: string): number | undefined {\n if (!/^\\d+$/.test(messageId)) return undefined;\n const id = Number(messageId);\n return Number.isSafeInteger(id) && id > 0 ? id : undefined;\n}\n\n/** Did Telegram refuse the edit because the message already shows this text? */\nfunction isNotModified(err: unknown): boolean {\n return (\n err instanceof GrammyError &&\n (err.description ?? \"\").toLowerCase().includes(\"message is not modified\")\n );\n}\n\n/**\n * The refusal for a text that is not exactly one Telegram message.\n *\n * More than one part is `edit_too_long`. No parts cannot happen today, since `splitForTelegram`\n * returns `[text]` for any text up to 4096 characters and empty text is refused earlier; the arm\n * keeps a later splitter that returns `[]` from editing with `undefined`.\n */\nfunction editPartsRefusal(partCount: number): SendResult {\n if (partCount > 1) {\n return {\n ok: false,\n error: {\n code: \"edit_too_long\",\n message: `text needs ${partCount} Telegram messages; an edit replaces one`,\n },\n };\n }\n return { ok: false, error: { code: \"empty_text\", message: \"text reduced to zero parts\" } };\n}\n","/**\n * Typed errors for `@theokit/gateway-telegram`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway\n * package's does, so `createChannels` reports a refused Telegram config as a rejected channel\n * rather than rethrowing it as a defect.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/**\n * Misconfiguration of the Telegram channel, raised before any network call.\n *\n * Carries a structured `code` the caller can branch on and, for a refused field, the field's key\n * in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it\n * is never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: GatewayConfigurationErrorOptions) {\n super(\"gateway-telegram\", opts);\n }\n}\n","/**\n * `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { TelegramAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-telegram: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\nfunction readToken(config: Readonly<Record<string, unknown>>): string {\n const token = config.token;\n if (typeof token !== \"string\") throw invalid(\"token\", \"a string\");\n if (token.length === 0) {\n // grammy's own `new Bot(\"\")` throws a plain Error, which `createChannels` would rethrow as a\n // defect instead of reporting the channel as rejected.\n throw new ConfigurationError({\n code: \"token_required\",\n message: \"gateway-telegram: config.token is empty\",\n detail: \"token\",\n });\n }\n return token;\n}\n\nfunction readAllowedUsers(config: Readonly<Record<string, unknown>>): string[] | undefined {\n const value = config.allowedUsers;\n if (value === undefined || value === null) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw invalid(\"allowedUsers\", \"an array of user id strings\");\n }\n return value;\n}\n\nfunction readRequireMention(config: Readonly<Record<string, unknown>>): boolean | undefined {\n const value = config.requireMention;\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"boolean\") throw invalid(\"requireMention\", \"a boolean\");\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"token\",\n required: true,\n secret: true,\n description: \"The bot token BotFather issued for this bot.\",\n },\n {\n key: \"allowedUsers\",\n required: false,\n secret: false,\n description: \"Telegram user ids allowed to reach the handler; absent or empty allows everyone.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description:\n \"When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false.\",\n },\n];\n\n/**\n * The Telegram channel: a long-polling bot, so it needs no webhook route.\n *\n * `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is\n * not an array of strings, with this package's `ConfigurationError`; it performs no network call.\n *\n * @public\n */\nexport const telegramChannel = {\n platform: \"telegram\" as const,\n transport: \"socket\" as const,\n senderIdentity: \"authenticated\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n const requireMention = readRequireMention(config);\n return new TelegramAdapter({\n token,\n ...(allowedUsers === undefined ? {} : { allowedUsers }),\n ...(requireMention === undefined ? {} : { requireMention }),\n });\n },\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-telegram",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Telegram (grammy) platform adapter for @theokit/gateway. ADR D171.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {