@theokit/gateway-telegram 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # Changelog
2
+
3
+ ## 2.0.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+ - @theokit/sdk@1.3.0
9
+ - @theokit/gateway@2.0.0
10
+
11
+ ## 1.0.0
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies
16
+ - @theokit/sdk@1.2.0
17
+ - @theokit/gateway@1.0.0
18
+
19
+ ## [0.1.0] — 2026-05-20
20
+
21
+ ### Added
22
+
23
+ - Initial release. `TelegramAdapter` wraps grammy in the `@theokit/gateway` `BasePlatformAdapter` contract.
24
+ - `shouldRespondInChat(ctx, policy)` helper for group-chat filtering.
25
+ - `splitForTelegram(text)` helper for auto-splitting >4096-char messages.
26
+ - EC-I: invalid token resolves `connect()` to `false` (never throws).
27
+ - EC-J: `splitForTelegram` preserves markdown pair integrity.
28
+ - EC-K: ignores messages where `ctx.from.is_bot === true`.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @theokit/gateway-telegram
2
+
3
+ Telegram platform adapter for `@theokit/gateway`. Wraps [grammy](https://grammy.dev/) in the `BasePlatformAdapter` contract.
4
+
5
+ > **Status: 0.1.0 — pre-release.**
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @theokit/gateway-telegram @theokit/gateway @theokit/sdk grammy
11
+ ```
12
+
13
+ `grammy` is a peer dep — install the version your bot needs.
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ import { GatewayRunner } from "@theokit/gateway";
19
+ import { TelegramAdapter } from "@theokit/gateway-telegram";
20
+
21
+ const adapter = new TelegramAdapter({
22
+ token: process.env.TELEGRAM_BOT_TOKEN!,
23
+ allowedUsers: ["7528967933"], // optional
24
+ });
25
+
26
+ const runner = new GatewayRunner({
27
+ adapters: [adapter],
28
+ handler: async (event, ctx) => {
29
+ await ctx.reply(`got: ${event.text}`);
30
+ },
31
+ });
32
+
33
+ await runner.start();
34
+ ```
35
+
36
+ ## Helpers
37
+
38
+ - `shouldRespondInChat(ctx, policy)` — group-chat policy (DM = always reply, group = only on `@mention` or reply-to-bot or slash command). Register as a `pre_inbound` hook.
39
+ - `splitForTelegram(text)` — auto-splits text >4096 chars across multiple `sendMessage` calls.
40
+
41
+ ## Platform escape hatch
42
+
43
+ For Telegram features not portable across platforms (voice transcription, photo OCR, sticker handling), use `event.telegram?.raw` to access the underlying grammy `Context`:
44
+
45
+ ```typescript
46
+ runner.onInbound(async (event) => {
47
+ if (event.platform !== "telegram") return;
48
+ const ctx = event.telegram.raw as import("grammy").Context;
49
+ if (ctx.message?.voice) { /* ... */ }
50
+ });
51
+ ```
52
+
53
+ ## License
54
+
55
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,257 @@
1
+ 'use strict';
2
+
3
+ var gateway = require('@theokit/gateway');
4
+ var grammy = require('grammy');
5
+
6
+ // src/adapter.ts
7
+
8
+ // src/split.ts
9
+ var TELEGRAM_MAX_MESSAGE = 4096;
10
+ var SAFE_CHUNK = 4e3;
11
+ function splitForTelegram(text) {
12
+ if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];
13
+ const parts = [];
14
+ let remaining = text;
15
+ while (remaining.length > 0) {
16
+ if (remaining.length <= SAFE_CHUNK) {
17
+ parts.push(remaining);
18
+ break;
19
+ }
20
+ let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
21
+ if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
22
+ if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;
23
+ let chunk = remaining.slice(0, boundary);
24
+ chunk = balanceMarkdownPairs(chunk);
25
+ boundary = chunk.length;
26
+ parts.push(chunk);
27
+ remaining = remaining.slice(boundary).replace(/^\n+/, "");
28
+ }
29
+ return parts;
30
+ }
31
+ function balanceMarkdownPairs(chunk) {
32
+ const markers = ["**", "__", "~~", "`"];
33
+ let out = chunk;
34
+ for (const m of markers) {
35
+ const count = countOccurrences(out, m);
36
+ if (count % 2 === 1) {
37
+ const lastIdx = out.lastIndexOf(m);
38
+ out = out.slice(0, lastIdx).trimEnd();
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+ function countOccurrences(haystack, needle) {
44
+ let count = 0;
45
+ let pos = 0;
46
+ while (true) {
47
+ const found = haystack.indexOf(needle, pos);
48
+ if (found === -1) break;
49
+ count += 1;
50
+ pos = found + needle.length;
51
+ }
52
+ return count;
53
+ }
54
+
55
+ // src/adapter.ts
56
+ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
57
+ platform = "telegram";
58
+ bot;
59
+ allowedUsers;
60
+ handler;
61
+ connected = false;
62
+ startPromise;
63
+ constructor(opts) {
64
+ super();
65
+ this.bot = new grammy.Bot(opts.token);
66
+ this.allowedUsers = new Set(opts.allowedUsers ?? []);
67
+ this.bot.on("message", async (ctx) => this.handleInbound(ctx));
68
+ this.bot.catch((err) => {
69
+ process.stderr.write(`[telegram] bot error: ${err.error?.message ?? err}
70
+ `);
71
+ });
72
+ }
73
+ /**
74
+ * Expose the underlying grammy `Bot` so consumers can register
75
+ * grammy-specific event handlers that don't fit the portable
76
+ * contract — `callbackQuery`, `bot.on(":voice")`, `bot.command(...)`,
77
+ * etc. Register BEFORE calling `runner.start()`.
78
+ *
79
+ * @public
80
+ */
81
+ getBot() {
82
+ return this.bot;
83
+ }
84
+ async connect() {
85
+ if (this.connected) return true;
86
+ try {
87
+ await this.bot.init();
88
+ } catch (err) {
89
+ process.stderr.write(`[telegram] connect failed: ${err.message}
90
+ `);
91
+ return false;
92
+ }
93
+ this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {
94
+ process.stderr.write(`[telegram] polling stopped: ${err.message}
95
+ `);
96
+ });
97
+ this.connected = true;
98
+ return true;
99
+ }
100
+ async disconnect() {
101
+ if (!this.connected) return;
102
+ this.connected = false;
103
+ try {
104
+ await this.bot.stop();
105
+ } catch {
106
+ }
107
+ if (this.startPromise !== void 0) {
108
+ await this.startPromise.catch(() => void 0);
109
+ this.startPromise = void 0;
110
+ }
111
+ }
112
+ // 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.
113
+ async sendMessage(out) {
114
+ if (out.text.length === 0) {
115
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
116
+ }
117
+ const chatIdNum = Number(out.channel.id);
118
+ if (Number.isNaN(chatIdNum)) {
119
+ return {
120
+ ok: false,
121
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
122
+ };
123
+ }
124
+ const parseMode = mapFormat(out.format);
125
+ const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
126
+ const chunks = splitForTelegram(out.text);
127
+ let lastId;
128
+ for (const chunk of chunks) {
129
+ try {
130
+ const msg = await this.bot.api.sendMessage(chatIdNum, chunk, {
131
+ ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
132
+ ...threadId !== void 0 ? { message_thread_id: threadId } : {},
133
+ ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
134
+ });
135
+ lastId = String(msg.message_id);
136
+ } catch (err) {
137
+ return mapSendError(err);
138
+ }
139
+ }
140
+ return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
141
+ }
142
+ onInbound(handler) {
143
+ this.handler = handler;
144
+ return () => {
145
+ if (this.handler === handler) this.handler = void 0;
146
+ };
147
+ }
148
+ async startTyping(channelId) {
149
+ const chatId = Number(channelId);
150
+ if (Number.isNaN(chatId)) return;
151
+ try {
152
+ await this.bot.api.sendChatAction(chatId, "typing");
153
+ } catch {
154
+ }
155
+ }
156
+ async handleInbound(ctx) {
157
+ if (this.handler === void 0) return;
158
+ if (ctx.from?.is_bot === true) return;
159
+ if (this.allowedUsers.size > 0) {
160
+ const senderId = String(ctx.from?.id ?? "");
161
+ if (!this.allowedUsers.has(senderId)) return;
162
+ }
163
+ const event = normalizeEvent(ctx);
164
+ if (event === void 0) return;
165
+ await this.handler(event);
166
+ }
167
+ };
168
+ function normalizeEvent(ctx) {
169
+ const chat = ctx.chat;
170
+ const msg = ctx.message;
171
+ if (chat === void 0 || msg === void 0) return void 0;
172
+ let channelType;
173
+ if (chat.type === "private") {
174
+ channelType = "dm";
175
+ } else if (msg.message_thread_id !== void 0) {
176
+ channelType = "thread";
177
+ } else {
178
+ channelType = "group";
179
+ }
180
+ const text = msg.text ?? msg.caption ?? "";
181
+ const senderId = String(ctx.from?.id ?? "anonymous");
182
+ return {
183
+ id: `tg-${chat.id}-${msg.message_id}`,
184
+ platform: "telegram",
185
+ sender: {
186
+ id: senderId,
187
+ ...ctx.from?.username !== void 0 ? { username: ctx.from.username } : {},
188
+ ...ctx.from?.first_name !== void 0 ? { displayName: ctx.from.first_name } : {}
189
+ },
190
+ channel: {
191
+ id: String(chat.id),
192
+ type: channelType,
193
+ ...msg.message_thread_id !== void 0 ? { topicId: String(msg.message_thread_id) } : {}
194
+ },
195
+ text,
196
+ receivedAt: msg.date * 1e3,
197
+ ...msg.reply_to_message?.message_id !== void 0 ? { replyTo: String(msg.reply_to_message.message_id) } : {},
198
+ telegram: {
199
+ chatId: chat.id,
200
+ messageId: msg.message_id,
201
+ ...msg.message_thread_id !== void 0 ? { threadId: msg.message_thread_id } : {},
202
+ raw: ctx
203
+ }
204
+ };
205
+ }
206
+ function mapFormat(format) {
207
+ if (format === "markdown") return "Markdown";
208
+ if (format === "html") return "HTML";
209
+ return void 0;
210
+ }
211
+ function mapSendError(err) {
212
+ if (err instanceof grammy.GrammyError) {
213
+ const description = err.description.toLowerCase();
214
+ if (description.includes("rate limit") || err.error_code === 429) {
215
+ return { ok: false, error: { code: "rate_limited", message: err.description } };
216
+ }
217
+ if (description.includes("forbidden") || err.error_code === 403) {
218
+ return { ok: false, error: { code: "no_permission", message: err.description } };
219
+ }
220
+ if (description.includes("parse")) {
221
+ return { ok: false, error: { code: "markdown_error", message: err.description } };
222
+ }
223
+ return {
224
+ ok: false,
225
+ error: { code: `telegram_${err.error_code}`, message: err.description }
226
+ };
227
+ }
228
+ if (err instanceof grammy.HttpError) {
229
+ return { ok: false, error: { code: "network_error", message: err.message } };
230
+ }
231
+ return { ok: false, error: { code: "unknown", message: err.message } };
232
+ }
233
+
234
+ // src/group-policy.ts
235
+ function shouldRespondInChat(ctx, policy) {
236
+ const chat = ctx.chat;
237
+ if (chat === void 0) return false;
238
+ if (chat.type === "private") return true;
239
+ const text = ctx.message?.text ?? ctx.message?.caption ?? "";
240
+ if (text.startsWith("/")) return true;
241
+ const replyTo = ctx.message?.reply_to_message;
242
+ if (replyTo?.from?.id === policy.botId) return true;
243
+ const mentionTag = `@${policy.botUsername.toLowerCase()}`;
244
+ if (text.toLowerCase().includes(mentionTag)) return true;
245
+ return false;
246
+ }
247
+ function stripBotMention(text, botUsername) {
248
+ const regex = new RegExp(`@${botUsername}`, "gi");
249
+ return text.replace(regex, "").trim();
250
+ }
251
+
252
+ exports.TelegramAdapter = TelegramAdapter;
253
+ exports.shouldRespondInChat = shouldRespondInChat;
254
+ exports.splitForTelegram = splitForTelegram;
255
+ exports.stripBotMention = stripBotMention;
256
+ //# sourceMappingURL=index.cjs.map
257
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/split.ts","../src/adapter.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError"],"mappings":";;;;;;;;AAMA,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,I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AC1D,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, ported from examples/telegram-pro\n * 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 let chunk = remaining.slice(0, boundary);\n chunk = balanceMarkdownPairs(chunk);\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 {\n /* ignore */\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.handler(event);\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, ported from\n * examples/telegram-pro/src/group-policy.ts).\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"]}
@@ -0,0 +1,95 @@
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
2
+ import { Bot, Context } from 'grammy';
3
+
4
+ /**
5
+ * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`
6
+ * `BasePlatformAdapter` contract (T5.1, ADR D171).
7
+ *
8
+ * - `connect()` calls `bot.start()` in the background; never throws on
9
+ * bad token (EC-I — returns `false`).
10
+ * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.
11
+ * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`
12
+ * never reaches the handler) — EC-K.
13
+ * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by
14
+ * chat/message/thread ids.
15
+ *
16
+ * @public
17
+ */
18
+
19
+ interface TelegramAdapterOptions {
20
+ readonly token: string;
21
+ /** Optional allow-list filter applied at the adapter level. */
22
+ readonly allowedUsers?: ReadonlyArray<string>;
23
+ }
24
+ declare class TelegramAdapter extends BasePlatformAdapter {
25
+ readonly platform: "telegram";
26
+ private readonly bot;
27
+ private readonly allowedUsers;
28
+ private handler?;
29
+ private connected;
30
+ private startPromise?;
31
+ constructor(opts: TelegramAdapterOptions);
32
+ /**
33
+ * Expose the underlying grammy `Bot` so consumers can register
34
+ * grammy-specific event handlers that don't fit the portable
35
+ * contract — `callbackQuery`, `bot.on(":voice")`, `bot.command(...)`,
36
+ * etc. Register BEFORE calling `runner.start()`.
37
+ *
38
+ * @public
39
+ */
40
+ getBot(): Bot;
41
+ connect(): Promise<boolean>;
42
+ disconnect(): Promise<void>;
43
+ sendMessage(out: OutboundMessage): Promise<SendResult>;
44
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
45
+ startTyping(channelId: string): Promise<void>;
46
+ private handleInbound;
47
+ }
48
+
49
+ /**
50
+ * Group-chat policy for Telegram bots (T5.1, ported from
51
+ * examples/telegram-pro/src/group-policy.ts).
52
+ *
53
+ * In private chats: respond to everything.
54
+ * In groups: respond only when:
55
+ * 1. the user @-mentions the bot OR
56
+ * 2. the message is a reply to one of the bot's earlier messages OR
57
+ * 3. it's a slash command (Telegram auto-routes those to the bot).
58
+ *
59
+ * Without this filter, a Telegram bot in a group becomes a noisemaker.
60
+ * Register as a `pre_inbound` hook on the runner.
61
+ *
62
+ * @public
63
+ */
64
+
65
+ /** Policy state. Build once per bot at boot from `bot.botInfo`. */
66
+ interface PolicyContext {
67
+ /** The bot's username (without leading `@`). */
68
+ readonly botUsername: string;
69
+ /** The bot's user id. Used to detect reply-to-bot. */
70
+ readonly botId: number;
71
+ }
72
+ /**
73
+ * Decide whether the bot should respond to this update.
74
+ * @public
75
+ */
76
+ declare function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean;
77
+ /** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */
78
+ declare function stripBotMention(text: string, botUsername: string): string;
79
+
80
+ /**
81
+ * Telegram's 4096-char per-message cap. Split agent responses on safe
82
+ * boundaries before sending (T5.1, ported from examples/telegram-pro
83
+ * with EC-J markdown-pair preservation).
84
+ */
85
+ /**
86
+ * Split a long text into Telegram-sized chunks, preferring paragraph,
87
+ * line, then hard boundaries. EC-J: when a chunk ends in the middle of
88
+ * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last
89
+ * complete pair so neither chunk produces a "markdown_parse_error" 400.
90
+ *
91
+ * @public
92
+ */
93
+ declare function splitForTelegram(text: string): string[];
94
+
95
+ export { type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, shouldRespondInChat, splitForTelegram, stripBotMention };
@@ -0,0 +1,95 @@
1
+ import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent } from '@theokit/gateway';
2
+ import { Bot, Context } from 'grammy';
3
+
4
+ /**
5
+ * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`
6
+ * `BasePlatformAdapter` contract (T5.1, ADR D171).
7
+ *
8
+ * - `connect()` calls `bot.start()` in the background; never throws on
9
+ * bad token (EC-I — returns `false`).
10
+ * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.
11
+ * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`
12
+ * never reaches the handler) — EC-K.
13
+ * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by
14
+ * chat/message/thread ids.
15
+ *
16
+ * @public
17
+ */
18
+
19
+ interface TelegramAdapterOptions {
20
+ readonly token: string;
21
+ /** Optional allow-list filter applied at the adapter level. */
22
+ readonly allowedUsers?: ReadonlyArray<string>;
23
+ }
24
+ declare class TelegramAdapter extends BasePlatformAdapter {
25
+ readonly platform: "telegram";
26
+ private readonly bot;
27
+ private readonly allowedUsers;
28
+ private handler?;
29
+ private connected;
30
+ private startPromise?;
31
+ constructor(opts: TelegramAdapterOptions);
32
+ /**
33
+ * Expose the underlying grammy `Bot` so consumers can register
34
+ * grammy-specific event handlers that don't fit the portable
35
+ * contract — `callbackQuery`, `bot.on(":voice")`, `bot.command(...)`,
36
+ * etc. Register BEFORE calling `runner.start()`.
37
+ *
38
+ * @public
39
+ */
40
+ getBot(): Bot;
41
+ connect(): Promise<boolean>;
42
+ disconnect(): Promise<void>;
43
+ sendMessage(out: OutboundMessage): Promise<SendResult>;
44
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
45
+ startTyping(channelId: string): Promise<void>;
46
+ private handleInbound;
47
+ }
48
+
49
+ /**
50
+ * Group-chat policy for Telegram bots (T5.1, ported from
51
+ * examples/telegram-pro/src/group-policy.ts).
52
+ *
53
+ * In private chats: respond to everything.
54
+ * In groups: respond only when:
55
+ * 1. the user @-mentions the bot OR
56
+ * 2. the message is a reply to one of the bot's earlier messages OR
57
+ * 3. it's a slash command (Telegram auto-routes those to the bot).
58
+ *
59
+ * Without this filter, a Telegram bot in a group becomes a noisemaker.
60
+ * Register as a `pre_inbound` hook on the runner.
61
+ *
62
+ * @public
63
+ */
64
+
65
+ /** Policy state. Build once per bot at boot from `bot.botInfo`. */
66
+ interface PolicyContext {
67
+ /** The bot's username (without leading `@`). */
68
+ readonly botUsername: string;
69
+ /** The bot's user id. Used to detect reply-to-bot. */
70
+ readonly botId: number;
71
+ }
72
+ /**
73
+ * Decide whether the bot should respond to this update.
74
+ * @public
75
+ */
76
+ declare function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean;
77
+ /** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */
78
+ declare function stripBotMention(text: string, botUsername: string): string;
79
+
80
+ /**
81
+ * Telegram's 4096-char per-message cap. Split agent responses on safe
82
+ * boundaries before sending (T5.1, ported from examples/telegram-pro
83
+ * with EC-J markdown-pair preservation).
84
+ */
85
+ /**
86
+ * Split a long text into Telegram-sized chunks, preferring paragraph,
87
+ * line, then hard boundaries. EC-J: when a chunk ends in the middle of
88
+ * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last
89
+ * complete pair so neither chunk produces a "markdown_parse_error" 400.
90
+ *
91
+ * @public
92
+ */
93
+ declare function splitForTelegram(text: string): string[];
94
+
95
+ export { type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, shouldRespondInChat, splitForTelegram, stripBotMention };
package/dist/index.js ADDED
@@ -0,0 +1,252 @@
1
+ import { BasePlatformAdapter } from '@theokit/gateway';
2
+ import { Bot, GrammyError, HttpError } from 'grammy';
3
+
4
+ // src/adapter.ts
5
+
6
+ // src/split.ts
7
+ var TELEGRAM_MAX_MESSAGE = 4096;
8
+ var SAFE_CHUNK = 4e3;
9
+ function splitForTelegram(text) {
10
+ if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];
11
+ const parts = [];
12
+ let remaining = text;
13
+ while (remaining.length > 0) {
14
+ if (remaining.length <= SAFE_CHUNK) {
15
+ parts.push(remaining);
16
+ break;
17
+ }
18
+ let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
19
+ if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
20
+ if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;
21
+ let chunk = remaining.slice(0, boundary);
22
+ chunk = balanceMarkdownPairs(chunk);
23
+ boundary = chunk.length;
24
+ parts.push(chunk);
25
+ remaining = remaining.slice(boundary).replace(/^\n+/, "");
26
+ }
27
+ return parts;
28
+ }
29
+ function balanceMarkdownPairs(chunk) {
30
+ const markers = ["**", "__", "~~", "`"];
31
+ let out = chunk;
32
+ for (const m of markers) {
33
+ const count = countOccurrences(out, m);
34
+ if (count % 2 === 1) {
35
+ const lastIdx = out.lastIndexOf(m);
36
+ out = out.slice(0, lastIdx).trimEnd();
37
+ }
38
+ }
39
+ return out;
40
+ }
41
+ function countOccurrences(haystack, needle) {
42
+ let count = 0;
43
+ let pos = 0;
44
+ while (true) {
45
+ const found = haystack.indexOf(needle, pos);
46
+ if (found === -1) break;
47
+ count += 1;
48
+ pos = found + needle.length;
49
+ }
50
+ return count;
51
+ }
52
+
53
+ // src/adapter.ts
54
+ var TelegramAdapter = class extends BasePlatformAdapter {
55
+ platform = "telegram";
56
+ bot;
57
+ allowedUsers;
58
+ handler;
59
+ connected = false;
60
+ startPromise;
61
+ constructor(opts) {
62
+ super();
63
+ this.bot = new Bot(opts.token);
64
+ this.allowedUsers = new Set(opts.allowedUsers ?? []);
65
+ this.bot.on("message", async (ctx) => this.handleInbound(ctx));
66
+ this.bot.catch((err) => {
67
+ process.stderr.write(`[telegram] bot error: ${err.error?.message ?? err}
68
+ `);
69
+ });
70
+ }
71
+ /**
72
+ * Expose the underlying grammy `Bot` so consumers can register
73
+ * grammy-specific event handlers that don't fit the portable
74
+ * contract — `callbackQuery`, `bot.on(":voice")`, `bot.command(...)`,
75
+ * etc. Register BEFORE calling `runner.start()`.
76
+ *
77
+ * @public
78
+ */
79
+ getBot() {
80
+ return this.bot;
81
+ }
82
+ async connect() {
83
+ if (this.connected) return true;
84
+ try {
85
+ await this.bot.init();
86
+ } catch (err) {
87
+ process.stderr.write(`[telegram] connect failed: ${err.message}
88
+ `);
89
+ return false;
90
+ }
91
+ this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {
92
+ process.stderr.write(`[telegram] polling stopped: ${err.message}
93
+ `);
94
+ });
95
+ this.connected = true;
96
+ return true;
97
+ }
98
+ async disconnect() {
99
+ if (!this.connected) return;
100
+ this.connected = false;
101
+ try {
102
+ await this.bot.stop();
103
+ } catch {
104
+ }
105
+ if (this.startPromise !== void 0) {
106
+ await this.startPromise.catch(() => void 0);
107
+ this.startPromise = void 0;
108
+ }
109
+ }
110
+ // 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.
111
+ async sendMessage(out) {
112
+ if (out.text.length === 0) {
113
+ return { ok: false, error: { code: "empty_text", message: "text is empty" } };
114
+ }
115
+ const chatIdNum = Number(out.channel.id);
116
+ if (Number.isNaN(chatIdNum)) {
117
+ return {
118
+ ok: false,
119
+ error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
120
+ };
121
+ }
122
+ const parseMode = mapFormat(out.format);
123
+ const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
124
+ const chunks = splitForTelegram(out.text);
125
+ let lastId;
126
+ for (const chunk of chunks) {
127
+ try {
128
+ const msg = await this.bot.api.sendMessage(chatIdNum, chunk, {
129
+ ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
130
+ ...threadId !== void 0 ? { message_thread_id: threadId } : {},
131
+ ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
132
+ });
133
+ lastId = String(msg.message_id);
134
+ } catch (err) {
135
+ return mapSendError(err);
136
+ }
137
+ }
138
+ return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
139
+ }
140
+ onInbound(handler) {
141
+ this.handler = handler;
142
+ return () => {
143
+ if (this.handler === handler) this.handler = void 0;
144
+ };
145
+ }
146
+ async startTyping(channelId) {
147
+ const chatId = Number(channelId);
148
+ if (Number.isNaN(chatId)) return;
149
+ try {
150
+ await this.bot.api.sendChatAction(chatId, "typing");
151
+ } catch {
152
+ }
153
+ }
154
+ async handleInbound(ctx) {
155
+ if (this.handler === void 0) return;
156
+ if (ctx.from?.is_bot === true) return;
157
+ if (this.allowedUsers.size > 0) {
158
+ const senderId = String(ctx.from?.id ?? "");
159
+ if (!this.allowedUsers.has(senderId)) return;
160
+ }
161
+ const event = normalizeEvent(ctx);
162
+ if (event === void 0) return;
163
+ await this.handler(event);
164
+ }
165
+ };
166
+ function normalizeEvent(ctx) {
167
+ const chat = ctx.chat;
168
+ const msg = ctx.message;
169
+ if (chat === void 0 || msg === void 0) return void 0;
170
+ let channelType;
171
+ if (chat.type === "private") {
172
+ channelType = "dm";
173
+ } else if (msg.message_thread_id !== void 0) {
174
+ channelType = "thread";
175
+ } else {
176
+ channelType = "group";
177
+ }
178
+ const text = msg.text ?? msg.caption ?? "";
179
+ const senderId = String(ctx.from?.id ?? "anonymous");
180
+ return {
181
+ id: `tg-${chat.id}-${msg.message_id}`,
182
+ platform: "telegram",
183
+ sender: {
184
+ id: senderId,
185
+ ...ctx.from?.username !== void 0 ? { username: ctx.from.username } : {},
186
+ ...ctx.from?.first_name !== void 0 ? { displayName: ctx.from.first_name } : {}
187
+ },
188
+ channel: {
189
+ id: String(chat.id),
190
+ type: channelType,
191
+ ...msg.message_thread_id !== void 0 ? { topicId: String(msg.message_thread_id) } : {}
192
+ },
193
+ text,
194
+ receivedAt: msg.date * 1e3,
195
+ ...msg.reply_to_message?.message_id !== void 0 ? { replyTo: String(msg.reply_to_message.message_id) } : {},
196
+ telegram: {
197
+ chatId: chat.id,
198
+ messageId: msg.message_id,
199
+ ...msg.message_thread_id !== void 0 ? { threadId: msg.message_thread_id } : {},
200
+ raw: ctx
201
+ }
202
+ };
203
+ }
204
+ function mapFormat(format) {
205
+ if (format === "markdown") return "Markdown";
206
+ if (format === "html") return "HTML";
207
+ return void 0;
208
+ }
209
+ function mapSendError(err) {
210
+ if (err instanceof GrammyError) {
211
+ const description = err.description.toLowerCase();
212
+ if (description.includes("rate limit") || err.error_code === 429) {
213
+ return { ok: false, error: { code: "rate_limited", message: err.description } };
214
+ }
215
+ if (description.includes("forbidden") || err.error_code === 403) {
216
+ return { ok: false, error: { code: "no_permission", message: err.description } };
217
+ }
218
+ if (description.includes("parse")) {
219
+ return { ok: false, error: { code: "markdown_error", message: err.description } };
220
+ }
221
+ return {
222
+ ok: false,
223
+ error: { code: `telegram_${err.error_code}`, message: err.description }
224
+ };
225
+ }
226
+ if (err instanceof HttpError) {
227
+ return { ok: false, error: { code: "network_error", message: err.message } };
228
+ }
229
+ return { ok: false, error: { code: "unknown", message: err.message } };
230
+ }
231
+
232
+ // src/group-policy.ts
233
+ function shouldRespondInChat(ctx, policy) {
234
+ const chat = ctx.chat;
235
+ if (chat === void 0) return false;
236
+ if (chat.type === "private") return true;
237
+ const text = ctx.message?.text ?? ctx.message?.caption ?? "";
238
+ if (text.startsWith("/")) return true;
239
+ const replyTo = ctx.message?.reply_to_message;
240
+ if (replyTo?.from?.id === policy.botId) return true;
241
+ const mentionTag = `@${policy.botUsername.toLowerCase()}`;
242
+ if (text.toLowerCase().includes(mentionTag)) return true;
243
+ return false;
244
+ }
245
+ function stripBotMention(text, botUsername) {
246
+ const regex = new RegExp(`@${botUsername}`, "gi");
247
+ return text.replace(regex, "").trim();
248
+ }
249
+
250
+ export { TelegramAdapter, shouldRespondInChat, splitForTelegram, stripBotMention };
251
+ //# sourceMappingURL=index.js.map
252
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/split.ts","../src/adapter.ts","../src/group-policy.ts"],"names":[],"mappings":";;;;;;AAMA,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;AAC1C,IAAA,IAAI,KAAA,GAAQ,SAAA,CAAU,KAAA,CAAM,CAAA,EAAG,QAAQ,CAAA;AACvC,IAAA,KAAA,G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,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, ported from examples/telegram-pro\n * 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 let chunk = remaining.slice(0, boundary);\n chunk = balanceMarkdownPairs(chunk);\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 {\n /* ignore */\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.handler(event);\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, ported from\n * examples/telegram-pro/src/group-policy.ts).\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 ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@theokit/gateway-telegram",
3
+ "version": "0.1.0",
4
+ "description": "Telegram (grammy) platform adapter for @theokit/gateway. ADR D171.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22.12.0"
9
+ },
10
+ "main": "./dist/index.cjs",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "import": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "require": {
20
+ "types": "./dist/index.d.cts",
21
+ "default": "./dist/index.cjs"
22
+ }
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE",
29
+ "CHANGELOG.md"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsup",
33
+ "typecheck": "tsc --noEmit",
34
+ "test": "vitest run"
35
+ },
36
+ "peerDependencies": {
37
+ "@theokit/gateway": "workspace:^",
38
+ "@theokit/sdk": "workspace:^",
39
+ "grammy": "^1.30.0"
40
+ },
41
+ "devDependencies": {
42
+ "@theokit/gateway": "workspace:*",
43
+ "@theokit/sdk": "workspace:*",
44
+ "grammy": "^1.30.0",
45
+ "tsup": "^8.5.0",
46
+ "typescript": "^5.8.0",
47
+ "vitest": "^3.0.0"
48
+ }
49
+ }