loopzero-gateway-telegram 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +535 -0
- package/LICENSE +201 -0
- package/README.md +212 -2
- package/dist/index.cjs +1193 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +283 -0
- package/dist/index.d.ts +283 -0
- package/dist/index.js +1185 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/group-policy.ts","../src/inline-keyboard.ts","../src/parse-inbound.ts","../src/read-voice.ts","../src/read-document.ts","../src/refuse-attachments.ts","../src/split.ts","../src/send-photos.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts"],"names":["refusal","audio","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,OAAA,EAAS,IAAA,IAAQ,GAA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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,MAAM,OAAA,GAAU,YAAY,MAAM,CAAA;AAClC,IAAA,OAAO,IAAI,eAAA,CAAgB;AAAA,MACzB,KAAA;AAAA,MACA,GAAI,OAAA,KAAY,MAAA,GAAY,EAAC,GAAI,EAAE,OAAA,EAAQ;AAAA,MAC3C,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 * `OutboundMessage.buttons` as Telegram's `reply_markup.inline_keyboard` (issue #4).\n *\n * The adapter checks the rows itself, with no request, because a caller of `sendMessage` reaches\n * it without passing through the core's check. Only types come from `loopzero-gateway`, so the\n * adapter calls nothing its declared core floor lacks.\n */\n\nimport type {\n ButtonCapability,\n OutboundButton,\n OutboundMessage,\n SendResult,\n} from \"loopzero-gateway\";\n\n/**\n * What this adapter renders: URL buttons and `web_app` buttons. `callback` is left out on purpose:\n * the adapter does not receive `callback_query` updates yet, so a pressed callback button would\n * reach nobody. Telegram documents no row or per-row limit, so none is declared.\n */\nexport const TELEGRAM_BUTTONS: ButtonCapability = { actionKinds: [\"url\", \"web_app\"] };\n\n/** One Bot API `InlineKeyboardButton`, in the two shapes this adapter sends. */\ntype InlineKeyboardButton =\n | { readonly text: string; readonly url: string }\n | { readonly text: string; readonly web_app: { readonly url: string } };\n\n/** The `reply_markup` option of a send or an edit. */\nexport interface InlineKeyboardMarkup {\n readonly reply_markup: { readonly inline_keyboard: InlineKeyboardButton[][] };\n}\n\nfunction refusal(code: \"buttons_unsupported\" | \"invalid_buttons\", message: string): SendResult {\n return { ok: false, error: { code, message } };\n}\n\nfunction absoluteUrl(value: unknown): URL | undefined {\n if (typeof value !== \"string\") return undefined;\n try {\n return new URL(value);\n } catch {\n // Not absolute: the caller names the button that carries it.\n return undefined;\n }\n}\n\n/** A URL button, or the refusal of a URL that is not absolute. */\nfunction urlButton(label: string, url: string, at: string): InlineKeyboardButton | SendResult {\n if (absoluteUrl(url) === undefined) {\n return refusal(\"invalid_buttons\", `the URL of ${at} is not an absolute URL`);\n }\n return { text: label, url };\n}\n\n/** A Mini App button, or the refusal of one outside a private chat or with a URL that is not HTTPS. */\nfunction webAppButton(\n label: string,\n url: string,\n at: string,\n channelType: OutboundMessage[\"channel\"][\"type\"],\n): InlineKeyboardButton | SendResult {\n // Telegram answers BUTTON_TYPE_INVALID for a web_app button outside a private chat.\n if (channelType !== \"dm\") {\n return refusal(\n \"buttons_unsupported\",\n \"telegram adapter sends a web_app button only in a private chat\",\n );\n }\n if (absoluteUrl(url)?.protocol !== \"https:\") {\n return refusal(\"invalid_buttons\", `the web_app URL of ${at} must be an absolute https: URL`);\n }\n return { text: label, web_app: { url } };\n}\n\n/** The Bot API button for `button`, or the refusal that keeps it from being sent. */\nfunction toInlineButton(\n button: OutboundButton,\n at: string,\n channelType: OutboundMessage[\"channel\"][\"type\"],\n): InlineKeyboardButton | SendResult {\n if (typeof button?.label !== \"string\" || button.label.trim() === \"\") {\n return refusal(\"invalid_buttons\", `${at} has no label`);\n }\n const action = button.action;\n switch (action?.kind) {\n case \"url\":\n return urlButton(button.label, action.url, at);\n case \"web_app\":\n return webAppButton(button.label, action.url, at, channelType);\n case \"callback\":\n return refusal(\"buttons_unsupported\", \"telegram adapter cannot send a callback button\");\n default:\n return refusal(\"invalid_buttons\", `${at} has no known action kind`);\n }\n}\n\n/** The keyboard row for `buttons`, row `row` (from 0), or the refusal of its first bad button. */\nfunction keyboardRow(\n buttons: unknown,\n row: number,\n channelType: OutboundMessage[\"channel\"][\"type\"],\n): InlineKeyboardButton[] | SendResult {\n if (!Array.isArray(buttons) || buttons.length === 0) {\n return refusal(\"invalid_buttons\", `button row ${row + 1} is empty`);\n }\n const line: InlineKeyboardButton[] = [];\n for (const [column, button] of (buttons as ReadonlyArray<OutboundButton>).entries()) {\n const mapped = toInlineButton(button, `button ${column + 1} of row ${row + 1}`, channelType);\n if (\"ok\" in mapped) return mapped;\n line.push(mapped);\n }\n return line;\n}\n\n/**\n * The `reply_markup` for `out.buttons`, `{}` when it carries none, or the refusal of the first\n * button that cannot be sent: an empty row, a blank label, a URL that is not absolute, a `web_app`\n * URL that is not HTTPS or outside a private chat, a `callback` button, or buttons together with\n * attachments (a media group takes no keyboard).\n */\nexport function inlineKeyboardOf(\n out: OutboundMessage,\n): InlineKeyboardMarkup | Record<string, never> | SendResult {\n const rows = out.buttons;\n if (rows == null || rows.length === 0) return {};\n if (out.attachments != null && out.attachments.length !== 0) {\n return refusal(\"buttons_unsupported\", \"telegram adapter cannot send buttons with attachments\");\n }\n if (!Array.isArray(rows)) return refusal(\"invalid_buttons\", \"buttons is not a list of rows\");\n const keyboard: InlineKeyboardButton[][] = [];\n for (const [row, buttons] of rows.entries()) {\n const line = keyboardRow(buttons, row, out.channel.type);\n if (!Array.isArray(line)) return line;\n keyboard.push(line);\n }\n return { reply_markup: { inline_keyboard: keyboard } };\n}\n\n/** Whether {@link inlineKeyboardOf} answered a refusal rather than options. */\nexport function isRefusal(\n value: InlineKeyboardMarkup | Record<string, never> | SendResult,\n): value is SendResult {\n return \"ok\" in value;\n}\n","/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of LoopZero's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `loopzero-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 \"loopzero-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 LoopZero 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 `loopzero@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), or of an audio file (`message.audio`,\n * OC-103), which takes the same two requests and the same bounds.\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 `<apiBase>/file/bot<token>/<path>` (`https://api.telegram.org` by default). Only the polled\n * path holds the token, so the webhook `parseInbound` does not read voice notes.\n *\n * The read is deferred (`deferVoice`): the event reaches the hooks with metadata only, and no\n * request leaves until a hook or the handler calls `audio.read()`. A failure rejects that call with\n * a `VoiceReadError` naming a reason, and writes the reason to stderr. No reason carries the\n * download URL, which contains the bot token.\n */\n\nimport type { Context } from \"grammy\";\nimport type { InboundAudio } from \"loopzero-gateway\";\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\nexport const DEFAULT_API_BASE = \"https://api.telegram.org\";\n\nconst DEFAULT_MEDIA_TYPE = \"audio/ogg\";\n\n/**\n * The media type of an audio file whose sender's client reported none. Telegram's own docs say a\n * bot can send audio files \"in the .MP3 or .M4A format\" (sendAudio), so MP3 is the usual case.\n */\nconst DEFAULT_AUDIO_FILE_MEDIA_TYPE = \"audio/mpeg\";\n\n/** What a read produced: the audio, or why there is none. */\ntype VoiceRead = { readonly audio: { readonly data: Uint8Array } } | { readonly reason: string };\n\n/** The `fetch` this module calls; injected in tests so nothing reaches api.telegram.org. */\nexport type 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. */\nexport type Failure = { readonly reason: string };\n\n/** Why a deferred read failed; the message holds a reason and never the download URL. */\nexport class VoiceReadError extends Error {\n override readonly name = \"VoiceReadError\";\n constructor(readonly reason: string) {\n super(`voice not read: ${reason}`);\n }\n}\n\n/**\n * Why a deferred read of an audio file (`message.audio`) failed; the message holds a reason and\n * never the download URL.\n */\nexport class AudioReadError extends Error {\n override readonly name = \"AudioReadError\";\n constructor(readonly reason: string) {\n super(`audio not read: ${reason}`);\n }\n}\n\n/**\n * The audio of `ctx.message`'s voice note, with nothing fetched yet. `read()` downloads on its\n * first call and returns the same bytes after; a failure is cached too, and is reported through\n * `onFailure` once.\n */\nexport function deferVoice(\n ctx: Context,\n token: string,\n onFailure: (reason: string) => void,\n fetchImpl: FetchLike = fetch,\n apiBase = DEFAULT_API_BASE,\n): InboundAudio {\n const voice = (ctx.message?.voice ?? {}) as VoiceFields;\n return deferMessageAudio(ctx, voice, DEFAULT_MEDIA_TYPE, token, {\n onFailure,\n toError: (reason) => new VoiceReadError(reason),\n fetchImpl,\n apiBase,\n });\n}\n\n/**\n * The audio file of `ctx.message` (Bot API `Audio`: a music or recording file sent as audio\n * rather than as a voice note, OC-103), with nothing fetched yet. Read like a voice note: the same\n * two requests, the same 20 MB bound and deadline, and a failure that rejects `read()` with an\n * {@link AudioReadError} naming a reason, never the URL that holds the token.\n */\nexport function deferAudioFile(\n ctx: Context,\n token: string,\n onFailure: (reason: string) => void,\n fetchImpl: FetchLike = fetch,\n apiBase = DEFAULT_API_BASE,\n): InboundAudio {\n const audio = (ctx.message?.audio ?? {}) as VoiceFields;\n return deferMessageAudio(ctx, audio, DEFAULT_AUDIO_FILE_MEDIA_TYPE, token, {\n onFailure,\n toError: (reason) => new AudioReadError(reason),\n fetchImpl,\n apiBase,\n });\n}\n\n/** How a deferred read reports a failure and reaches the Bot API. */\ninterface DeferredReadSettings {\n readonly onFailure: (reason: string) => void;\n readonly toError: (reason: string) => Error;\n readonly fetchImpl: FetchLike;\n readonly apiBase: string;\n}\n\nfunction deferMessageAudio(\n ctx: Context,\n fields: VoiceFields,\n defaultMediaType: string,\n token: string,\n settings: DeferredReadSettings,\n): InboundAudio {\n let pending: Promise<Uint8Array> | undefined;\n const fetchBytes = async (): Promise<Uint8Array> => {\n const result = await readMessageFile(ctx, fields, token, settings.fetchImpl, settings.apiBase);\n if (\"reason\" in result) {\n settings.onFailure(result.reason);\n throw settings.toError(result.reason);\n }\n return result.data;\n };\n return {\n read: () => (pending ??= fetchBytes()),\n ...(typeof fields.file_size === \"number\" ? { size: fields.file_size } : {}),\n ...audioDetails(fields, defaultMediaType),\n };\n}\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 apiBase = DEFAULT_API_BASE,\n): Promise<VoiceRead> {\n const voice = (ctx.message?.voice ?? {}) as VoiceFields;\n const read = await readMessageFile(ctx, voice, token, fetchImpl, apiBase);\n return \"reason\" in read ? read : { audio: { data: read.data } };\n}\n\n/** The file fields of a message's voice note or document, as far as a read uses them. */\nexport interface MessageFileFields {\n readonly file_id?: unknown;\n readonly file_size?: unknown;\n}\n\n/**\n * Download the file `fields` describes, which must be the file of `ctx.message`: `getFile` then\n * the file server, under one deadline, refusing more than the 20 MB `getFile` serves.\n */\nexport async function readMessageFile(\n ctx: Context,\n fields: MessageFileFields,\n token: string,\n fetchImpl: FetchLike = fetch,\n apiBase = DEFAULT_API_BASE,\n): Promise<{ readonly data: Uint8Array } | Failure> {\n if (typeof fields.file_id !== \"string\") return { reason: \"no_file_id\" };\n if (typeof fields.file_size === \"number\" && fields.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 = `${apiBase}/file/bot${token}/${path}`;\n const bytes = await download(url, fetchImpl, controller.signal);\n if (!(bytes instanceof Uint8Array)) return bytes;\n return { data: bytes };\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 audioDetails(\n voice: VoiceFields,\n defaultMediaType: string,\n): { mediaType: string; durationSeconds: number } {\n const duration = voice.duration;\n return {\n mediaType: typeof voice.mime_type === \"string\" ? voice.mime_type : defaultMediaType,\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 * Read the document of a polled message: a file the sender attached as a file, such as a PDF, a\n * CSV, or a photo sent uncompressed.\n *\n * The bytes take the same two requests as a voice note (`readMessageFile` in `read-voice.ts`): the\n * Bot API's `getFile`, then the file server. `getFile` serves files of at most 20 MB, so a larger\n * document is refused before any request. The read is deferred: no request leaves until a hook or\n * the handler calls `read()`. A failure rejects that call with a `DocumentReadError` naming a\n * reason, never the download URL, which contains the bot token.\n */\n\nimport type { Context } from \"grammy\";\nimport type { InboundFile } from \"loopzero-gateway\";\n\nimport { DEFAULT_API_BASE, type FetchLike, readMessageFile } from \"./read-voice.js\";\n\n/** The media type of a document whose sender's client reported none. */\nconst UNKNOWN_MEDIA_TYPE = \"application/octet-stream\";\n\n/**\n * The document object of the message, as far as this module reads it. Every field is `unknown`:\n * a hand-built update or a change on Telegram's side may send any of them in another shape.\n */\ninterface DocumentFields {\n readonly file_id?: unknown;\n readonly file_name?: unknown;\n readonly mime_type?: unknown;\n readonly file_size?: unknown;\n}\n\n/** Why a deferred document read failed; the message holds a reason and never the download URL. */\nexport class DocumentReadError extends Error {\n override readonly name = \"DocumentReadError\";\n constructor(readonly reason: string) {\n super(`document not read: ${reason}`);\n }\n}\n\n/**\n * The document of `ctx.message`, with nothing fetched yet, or `undefined` when the message has\n * none. `read()` downloads on its first call and returns the same bytes after; a failure is cached\n * too, and is reported through `onFailure` once.\n */\nexport function deferDocument(\n ctx: Context,\n token: string,\n onFailure: (reason: string) => void,\n fetchImpl: FetchLike = fetch,\n apiBase = DEFAULT_API_BASE,\n): InboundFile | undefined {\n const document = ctx.message?.document as DocumentFields | undefined;\n if (document === undefined || document === null) return undefined;\n let pending: Promise<Uint8Array> | undefined;\n const fetchBytes = async (): Promise<Uint8Array> => {\n const result = await readMessageFile(ctx, document, token, fetchImpl, apiBase);\n if (\"reason\" in result) {\n onFailure(result.reason);\n throw new DocumentReadError(result.reason);\n }\n return result.data;\n };\n return {\n read: () => {\n pending ??= fetchBytes();\n return pending;\n },\n mediaType: typeof document.mime_type === \"string\" ? document.mime_type : UNKNOWN_MEDIA_TYPE,\n ...(typeof document.file_size === \"number\" ? { size: document.file_size } : {}),\n ...(typeof document.file_name === \"string\" ? { filename: document.file_name } : {}),\n };\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 `loopzero-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 \"loopzero-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 Api, GrammyError, HttpError, InputFile } from \"grammy\";\nimport {\n type FileUploadCapability,\n type OutboundAttachment,\n type OutboundMessage,\n readFileAttachment,\n refuseFileAttachment,\n type SendResult,\n} from \"loopzero-gateway\";\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/**\n * What `sendDocument` takes: any media type, up to the 50 MB a bot uploads (Bot API \"Sending\n * files\": \"50 MB max size for other files\").\n */\nexport const TELEGRAM_FILE_UPLOAD: FileUploadCapability = { maxBytes: MAX_AUDIO_BYTES };\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 attachments of `out` (photos, voice notes, documents), then the text when it is too long\n * for a caption.\n *\n * Returns the id of the last message sent. A failure on attachment k returns the mapped error at\n * once, and attachments 1 to k-1 stay delivered: Telegram has no way to take them back as one unit.\n * Every file is read before the first request, so a file that cannot be read sends nothing.\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 payloads = await payloadsOf(out.attachments as ReadonlyArray<OutboundAttachment>);\n if (\"error\" in payloads) return { ok: false, error: payloads.error };\n const shared = sharedOptions(out);\n try {\n let lastId = await sendEachAttachment(api, chatId, out, payloads, 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/** One attachment ready to upload: its kind, its bytes and the name Telegram shows. */\ninterface Payload {\n readonly kind: OutboundAttachment[\"kind\"];\n readonly bytes: Uint8Array;\n readonly filename: string | undefined;\n}\n\n/** Every attachment's bytes, a file's read from its source, or the error of the first that fails. */\nasync function payloadsOf(\n attachments: ReadonlyArray<OutboundAttachment>,\n): Promise<Payload[] | { error: NonNullable<SendResult[\"error\"]> }> {\n const payloads: Payload[] = [];\n for (const attachment of attachments) {\n if (attachment.kind !== \"file\") {\n payloads.push({\n kind: attachment.kind,\n bytes: attachment.data,\n filename: attachment.filename,\n });\n continue;\n }\n const read = await readFileAttachment(attachment, TELEGRAM_FILE_UPLOAD.maxBytes);\n if (!read.ok) return { error: read.error };\n payloads.push({ kind: \"file\", bytes: read.bytes, filename: attachment.filename });\n }\n return payloads;\n}\n\n/**\n * One `sendPhoto` per image, one `sendVoice` per audio clip and one `sendDocument` per file, in\n * order; the caption and reply target go on the first only, whatever its kind.\n */\nasync function sendEachAttachment(\n api: Api,\n chatId: number,\n out: OutboundMessage,\n payloads: readonly Payload[],\n shared: SharedOptions,\n): Promise<number> {\n const caption = captionOf(out.text);\n let lastId = 0;\n for (const [index, payload] of payloads.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(payload.bytes, payload.filename);\n if (payload.kind === \"audio\") return api.sendVoice(chatId, file, opts);\n if (payload.kind === \"file\") return api.sendDocument(chatId, file, opts);\n return 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 `[loopzero-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 file is held to {@link TELEGRAM_FILE_UPLOAD} by the core's\n * `refuseFileAttachment` (`attachment_too_large` over 50 MiB). Any other kind:\n * `attachments_unsupported`, the code every adapter answers for what it cannot attach. Every entry\n * is checked before the first request, so a refusal makes no call and never leaves part of the list\n * 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 === \"file\") {\n return refuseFileAttachment(attachment, TELEGRAM_FILE_UPLOAD, \"telegram\");\n }\n if (attachment.kind !== \"image\" && attachment.kind !== \"audio\") {\n return refuse(\n \"attachments_unsupported\",\n \"telegram adapter sends only image, audio and file 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 const retryAfter = err.parameters?.retry_after;\n return {\n ok: false,\n error: {\n code: \"rate_limit\",\n message,\n ...(typeof retryAfter === \"number\" ? { retryAfterMs: retryAfter * 1000 } : {}),\n },\n };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message, platformCode: String(err.error_code) },\n };\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 `loopzero-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 { Bot, type Context, GrammyError } from \"grammy\";\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"loopzero-gateway\";\nimport {\n type AdapterCapabilities,\n BasePlatformAdapter,\n type ButtonCapability,\n type FileUploadCapability,\n type OutboundMessage,\n type SendResult,\n type StreamingPreviewCapability,\n} from \"loopzero-gateway\";\nimport { type PolicyInput, shouldRespond } from \"./group-policy.js\";\nimport { inlineKeyboardOf, isRefusal, TELEGRAM_BUTTONS } from \"./inline-keyboard.js\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { deferDocument } from \"./read-document.js\";\nimport { deferAudioFile, deferVoice } from \"./read-voice.js\";\nimport { refuseAttachments } from \"./refuse-attachments.js\";\nimport {\n hasAttachments,\n mapFormat,\n mapSendError,\n parseModeOptions,\n sendPhotos,\n TELEGRAM_FILE_UPLOAD,\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 * Bot API root, for a self-hosted Bot API server or a fake one in tests. Default\n * `\"https://api.telegram.org\"`. Voice-note downloads use the same root. A trailing slash is ignored.\n */\n readonly apiBase?: string;\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 readonly apiBase: string | undefined;\n private warnedNoIdentity = false;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.apiBase = opts.apiBase === undefined ? undefined : opts.apiBase.replace(/\\/+$/, \"\");\n this.bot = new Bot(\n opts.token,\n this.apiBase === undefined ? undefined : { client: { apiRoot: this.apiBase } },\n );\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 `[loopzero-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 const keyboard = inlineKeyboardOf(out);\n if (isRefusal(keyboard)) return keyboard;\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 [index, chunk] of chunks.entries()) {\n try {\n const msg = await withPlainFallback(\n {\n // The keyboard belongs under the whole reply, so only the last part carries it.\n ...(index === chunks.length - 1 ? keyboard : {}),\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 sends a file through `sendDocument`: any media type, up to 50 MiB. */\n override readonly fileUpload: FileUploadCapability = TELEGRAM_FILE_UPLOAD;\n\n /**\n * Telegram shows rows of buttons under a message as an inline keyboard: URL buttons, and\n * `web_app` buttons that open a Mini App in a private chat. A `callback` button is refused until\n * the adapter receives `callback_query` updates.\n */\n override readonly buttonSupport: ButtonCapability = TELEGRAM_BUTTONS;\n\n /** Telegram edits a sent message's text through `editMessageText`. */\n override readonly supportsEdit = true;\n\n /**\n * A streamed reply is previewed by editing one message. Telegram allows about one message per\n * second in a chat, and an edit of up to 4096 characters is one `editMessageText`.\n */\n override readonly streamingPreview: StreamingPreviewCapability = {\n minUpdateIntervalMs: 1000,\n maxCharsPerMessage: () => TELEGRAM_MAX_MESSAGE,\n };\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 const keyboard = inlineKeyboardOf(out);\n if (isRefusal(keyboard)) return keyboard;\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(chatIdNum, id, parts[0] as string, {\n ...parseModeOptions(out.format),\n ...keyboard,\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 normalized = normalizeEvent(ctx);\n if (normalized === undefined) return;\n const event = this.gateMention(normalized);\n if (event === undefined) return;\n await this.dispatchEvent(\n this.withDocument(ctx, this.withVoice(ctx, event as TelegramMessageEvent)),\n );\n }\n\n /**\n * Marks whether the bot was addressed and applies the `requireMention` gate, shared by the\n * polled and webhook paths. Returns `undefined` when the gate drops the event. A direct message\n * is left unmarked; `addressed` stays unset while the bot's identity is not known.\n */\n private gateMention(event: GatewayMessageEvent): GatewayMessageEvent | undefined {\n if (event.channel.type === \"dm\") return event;\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.requireMention) return event;\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 undefined;\n }\n const addressed = shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });\n if (this.requireMention && !addressed) return undefined;\n return { ...event, addressed } as GatewayMessageEvent;\n }\n\n /**\n * The event with the voice note's audio when the message has one (B-715, ADR D1), or with the\n * audio file's when it carries one instead (`message.audio`, OC-103). A message holds at most\n * one of the two.\n *\n * The audio is deferred: no request leaves here, so a `pre_inbound` hook that refuses the event\n * costs no download. An unreadable voice or audio file rejects `audio.read()` and writes the\n * reason to stderr.\n */\n private withVoice(ctx: Context, event: TelegramMessageEvent): TelegramMessageEvent {\n const voice = ctx.message?.voice;\n if (voice !== undefined) {\n if (typeof voice.file_id !== \"string\") {\n process.stderr.write(\"[telegram] voice not read: no_file_id\\n\");\n return event;\n }\n const audio = deferVoice(\n ctx,\n this.bot.token,\n (reason) => process.stderr.write(`[telegram] voice not read: ${reason}\\n`),\n undefined,\n this.apiBase,\n );\n return { ...event, audio };\n }\n const audioFile = ctx.message?.audio;\n if (audioFile === undefined) return event;\n if (typeof audioFile.file_id !== \"string\") {\n process.stderr.write(\"[telegram] audio not read: no_file_id\\n\");\n return event;\n }\n const audio = deferAudioFile(\n ctx,\n this.bot.token,\n (reason) => process.stderr.write(`[telegram] audio not read: ${reason}\\n`),\n undefined,\n this.apiBase,\n );\n return { ...event, audio };\n }\n\n /**\n * The event with the message's document as `files`, when it has one. Deferred like the voice\n * note: no request leaves here. An unreadable document rejects `read()` and writes the reason\n * to stderr.\n */\n private withDocument(ctx: Context, event: TelegramMessageEvent): TelegramMessageEvent {\n const file = deferDocument(\n ctx,\n this.bot.token,\n (reason) => process.stderr.write(`[telegram] document not read: ${reason}\\n`),\n undefined,\n this.apiBase,\n );\n return file === undefined ? event : { ...event, files: [file] };\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 const gated = this.gateMention(event);\n if (gated === undefined) return \"ok\";\n return this.runHandler(this.handler, gated);\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 `loopzero-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 \"loopzero-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 `loopzero-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 // `configFromEnv` yields strings, so a comma-separated string is accepted next to an array.\n // An empty element (a stray or trailing comma, a blank string) is refused: an empty list means\n // \"allow everyone\", so a malformed allowlist must not collapse into one.\n const expected = \"an array of user id strings or a comma-separated string of user ids\";\n const ids =\n typeof value === \"string\" ? value.split(\",\").map((id) => id.trim()) : (value as unknown);\n if (!Array.isArray(ids) || !ids.every((id) => typeof id === \"string\" && id.length > 0)) {\n throw invalid(\"allowedUsers\", expected);\n }\n return ids;\n}\n\nfunction readRequireMention(config: Readonly<Record<string, unknown>>): boolean | undefined {\n const value = config.requireMention;\n if (value === undefined) return undefined;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n if (typeof value !== \"boolean\") throw invalid(\"requireMention\", \"a boolean\");\n return value;\n}\n\nfunction readApiBase(config: Readonly<Record<string, unknown>>): string | undefined {\n const value = config.apiBase;\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\" || value.length === 0)\n throw invalid(\"apiBase\", \"a non-empty URL string\");\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 env?: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"token\",\n env: \"TELEGRAM_TOKEN\",\n required: true,\n secret: true,\n description: \"The bot token BotFather issued for this bot.\",\n },\n {\n key: \"allowedUsers\",\n env: \"TELEGRAM_ALLOWED_USERS\",\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: \"apiBase\",\n env: \"TELEGRAM_API_BASE\",\n required: false,\n secret: false,\n description:\n \"Bot API root, for a self-hosted Bot API server; default https://api.telegram.org.\",\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 const apiBase = readApiBase(config);\n return new TelegramAdapter({\n token,\n ...(apiBase === undefined ? {} : { apiBase }),\n ...(allowedUsers === undefined ? {} : { allowedUsers }),\n ...(requireMention === undefined ? {} : { requireMention }),\n });\n },\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "loopzero-gateway-telegram",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Telegram (grammy) platform adapter for loopzero-gateway. ADR D171.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/getloopscale/loopzero-gateways.git",
|
|
9
|
+
"directory": "packages/gateway-telegram"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=22.12.0"
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.cjs",
|
|
16
|
+
"module": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/index.d.cts",
|
|
26
|
+
"default": "./dist/index.cjs"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"CHANGELOG.md"
|
|
36
|
+
],
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"loopzero-gateway": ">=0.2.0 <1.0.0",
|
|
39
|
+
"grammy": "^1.30.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@stryker-mutator/core": "10",
|
|
43
|
+
"@stryker-mutator/vitest-runner": "10",
|
|
44
|
+
"loopzero-sdk": "^0.1.0",
|
|
45
|
+
"grammy": "^1.30.0",
|
|
46
|
+
"tsup": "^8.5.0",
|
|
47
|
+
"typescript": "5.9.3",
|
|
48
|
+
"vitest": "^4.1.11",
|
|
49
|
+
"zod": "^4.0.0",
|
|
50
|
+
"loopzero-gateway": "0.2.0"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public",
|
|
54
|
+
"provenance": true
|
|
55
|
+
},
|
|
56
|
+
"sideEffects": false,
|
|
57
|
+
"bugs": {
|
|
58
|
+
"url": "https://github.com/getloopscale/loopzero-gateways/issues"
|
|
59
|
+
},
|
|
60
|
+
"homepage": "https://github.com/getloopscale/loopzero-gateways/tree/main/packages/gateway-telegram#readme",
|
|
61
|
+
"keywords": [
|
|
62
|
+
"loopzero",
|
|
63
|
+
"gateway",
|
|
64
|
+
"telegram",
|
|
65
|
+
"grammy",
|
|
66
|
+
"platform",
|
|
67
|
+
"adapter",
|
|
68
|
+
"adr",
|
|
69
|
+
"d171"
|
|
70
|
+
],
|
|
71
|
+
"dependencies": {
|
|
72
|
+
"@types/node-fetch": "^2.6.13"
|
|
73
|
+
},
|
|
74
|
+
"scripts": {
|
|
75
|
+
"build": "tsup",
|
|
76
|
+
"typecheck": "tsc --noEmit",
|
|
77
|
+
"test": "vitest run",
|
|
78
|
+
"test:mutation": "stryker run"
|
|
79
|
+
}
|
|
6
80
|
}
|