@theokit/gateway-telegram 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Patch Changes
6
+
7
+ - Drop the unused `@theokit/sdk` peer dependency, so a TheoKit app can install an adapter.
8
+
9
+ Every adapter declared `peer @theokit/sdk@^2.18.0` and imported the SDK in **zero** source files.
10
+ The framework ships `@theokit/sdk@4.x`, so `npm install @theokit/gateway-line` into a TheoKit app
11
+ failed outright with `ERESOLVE`.
12
+
13
+ The core's range was widened in `@theokit/gateway@0.7.0`, which was not enough on its own: an
14
+ adapter's own manifest still carried the pin, so installing one still failed even against the fixed
15
+ core. Measured in a real app before and after.
16
+
17
+ ## 0.1.3
18
+
19
+ ### Patch Changes
20
+
21
+ - e682180: **A message whose handler throws no longer kills the bot.** On Teams and on WhatsApp's web backend it did — not degraded delivery, an exit code. `Error: ... / Node.js v22.22.2`, and the next message never arrived.
22
+
23
+ Both dispatched with `void handler(event)`. `void` reads as "I am not waiting for this"; what it tells the runtime is "I am not handling the error", and under Node 22's default an unhandled rejection ends the process. Measured against both adapters through their own injection seams before the fix, and again after: the throw is now contained, named, and delivery continues.
24
+
25
+ **Discord and Telegram contained it but blamed the wrong thing.** The rejection escaped into the platform library's error channel, so a bug in the consumer's own handler surfaced as `[discord] client error` / `[telegram] bot error`. Anyone debugging that went looking in discord.js and grammy for a fault that was in their own code. Both now report `handler threw` and return `"handler_threw"` from the internal dispatch seam.
26
+
27
+ **WhatsApp Cloud dropped the rest of the batch, and made the platform resend it.** Meta packs several messages and their delivery receipts into one webhook, and the dispatch loop awaited each handler with nothing around it. One throw skipped every remaining message in the payload, skipped the status receipts, and rejected `handleWebhookPayload` — so the caller's route answered 500 and Meta redelivered the whole batch, replaying the messages that had already been handled. That is a duplicate-reply bug reached through a different door than the one fixed in #11. The same method also now answers `false` on a signed body that is not JSON, instead of throwing out of a method whose contract is `true`/`false`.
28
+
29
+ **Email gained a net it did not strictly need.** Its drain is written never to reject, and it does not — but both launch sites discard the promise, so that property was the only thing between a future edit and the same fatal rejection, and nothing enforced it. The catch now lives at the site that would pay for it.
30
+
31
+ **The contract is written down, and held to.** `BasePlatformAdapter.onInbound` now states it: a handler may throw, and an adapter must contain that throw, report it as the handler's failure rather than the platform's, and keep delivering. Eight of ten adapters had converged on exactly that with nothing recording it. `tests/lint/adapter-contract.test.ts` gains two invariants — every adapter names a handler throw as the handler's, and no adapter launches a user callback with a bare `void` — and both were checked against a deliberately reverted adapter to confirm they fire rather than pass vacuously.
32
+
33
+ - 8cbf136: **Every published export now carries documentation.** Forty-seven public symbols shipped with no docblock at all, so a consumer hovering `DiscordAdapter`, `SlackAdapter`, `WhatsAppCloudBackend`, `ThreadStore` or any of the error classes got an empty tooltip. Coverage across the eleven packages went from 71.2% to 100% (163/163), measured over the published declarations rather than the source, because a docblock is not documentation until it survives the build.
34
+
35
+ The text says what each symbol is for and what constrains it, not what its name already says. `TelegramAdapter` records that a bot cannot enumerate its chats nor speak into one that has not spoken first. `DiscordAdapter` records that reading message content needs a privileged intent enabled in the developer portal, without which every `event.text` arrives empty and nothing says why. `WhatsAppWebBackend` records that it is unofficial and can get a number banned. `shouldDispatchSyncEvent` records that Matrix replays history on sync, which is why a freshly started bot would otherwise answer every message it can still see.
36
+
37
+ **`gateway-slack`'s README documented a type that does not exist.** Its usage example imported `GatewayMessageEvent` from `@theokit/gateway`. That name is an internal alias inside the Discord and Telegram adapters (`MessageEvent as GatewayMessageEvent`), never an export. A reader who copied the example got code that did not compile. It now imports `MessageEvent`, which is what `onInbound` actually hands the handler.
38
+
39
+ Two docblocks that attached to nothing were reattached: `acquirePidLock` in `gateway-whatsapp` had its documentation stranded thirty lines above, over a different function, and shipped undocumented as a result.
40
+
41
+ - b8ef098: **Every package now ships the licence it declares.** All twelve manifests in this repository declare `Apache-2.0`, and the repository had no `LICENSE` file at all — not at the root, and not in any package directory except `gateway-email`. So each published tarball asserted a licence while carrying none of its terms, and §4(a) of that licence requires a copy to travel with the distribution. Worse than a missing file: with no licence text anywhere, everything outside the manifests fell back to default copyright, which grants a recipient nothing.
42
+
43
+ The text is now at the repository root and inside every publishable package, byte-identical to the canonical Apache License 2.0 with the appendix filled in (`Copyright 2026 usetheo.dev`). The one pre-existing copy, in `gateway-email`, was replaced along with the rest: it carried the same truncated paragraph 4(d) found across the ecosystem, dropping "reasonable and customary use" from the NOTICE clause — a modified body under an unmodified SPDX identifier.
44
+
45
+ **The repository moved to the official `usetheokit` organization.** Existing clones and published URLs keep working through GitHub's permanent redirect; the root manifest now declares `Apache-2.0` explicitly rather than leaving the workspace root silent.
46
+
47
+ - 5bae032: Six defects that broke real conversations, found by testing the adapters against the live platforms instead of against fakes.
48
+
49
+ **LINE — no outbound message was ever delivered.** The adapter called the v9 SDK client with positional arguments while that client takes a single request object, so LINE received an empty request and rejected every send with a 400. Upgrade if you use this adapter at all: nothing it sent reached anyone.
50
+
51
+ **Telegram — the bot froze on long replies.** Any message over 4096 characters that began with an unclosed code span (a stray backtick) put the splitter into an infinite loop, hanging the process until it ran out of memory. Long agent answers now split correctly whatever markdown they contain.
52
+
53
+ **Mattermost — long messages silently vanished.** The adapter never split anything, so any reply over 16,383 characters was rejected by the server and the user simply saw nothing. Long replies are now split into parts Mattermost accepts.
54
+
55
+ **SMS — long messages were rejected from the hundredth part onward.** The `(i/N)` prefix outgrew the space reserved for it, pushing every later part past the provider's limit.
56
+
57
+ **Matrix and LINE — `connect()` reported success with an invalid token.** Both now verify the credential with the server before returning `true`, so a wrong token fails at startup instead of silently receiving nothing forever.
58
+
59
+ **Email and Teams — the bot could go permanently deaf.** Replacing an inbound handler and then disposing of the previous one removed the new handler as well, and the gateway stopped receiving messages with nothing logged.
60
+
61
+ Also: a `pre_inbound` hook that threw put its raw error text into the user's chat, which could expose internal details such as connection strings or tokens. Users now see only which hook failed; the detail goes to the server log, redacted.
62
+
63
+ WhatsApp additionally stops opening a second session when `connect()` is called twice, and its group mention filter no longer treats unrelated digits scattered through a message as a mention of the bot.
64
+
3
65
  ## 0.1.2
4
66
 
5
67
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -184,7 +184,14 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
184
184
  */
185
185
  async dispatchEvent(event) {
186
186
  if (this.handler === void 0) return "no_handler";
187
- await this.handler(event);
187
+ try {
188
+ await this.handler(event);
189
+ } catch (err) {
190
+ const m = err instanceof Error ? err.message : String(err);
191
+ process.stderr.write(`[telegram] handler threw: ${m}
192
+ `);
193
+ return "handler_threw";
194
+ }
188
195
  return "ok";
189
196
  }
190
197
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/split.ts","../src/adapter.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError"],"mappings":";;;;;;;;AAKA,IAAM,oBAAA,GAAuB,IAAA;AAC7B,IAAM,UAAA,GAAa,GAAA;AAUZ,SAAS,iBAAiB,IAAA,EAAwB;AACvD,EAAA,IAAI,IAAA,CAAK,MAAA,IAAU,oBAAA,EAAsB,OAAO,CAAC,IAAI,CAAA;AACrD,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,IAAI,SAAA,GAAY,IAAA;AAChB,EAAA,OAAO,SAAA,CAAU,SAAS,CAAA,EAAG;AAC3B,IAAA,IAAI,SAAA,CAAU,UAAU,UAAA,EAAY;AAClC,MAAA,KAAA,CAAM,KAAK,SAAS,CAAA;AACpB,MAAA;AAAA,IACF;AACA,IAAA,IAAI,QAAA,GAAW,SAAA,CAAU,WAAA,CAAY,MAAA,EAAQ,UAAU,CAAA;AACvD,IAAA,IAAI,WAAW,UAAA,GAAa,CAAA,aAAc,SAAA,CAAU,WAAA,CAAY,MAAM,UAAU,CAAA;AAChF,IAAA,IAAI,QAAA,GAAW,UAAA,GAAa,CAAA,EAAG,QAAA,GAAW,UAAA;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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 * 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\";\n\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n}\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\"> {\n if (this.handler === undefined) return \"no_handler\";\n await this.handler(event);\n return \"ok\";\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional field; splitting hurts the \"one event normalization here\" locality.\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 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 const text = msg.text ?? msg.caption ?? \"\";\n const senderId = String(ctx.from?.id ?? \"anonymous\");\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: senderId,\n ...(ctx.from?.username !== undefined ? { username: ctx.from.username } : {}),\n ...(ctx.from?.first_name !== undefined ? { displayName: ctx.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,\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: ctx,\n },\n };\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/split.ts","../src/adapter.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError"],"mappings":";;;;;;;;AAKA,IAAM,oBAAA,GAAuB,IAAA;AAC7B,IAAM,UAAA,GAAa,GAAA;AAUZ,SAAS,iBAAiB,IAAA,EAAwB;AACvD,EAAA,IAAI,IAAA,CAAK,MAAA,IAAU,oBAAA,EAAsB,OAAO,CAAC,IAAI,CAAA;AACrD,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,IAAI,SAAA,GAAY,IAAA;AAChB,EAAA,OAAO,SAAA,CAAU,SAAS,CAAA,EAAG;AAC3B,IAAA,IAAI,SAAA,CAAU,UAAU,UAAA,EAAY;AAClC,MAAA,KAAA,CAAM,KAAK,SAAS,CAAA;AACpB,MAAA;AAAA,IACF;AACA,IAAA,IAAI,QAAA,GAAW,SAAA,CAAU,WAAA,CAAY,MAAA,EAAQ,UAAU,CAAA;AACvD,IAAA,IAAI,WAAW,UAAA,GAAa,CAAA,aAAc,SAAA,CAAU,WAAA,CAAY,MAAM,UAAU,CA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AAA,EAC7E;AACA,EAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,EAAE,MAAM,SAAA,EAAW,OAAA,EAAU,GAAA,CAAc,OAAA,EAAQ,EAAE;AAClF;;;ACjPO,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 * 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\";\n\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\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// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional field; splitting hurts the \"one event normalization here\" locality.\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 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 const text = msg.text ?? msg.caption ?? \"\";\n const senderId = String(ctx.from?.id ?? \"anonymous\");\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: senderId,\n ...(ctx.from?.username !== undefined ? { username: ctx.from.username } : {}),\n ...(ctx.from?.first_name !== undefined ? { displayName: ctx.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,\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: ctx,\n },\n };\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
@@ -21,6 +21,13 @@ interface TelegramAdapterOptions {
21
21
  /** Optional allow-list filter applied at the adapter level. */
22
22
  readonly allowedUsers?: ReadonlyArray<string>;
23
23
  }
24
+ /**
25
+ * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.
26
+ *
27
+ * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate
28
+ * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat
29
+ * id therefore has to come from an inbound message, never from the token.
30
+ */
24
31
  declare class TelegramAdapter extends BasePlatformAdapter {
25
32
  readonly platform: "telegram";
26
33
  private readonly bot;
package/dist/index.d.ts CHANGED
@@ -21,6 +21,13 @@ interface TelegramAdapterOptions {
21
21
  /** Optional allow-list filter applied at the adapter level. */
22
22
  readonly allowedUsers?: ReadonlyArray<string>;
23
23
  }
24
+ /**
25
+ * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.
26
+ *
27
+ * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate
28
+ * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat
29
+ * id therefore has to come from an inbound message, never from the token.
30
+ */
24
31
  declare class TelegramAdapter extends BasePlatformAdapter {
25
32
  readonly platform: "telegram";
26
33
  private readonly bot;
package/dist/index.js CHANGED
@@ -182,7 +182,14 @@ var TelegramAdapter = class extends BasePlatformAdapter {
182
182
  */
183
183
  async dispatchEvent(event) {
184
184
  if (this.handler === void 0) return "no_handler";
185
- await this.handler(event);
185
+ try {
186
+ await this.handler(event);
187
+ } catch (err) {
188
+ const m = err instanceof Error ? err.message : String(err);
189
+ process.stderr.write(`[telegram] handler threw: ${m}
190
+ `);
191
+ return "handler_threw";
192
+ }
186
193
  return "ok";
187
194
  }
188
195
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/split.ts","../src/adapter.ts","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A6B;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 * 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\";\n\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n}\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\"> {\n if (this.handler === undefined) return \"no_handler\";\n await this.handler(event);\n return \"ok\";\n }\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional field; splitting hurts the \"one event normalization here\" locality.\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 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 const text = msg.text ?? msg.caption ?? \"\";\n const senderId = String(ctx.from?.id ?? \"anonymous\");\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: senderId,\n ...(ctx.from?.username !== undefined ? { username: ctx.from.username } : {}),\n ...(ctx.from?.first_name !== undefined ? { displayName: ctx.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,\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: ctx,\n },\n };\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
+ {"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AA,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 * 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\";\n\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\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// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: shape-mapping function — each branch is a small conditional spread for an optional field; splitting hurts the \"one event normalization here\" locality.\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 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 const text = msg.text ?? msg.caption ?? \"\";\n const senderId = String(ctx.from?.id ?? \"anonymous\");\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: senderId,\n ...(ctx.from?.username !== undefined ? { username: ctx.from.username } : {}),\n ...(ctx.from?.first_name !== undefined ? { displayName: ctx.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,\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: ctx,\n },\n };\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,8 +1,13 @@
1
1
  {
2
2
  "name": "@theokit/gateway-telegram",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Telegram (grammy) platform adapter for @theokit/gateway. ADR D171.",
5
5
  "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/usetheokit/theokit-gateways.git",
9
+ "directory": "packages/gateway-telegram"
10
+ },
6
11
  "type": "module",
7
12
  "engines": {
8
13
  "node": ">=22.12.0"
@@ -29,18 +34,21 @@
29
34
  "CHANGELOG.md"
30
35
  ],
31
36
  "peerDependencies": {
32
- "@theokit/sdk": "^2.18.0",
33
- "grammy": "^1.30.0",
34
- "@theokit/gateway": "^0.5.1"
37
+ "@theokit/gateway": ">=0.6.0 <1.0.0",
38
+ "grammy": "^1.30.0"
35
39
  },
36
40
  "devDependencies": {
37
- "@theokit/sdk": "^2.18.0",
41
+ "@theokit/sdk": "^4.53.1",
38
42
  "grammy": "^1.30.0",
39
43
  "tsup": "^8.5.0",
40
44
  "typescript": "^5.8.0",
41
45
  "vitest": "^4.1.8",
42
46
  "zod": "^4.0.0",
43
- "@theokit/gateway": "0.5.1"
47
+ "@theokit/gateway": "0.7.0"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public",
51
+ "provenance": true
44
52
  },
45
53
  "scripts": {
46
54
  "build": "tsup",