@theokit/gateway-telegram 0.2.3 → 0.3.1
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 +59 -0
- package/README.md +8 -0
- package/dist/index.cjs +9 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -1
- package/package.json +10 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,64 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 1e215ab: The peer floor on `@theokit/gateway` is `>=0.9.0`, which is what these packages have needed since
|
|
8
|
+
they gained `deliver`.
|
|
9
|
+
|
|
10
|
+
`deliver` and `runHandler` arrived in the core at 0.9.0, and the previous release shipped these
|
|
11
|
+
adapters still declaring `>=0.6.0` — a floor `dep-check` had already proven false by building the
|
|
12
|
+
workspace against it: TS4113 on the override, TS2551 on `runHandler`, in all ten packages.
|
|
13
|
+
|
|
14
|
+
It could not be corrected in that release. `dep-check`'s install check packs an adapter and installs
|
|
15
|
+
it the way a consumer would, and until 0.9.0 was on npm no consumer could resolve a package asking
|
|
16
|
+
for it — the check was right about the world as it stood. The floor is raised here, against a
|
|
17
|
+
registry where the version it names exists.
|
|
18
|
+
|
|
19
|
+
Between the two releases a consumer installing against an older core got a build error rather than a
|
|
20
|
+
resolution error: the same failure, later and less clearly. That window is closed.
|
|
21
|
+
|
|
22
|
+
## 0.3.0
|
|
23
|
+
|
|
24
|
+
### Minor Changes
|
|
25
|
+
|
|
26
|
+
- b38172b: **The peer floor on `@theokit/gateway` rises with this release.** Every adapter now implements
|
|
27
|
+
`deliver` over `runHandler`, and neither exists in an older core — an adapter installed against one
|
|
28
|
+
does not build. `dep-check` caught that by building the whole workspace against the floor each
|
|
29
|
+
package claimed, which is the one thing a version range cannot tell you by reading it.
|
|
30
|
+
|
|
31
|
+
The floor is set in the version commit rather than here, because a range cannot name a version that
|
|
32
|
+
does not exist yet: raised in the workspace, the same gate then fails the other way round — every
|
|
33
|
+
adapter declaring a floor above the core installed beside it. That is the shape `fa70153` used when
|
|
34
|
+
these ranges were first written.
|
|
35
|
+
|
|
36
|
+
`deliver(event)` — every adapter can now be handed an event that arrived out of band (#83).
|
|
37
|
+
|
|
38
|
+
`onInbound` was the seam every adapter implemented and it had no public counterpart. Six platforms
|
|
39
|
+
self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync loop, IMAP — so
|
|
40
|
+
the asymmetry stayed invisible: `GatewayRunner` worked for eight platforms and silently did nothing
|
|
41
|
+
for LINE and WhatsApp Cloud, whose payloads arrive on an HTTP route the application owns. Every app
|
|
42
|
+
wired those two by hand, beside the runner rather than through it.
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
const outcome = await adapter.deliver(event); // "ok" | "no_handler" | "handler_threw"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The three outcomes are distinguished because a caller acts on them differently: answering a webhook
|
|
49
|
+
200 when nobody was subscribed tells the provider to stop retrying a message nothing received.
|
|
50
|
+
|
|
51
|
+
`BasePlatformAdapter.runHandler` holds the containment once, where ten copies of it used to live —
|
|
52
|
+
a handler is user code, its throw is named as the handler's failure rather than the platform's, and
|
|
53
|
+
delivery continues. Each adapter's `deliver` is one line over it.
|
|
54
|
+
|
|
55
|
+
Also: `gateway-sms`'s `createWebhookServer` now signs against the configured `publicUrl` (#90).
|
|
56
|
+
Twilio verifies against the URL it POSTed to, and behind a proxy that rewrites `host` — a tunnel, an
|
|
57
|
+
ingress, a load balancer terminating TLS — the reconstruction from headers yields the internal
|
|
58
|
+
address, so a correct signature fails on every delivery. `publicUrl` is required by all three
|
|
59
|
+
backend option shapes and documented as "used by signature verifier"; until now no source file read
|
|
60
|
+
it. The header reconstruction stays as the fallback for an app served directly.
|
|
61
|
+
|
|
3
62
|
## 0.2.3
|
|
4
63
|
|
|
5
64
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -4,6 +4,14 @@ Telegram platform adapter for `@theokit/gateway`. Wraps [grammy](https://grammy.
|
|
|
4
4
|
|
|
5
5
|
> **Status: 0.1.0 — pre-release.**
|
|
6
6
|
|
|
7
|
+
|
|
8
|
+
## How inbound arrives
|
|
9
|
+
|
|
10
|
+
**Long polling by default.** grammY pulls updates and they reach `onInbound` once `connect()`
|
|
11
|
+
resolves.
|
|
12
|
+
|
|
13
|
+
Telegram also supports a webhook, and `theokit/server/webhook` exports `telegram()` for the secret
|
|
14
|
+
token it sends in `X-Telegram-Bot-Api-Secret-Token`. Parsed updates go to `adapter.deliver(event)`.
|
|
7
15
|
## Install
|
|
8
16
|
|
|
9
17
|
```bash
|
package/dist/index.cjs
CHANGED
|
@@ -273,6 +273,15 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
273
273
|
}
|
|
274
274
|
return "ok";
|
|
275
275
|
}
|
|
276
|
+
/**
|
|
277
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
278
|
+
*
|
|
279
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
280
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
281
|
+
*/
|
|
282
|
+
async deliver(event) {
|
|
283
|
+
return this.runHandler(this.handler, event);
|
|
284
|
+
}
|
|
276
285
|
};
|
|
277
286
|
function normalizeEvent(ctx) {
|
|
278
287
|
const chat = ctx.chat;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError"],"mappings":";;;;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,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AM,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/**\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 * 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/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError"],"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,MAC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,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,SAAA,EAAW,OAAA,EAAU,GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF;;;ACrOO,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 * 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
|
@@ -58,6 +58,13 @@ declare class TelegramAdapter extends BasePlatformAdapter {
|
|
|
58
58
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
59
59
|
startTyping(channelId: string): Promise<void>;
|
|
60
60
|
private handleInbound;
|
|
61
|
+
/**
|
|
62
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
63
|
+
*
|
|
64
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
65
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
66
|
+
*/
|
|
67
|
+
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
61
68
|
}
|
|
62
69
|
|
|
63
70
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -58,6 +58,13 @@ declare class TelegramAdapter extends BasePlatformAdapter {
|
|
|
58
58
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
59
59
|
startTyping(channelId: string): Promise<void>;
|
|
60
60
|
private handleInbound;
|
|
61
|
+
/**
|
|
62
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
63
|
+
*
|
|
64
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
65
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
66
|
+
*/
|
|
67
|
+
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
61
68
|
}
|
|
62
69
|
|
|
63
70
|
/**
|
package/dist/index.js
CHANGED
|
@@ -271,6 +271,15 @@ var TelegramAdapter = class extends BasePlatformAdapter {
|
|
|
271
271
|
}
|
|
272
272
|
return "ok";
|
|
273
273
|
}
|
|
274
|
+
/**
|
|
275
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
276
|
+
*
|
|
277
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
278
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
279
|
+
*/
|
|
280
|
+
async deliver(event) {
|
|
281
|
+
return this.runHandler(this.handler, event);
|
|
282
|
+
}
|
|
274
283
|
};
|
|
275
284
|
function normalizeEvent(ctx) {
|
|
276
285
|
const chat = ctx.chat;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.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,CA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AA;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 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/**\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 * 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/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,EA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,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 * 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.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Telegram (grammy) platform adapter for @theokit/gateway. ADR D171.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -34,17 +34,19 @@
|
|
|
34
34
|
"CHANGELOG.md"
|
|
35
35
|
],
|
|
36
36
|
"peerDependencies": {
|
|
37
|
-
"@theokit/gateway": ">=0.
|
|
37
|
+
"@theokit/gateway": ">=0.9.0 <1.0.0",
|
|
38
38
|
"grammy": "^1.30.0"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@
|
|
41
|
+
"@stryker-mutator/core": "10",
|
|
42
|
+
"@stryker-mutator/vitest-runner": "10",
|
|
43
|
+
"@theokit/sdk": "^4.62.0",
|
|
42
44
|
"grammy": "^1.30.0",
|
|
43
45
|
"tsup": "^8.5.0",
|
|
44
|
-
"typescript": "
|
|
45
|
-
"vitest": "^4.1.
|
|
46
|
+
"typescript": "5.9.3",
|
|
47
|
+
"vitest": "^4.1.11",
|
|
46
48
|
"zod": "^4.0.0",
|
|
47
|
-
"@theokit/gateway": "0.
|
|
49
|
+
"@theokit/gateway": "0.9.0"
|
|
48
50
|
},
|
|
49
51
|
"publishConfig": {
|
|
50
52
|
"access": "public",
|
|
@@ -53,6 +55,7 @@
|
|
|
53
55
|
"scripts": {
|
|
54
56
|
"build": "tsup",
|
|
55
57
|
"typecheck": "tsc --noEmit",
|
|
56
|
-
"test": "vitest run"
|
|
58
|
+
"test": "vitest run",
|
|
59
|
+
"test:mutation": "stryker run"
|
|
57
60
|
}
|
|
58
61
|
}
|