@theokit/gateway-telegram 0.4.0 → 0.5.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,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 05e7fdd: Edit a message an adapter sent, so a reply can stream as a preview that the final text replaces.
8
+
9
+ `BasePlatformAdapter` gains `supportsEdit` (`false` by default) and
10
+ `editMessage(messageId, out)`, whose default refuses with `edit_unsupported`, makes no platform
11
+ call and never throws. A third-party subclass that already declares a member with either name and
12
+ a different type no longer compiles against this release, and under `noImplicitOverride` one
13
+ that declares it without `override` does not either.
14
+
15
+ Telegram (`editMessageText`), Discord (one REST `PATCH` of the message, without fetching the
16
+ channel), Slack (`chat.update`), Mattermost (`patchPost`), Matrix (an `m.replace` event) and Teams
17
+ (`updateActivity`, or `activities(conversationId).update` on `@microsoft/teams.api` below 2.0.14)
18
+ set `supportsEdit` to `true` and replace the text of a message they sent, honouring `format` as
19
+ `sendMessage` does (Slack's `chat.update` takes no `mrkdwn` argument, so its edit sends the text
20
+ as it is for every format), and return `{ ok: true, messageId }` with the same id. E-mail, SMS, LINE and
21
+ WhatsApp keep the default.
22
+
23
+ An edit is refused with no request as `edit_too_long` when the text would need more than one
24
+ platform message (Matrix has no length check), as `invalid_message_id` for an empty id (and on
25
+ Telegram one that is not a safe positive integer), and as `empty_text` and `not_connected` where
26
+ `sendMessage` answers those. Telegram answers its "message is not modified" refusal as a success.
27
+ On Discord an unknown channel is answered by the platform, as `discord_10003`. On Matrix a
28
+ `#alias` the adapter never resolved costs one lookup before the edit. Teams and Matrix do not
29
+ retry a refused markup as plain text on an edit, as they do on a send.
30
+
31
+ The six adapters keep `>=0.9.0` as their peer range on `@theokit/gateway` in this release. At run
32
+ time they work against any core in that range, since no adapter calls the base `editMessage`. Their
33
+ sources declare both members with `override`, so building them against a core older than this one
34
+ reports TS4113. The floor rises to this core in the next release, once it is on npm
35
+ (`docs/adr/0008-edit-capable-adapters-raise-their-core-floor-after-the-core-ships.md`). A
36
+ consumer's own typecheck reads the published declarations, which carry no `override`, and passes
37
+ on an older core.
38
+
3
39
  ## 0.4.0
4
40
 
5
41
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -224,6 +224,52 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
224
224
  }
225
225
  return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
226
226
  }
227
+ /** Telegram edits a sent message's text through `editMessageText`. */
228
+ supportsEdit = true;
229
+ /**
230
+ * Replace the text of a message this bot sent, through `editMessageText`.
231
+ *
232
+ * Refuses, with no request, empty text, a message id that is not a safe positive integer, and
233
+ * a non-numeric channel, in that order; the first and last are `sendMessage`'s own checks. A text `splitForTelegram` would cut in
234
+ * two is refused as `edit_too_long`: an edit replaces one message. Telegram's "message is not
235
+ * modified" refusal is answered as a success, because the message already shows the text; a
236
+ * caller that treated it as a failure would send the same text again as a second message.
237
+ */
238
+ async editMessage(messageId, out) {
239
+ if (out.text.length === 0) {
240
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
241
+ }
242
+ const id = parseMessageId(messageId);
243
+ if (id === void 0) {
244
+ return {
245
+ ok: false,
246
+ error: {
247
+ code: "invalid_message_id",
248
+ message: `message id "${messageId}" is not a positive integer`
249
+ }
250
+ };
251
+ }
252
+ const chatIdNum = Number(out.channel.id);
253
+ if (Number.isNaN(chatIdNum)) {
254
+ return {
255
+ ok: false,
256
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
257
+ };
258
+ }
259
+ const parts = splitForTelegram(out.text);
260
+ if (parts.length !== 1) return editPartsRefusal(parts.length);
261
+ try {
262
+ await this.bot.api.editMessageText(
263
+ chatIdNum,
264
+ id,
265
+ parts[0],
266
+ parseModeOptions(out.format)
267
+ );
268
+ } catch (err) {
269
+ if (!isNotModified(err)) return mapSendError(err);
270
+ }
271
+ return { ok: true, messageId };
272
+ }
227
273
  onInbound(handler) {
228
274
  this.handler = handler;
229
275
  return () => {
@@ -294,6 +340,30 @@ function mapFormat(format) {
294
340
  if (format === "html") return "HTML";
295
341
  return void 0;
296
342
  }
343
+ function parseModeOptions(format) {
344
+ const parseMode = mapFormat(format);
345
+ return parseMode !== void 0 ? { parse_mode: parseMode } : {};
346
+ }
347
+ function parseMessageId(messageId) {
348
+ if (!/^\d+$/.test(messageId)) return void 0;
349
+ const id = Number(messageId);
350
+ return Number.isSafeInteger(id) && id > 0 ? id : void 0;
351
+ }
352
+ function isNotModified(err) {
353
+ return err instanceof grammy.GrammyError && err.description.toLowerCase().includes("message is not modified");
354
+ }
355
+ function editPartsRefusal(partCount) {
356
+ if (partCount > 1) {
357
+ return {
358
+ ok: false,
359
+ error: {
360
+ code: "edit_too_long",
361
+ message: `text needs ${partCount} Telegram messages; an edit replaces one`
362
+ }
363
+ };
364
+ }
365
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
366
+ }
297
367
  function mapSendError(err) {
298
368
  if (err instanceof grammy.GrammyError) {
299
369
  const description = err.description.toLowerCase();
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError","GatewayConfigurationError"],"mappings":";;;;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,IAAA,WAAA,GAAc,IAAA;AAAA,EAChB,CAAA,MAAA,IAAW,GAAA,CAAI,iBAAA,KAAsB,MAAA,EAAW;AAC9C,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB,CAAA,MAAO;AACL,IAAA,WAAA,GAAc,OAAA;AAAA,EAChB;AAEA,EAAA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,YAAA,EAAc,CAAA;AAAA,EAC7F;AACF;;;ACvDO,SAAS,mBAAA,CAAoB,KAAc,MAAA,EAAgC;AAChF,EAAA,MAAM,OAAO,GAAA,CAAI,IAAA;AACjB,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,KAAA;AAC/B,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,SAAA,EAAW,OAAO,IAAA;AACpC,EAAA,MAAM,OAAO,GAAA,CAAI,OAAA,EAAS,IAAA,IAAQ,GAAA,CAAI,SAAS,OAAA,IAAW,EAAA;AAC1D,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,IAAA;AACjC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAS,gBAAA;AAC7B,EAAA,IAAI,OAAA,EAAS,IAAA,EAAM,EAAA,KAAO,MAAA,CAAO,OAAO,OAAO,IAAA;AAC/C,EAAA,MAAM,UAAA,GAAa,CAAA,CAAA,EAAI,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA,CAAA;AACvD,EAAA,IAAI,KAAK,WAAA,EAAY,CAAE,QAAA,CAAS,UAAU,GAAG,OAAO,IAAA;AACpD,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.cjs","sourcesContent":["/**\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 * 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 = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\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 parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\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, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.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\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\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 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.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 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 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: 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 (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 this.bot.api.sendMessage(chatIdNum, chunk, {\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 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 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 await this.dispatchEvent(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 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\nfunction 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\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\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 * 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\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\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 config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n return new TelegramAdapter(allowedUsers === undefined ? { token } : { token, allowedUsers });\n },\n};\n","/**\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/**\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 if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\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"]}
1
+ {"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError","GatewayConfigurationError"],"mappings":";;;;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,IAAA,WAAA,GAAc,IAAA;AAAA,EAChB,CAAA,MAAA,IAAW,GAAA,CAAI,iBAAA,KAAsB,MAAA,EAAW;AAC9C,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB,CAAA,MAAO;AACL,IAAA,WAAA,GAAc,OAAA;AAAA,EAChB;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,CAAA,GAAA,EAAM,IAAA,CAAK,EAAE,CAAA,CAAA,EAAI,IAAI,UAAU,CAAA,CAAA;AAAA,IACnC,QAAA,EAAU,UAAA;AAAA,IACV,MAAA,EAAQ;AAAA,MACN,EAAA,EAAI,MAAA,CAAO,IA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GAAA,CAAI,OAAA,EAAS,IAAA,IAAQ,GAAA,CAAI,SAAS,OAAA,IAAW,EAAA;AAC1D,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,IAAA;AACjC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAS,gBAAA;AAC7B,EAAA,IAAI,OAAA,EAAS,IAAA,EAAM,EAAA,KAAO,MAAA,CAAO,OAAO,OAAO,IAAA;AAC/C,EAAA,MAAM,UAAA,GAAa,CAAA,CAAA,EAAI,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA,CAAA;AACvD,EAAA,IAAI,KAAK,WAAA,EAAY,CAAE,QAAA,CAAS,UAAU,GAAG,OAAO,IAAA;AACpD,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.cjs","sourcesContent":["/**\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 * 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 = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\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 parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\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, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.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\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\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 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.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 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 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: 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 (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 this.bot.api.sendMessage(chatIdNum, chunk, {\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 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 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, empty text, a message id that is not a safe positive integer, and\n * a non-numeric channel, in that order; the first and last are `sendMessage`'s own checks. A text `splitForTelegram` would cut in\n * two is refused as `edit_too_long`: an edit replaces one message. Telegram's \"message is not\n * modified\" refusal is answered as a success, because the message already shows the text; a\n * caller that treated it as a failure would send the same text again as a second message.\n */\n override async editMessage(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 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 await this.dispatchEvent(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 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\nfunction 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. */\nfunction parseModeOptions(format: OutboundMessage[\"format\"]): { parse_mode?: \"Markdown\" | \"HTML\" } {\n const parseMode = mapFormat(format);\n return parseMode !== undefined ? { parse_mode: parseMode } : {};\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 && 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\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\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 * 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\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\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 config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n return new TelegramAdapter(allowedUsers === undefined ? { token } : { token, allowedUsers });\n },\n};\n","/**\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/**\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 if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\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"]}
package/dist/index.d.cts CHANGED
@@ -55,6 +55,18 @@ declare class TelegramAdapter extends BasePlatformAdapter {
55
55
  connect(): Promise<boolean>;
56
56
  disconnect(): Promise<void>;
57
57
  sendMessage(out: OutboundMessage): Promise<SendResult>;
58
+ /** Telegram edits a sent message's text through `editMessageText`. */
59
+ readonly supportsEdit = true;
60
+ /**
61
+ * Replace the text of a message this bot sent, through `editMessageText`.
62
+ *
63
+ * Refuses, with no request, empty text, a message id that is not a safe positive integer, and
64
+ * a non-numeric channel, in that order; the first and last are `sendMessage`'s own checks. A text `splitForTelegram` would cut in
65
+ * two is refused as `edit_too_long`: an edit replaces one message. Telegram's "message is not
66
+ * modified" refusal is answered as a success, because the message already shows the text; a
67
+ * caller that treated it as a failure would send the same text again as a second message.
68
+ */
69
+ editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
58
70
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
59
71
  startTyping(channelId: string): Promise<void>;
60
72
  private handleInbound;
package/dist/index.d.ts CHANGED
@@ -55,6 +55,18 @@ declare class TelegramAdapter extends BasePlatformAdapter {
55
55
  connect(): Promise<boolean>;
56
56
  disconnect(): Promise<void>;
57
57
  sendMessage(out: OutboundMessage): Promise<SendResult>;
58
+ /** Telegram edits a sent message's text through `editMessageText`. */
59
+ readonly supportsEdit = true;
60
+ /**
61
+ * Replace the text of a message this bot sent, through `editMessageText`.
62
+ *
63
+ * Refuses, with no request, empty text, a message id that is not a safe positive integer, and
64
+ * a non-numeric channel, in that order; the first and last are `sendMessage`'s own checks. A text `splitForTelegram` would cut in
65
+ * two is refused as `edit_too_long`: an edit replaces one message. Telegram's "message is not
66
+ * modified" refusal is answered as a success, because the message already shows the text; a
67
+ * caller that treated it as a failure would send the same text again as a second message.
68
+ */
69
+ editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
58
70
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
59
71
  startTyping(channelId: string): Promise<void>;
60
72
  private handleInbound;
package/dist/index.js CHANGED
@@ -222,6 +222,52 @@ var TelegramAdapter = class extends BasePlatformAdapter {
222
222
  }
223
223
  return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
224
224
  }
225
+ /** Telegram edits a sent message's text through `editMessageText`. */
226
+ supportsEdit = true;
227
+ /**
228
+ * Replace the text of a message this bot sent, through `editMessageText`.
229
+ *
230
+ * Refuses, with no request, empty text, a message id that is not a safe positive integer, and
231
+ * a non-numeric channel, in that order; the first and last are `sendMessage`'s own checks. A text `splitForTelegram` would cut in
232
+ * two is refused as `edit_too_long`: an edit replaces one message. Telegram's "message is not
233
+ * modified" refusal is answered as a success, because the message already shows the text; a
234
+ * caller that treated it as a failure would send the same text again as a second message.
235
+ */
236
+ async editMessage(messageId, out) {
237
+ if (out.text.length === 0) {
238
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
239
+ }
240
+ const id = parseMessageId(messageId);
241
+ if (id === void 0) {
242
+ return {
243
+ ok: false,
244
+ error: {
245
+ code: "invalid_message_id",
246
+ message: `message id "${messageId}" is not a positive integer`
247
+ }
248
+ };
249
+ }
250
+ const chatIdNum = Number(out.channel.id);
251
+ if (Number.isNaN(chatIdNum)) {
252
+ return {
253
+ ok: false,
254
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
255
+ };
256
+ }
257
+ const parts = splitForTelegram(out.text);
258
+ if (parts.length !== 1) return editPartsRefusal(parts.length);
259
+ try {
260
+ await this.bot.api.editMessageText(
261
+ chatIdNum,
262
+ id,
263
+ parts[0],
264
+ parseModeOptions(out.format)
265
+ );
266
+ } catch (err) {
267
+ if (!isNotModified(err)) return mapSendError(err);
268
+ }
269
+ return { ok: true, messageId };
270
+ }
225
271
  onInbound(handler) {
226
272
  this.handler = handler;
227
273
  return () => {
@@ -292,6 +338,30 @@ function mapFormat(format) {
292
338
  if (format === "html") return "HTML";
293
339
  return void 0;
294
340
  }
341
+ function parseModeOptions(format) {
342
+ const parseMode = mapFormat(format);
343
+ return parseMode !== void 0 ? { parse_mode: parseMode } : {};
344
+ }
345
+ function parseMessageId(messageId) {
346
+ if (!/^\d+$/.test(messageId)) return void 0;
347
+ const id = Number(messageId);
348
+ return Number.isSafeInteger(id) && id > 0 ? id : void 0;
349
+ }
350
+ function isNotModified(err) {
351
+ return err instanceof GrammyError && err.description.toLowerCase().includes("message is not modified");
352
+ }
353
+ function editPartsRefusal(partCount) {
354
+ if (partCount > 1) {
355
+ return {
356
+ ok: false,
357
+ error: {
358
+ code: "edit_too_long",
359
+ message: `text needs ${partCount} Telegram messages; an edit replaces one`
360
+ }
361
+ };
362
+ }
363
+ return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
364
+ }
295
365
  function mapSendError(err) {
296
366
  if (err instanceof GrammyError) {
297
367
  const description = err.description.toLowerCase();
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts","../src/group-policy.ts"],"names":[],"mappings":";;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,IAAA,WAAA,GAAc,IAAA;AAAA,EAChB,CAAA,MAAA,IAAW,GAAA,CAAI,iBAAA,KAAsB,MAAA,EAAW;AAC9C,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB,CAAA,MAAO;AACL,IAAA,WAAA,GAAc,OAAA;AAAA,EAChB;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,CAAA,GAAA,EAAM,IAAA,CAAK,EAAE,CAAA,CAAA,EAAI,IAAI,UAAU,CAAA,CAAA;AAAA,IACnC,QAAA,EAAU,UAAA;AAAA,IACV,MAAA,EAAQ;AAAA,MACN,EAAA,EAAI,MAAA,CAAO,IAAA,EAAM,EAAA,IAAM,WAAW,CAAA;AAAA,MAClC,GAAI,MAAM,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,EAAU,IAAA,CAAK,QAAA,EAAS,GAAI,EAAC;AAAA,MAClE,GAAI,MAAM,UAAA,KAAe,MAAA,GAAY,EAAE,WAAA,EAAa,IAAA,CAAK,UAAA,EAAW,GAAI;AAAC,KAC3E;AAAA,IACA,OAAA,EAAS;AAAA,MACP,EAAA,EAAI,MAAA,CAAO,IAAA,CAAK,EAAE,CAAA;AAAA,MAClB,IAAA,EAAM,WAAA;AAAA,MACN,GAAI,GAAA,CAAI,iBAAA,KAAsB,MAAA,GAAY,EAAE,OAAA,EAAS,MAAA,CAAO,GAAA,CAAI,iBAAiB,CAAA,EAAE,GAAI;AAAC,KAC1F;AAAA,IACA,IAAA,EAAM,GAAA,CAAI,I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AAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.js","sourcesContent":["/**\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 * 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 = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\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 parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\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, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.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\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\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 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.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 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 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: 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 (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 this.bot.api.sendMessage(chatIdNum, chunk, {\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 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 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 await this.dispatchEvent(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 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\nfunction 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\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\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 * 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\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\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 config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n return new TelegramAdapter(allowedUsers === undefined ? { token } : { token, allowedUsers });\n },\n};\n","/**\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/**\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 if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\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"]}
1
+ {"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts","../src/group-policy.ts"],"names":[],"mappings":";;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA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,UAAU,MAAM,CAAA;AAC9B,IAAA,MAAM,YAAA,GAAe,iBAAiB,MAAM,CAAA;AAC5C,IAAA,OAAO,IAAI,eAAA,CAAgB,YAAA,KAAiB,MAAA,GAAY,EAAE,OAAM,GAAI,EAAE,KAAA,EAAO,YAAA,EAAc,CAAA;AAAA,EAC7F;AACF;;;ACvDO,SAAS,mBAAA,CAAoB,KAAc,MAAA,EAAgC;AAChF,EAAA,MAAM,OAAO,GAAA,CAAI,IAAA;AACjB,EAAA,IAAI,IAAA,KAAS,QAAW,OAAO,KAAA;AAC/B,EAAA,IAAI,IAAA,CAAK,IAAA,KAAS,SAAA,EAAW,OAAO,IAAA;AACpC,EAAA,MAAM,OAAO,GAAA,CAAI,OAAA,EAAS,IAAA,IAAQ,GAAA,CAAI,SAAS,OAAA,IAAW,EAAA;AAC1D,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,IAAA;AACjC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAS,gBAAA;AAC7B,EAAA,IAAI,OAAA,EAAS,IAAA,EAAM,EAAA,KAAO,MAAA,CAAO,OAAO,OAAO,IAAA;AAC/C,EAAA,MAAM,UAAA,GAAa,CAAA,CAAA,EAAI,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA,CAAA;AACvD,EAAA,IAAI,KAAK,WAAA,EAAY,CAAE,QAAA,CAAS,UAAU,GAAG,OAAO,IAAA;AACpD,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.js","sourcesContent":["/**\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 * 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 = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\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 parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\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, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.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\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\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 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.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 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 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: 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 (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 this.bot.api.sendMessage(chatIdNum, chunk, {\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 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 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, empty text, a message id that is not a safe positive integer, and\n * a non-numeric channel, in that order; the first and last are `sendMessage`'s own checks. A text `splitForTelegram` would cut in\n * two is refused as `edit_too_long`: an edit replaces one message. Telegram's \"message is not\n * modified\" refusal is answered as a success, because the message already shows the text; a\n * caller that treated it as a failure would send the same text again as a second message.\n */\n override async editMessage(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 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 await this.dispatchEvent(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 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\nfunction 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. */\nfunction parseModeOptions(format: OutboundMessage[\"format\"]): { parse_mode?: \"Markdown\" | \"HTML\" } {\n const parseMode = mapFormat(format);\n return parseMode !== undefined ? { parse_mode: parseMode } : {};\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 && 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\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\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 * 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\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\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 config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n return new TelegramAdapter(allowedUsers === undefined ? { token } : { token, allowedUsers });\n },\n};\n","/**\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/**\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 if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-telegram",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Telegram (grammy) platform adapter for @theokit/gateway. ADR D171.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,7 +47,7 @@
47
47
  "typescript": "5.9.3",
48
48
  "vitest": "^4.1.11",
49
49
  "zod": "^4.0.0",
50
- "@theokit/gateway": "0.11.0"
50
+ "@theokit/gateway": "0.12.0"
51
51
  },
52
52
  "publishConfig": {
53
53
  "access": "public",