@theokit/gateway-telegram 0.3.1 → 0.4.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 +52 -0
- package/README.md +21 -0
- package/dist/index.cjs +61 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -2
- package/dist/index.d.ts +53 -2
- package/dist/index.js +61 -2
- package/dist/index.js.map +1 -1
- package/package.json +19 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,57 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 39d06f8: Wire channels from descriptors, and keep the channels that connect when another cannot.
|
|
8
|
+
|
|
9
|
+
`@theokit/gateway` exports `createChannels` and the types `ChannelDescriptor`,
|
|
10
|
+
`ChannelConfigField`, `ChannelWebhook`, `WebhookRequest`, `IngestResult`, `ChannelEntry`,
|
|
11
|
+
`ChannelRejection` and `CreateChannelsResult`. `createChannels(entries)` builds an adapter per
|
|
12
|
+
entry and returns `{ adapters, rejected }`: an entry whose required field is absent, `null` or
|
|
13
|
+
`""` is rejected with a `GatewayConfigurationError` coded `missing_required_config` naming the
|
|
14
|
+
keys, and a configuration error thrown by the descriptor's `create` is rejected the same way. Any
|
|
15
|
+
other error propagates. It connects nothing and makes no network call.
|
|
16
|
+
|
|
17
|
+
`GatewayRunner` accepts `connectFailure: "rollback" | "isolate"` (exported as `ConnectFailure`),
|
|
18
|
+
and `StartResult` is exported.
|
|
19
|
+
The default, `"rollback"`, is unchanged: one failed connect disconnects the adapters that did
|
|
20
|
+
connect and rejects `start()`. Under `"isolate"`, `start()` connects every adapter, wires inbound
|
|
21
|
+
only for the ones that connected, and reports the rest with a redacted reason.
|
|
22
|
+
|
|
23
|
+
`start()` now resolves a `StartResult` (`{ connected, failed }`) instead of `void`, under both
|
|
24
|
+
values. This is a type change: code that awaits `start()` and ignores the value is unaffected,
|
|
25
|
+
but a structural type declaring `start(): Promise<void>` that a `GatewayRunner` is assigned to
|
|
26
|
+
fails with TS2322, and a subclass overriding `start()` with that signature fails with TS2416.
|
|
27
|
+
|
|
28
|
+
`@theokit/gateway-telegram` exports `telegramChannel`, a socket channel whose config has a
|
|
29
|
+
required, secret `token` and an optional `allowedUsers`, and a `ConfigurationError` (a
|
|
30
|
+
`GatewayConfigurationError` with the `gateway-telegram` prefix). Called directly,
|
|
31
|
+
`telegramChannel.create` refuses a token that is not a string or is empty, and an `allowedUsers`
|
|
32
|
+
that is not an array of strings; through `createChannels`, an absent or empty token is rejected
|
|
33
|
+
first, as `missing_required_config`.
|
|
34
|
+
|
|
35
|
+
`@theokit/gateway-line` exports `lineChannel`, a webhook channel whose `webhook.verify` checks the
|
|
36
|
+
`x-line-signature` header against the raw body and whose `webhook.ingest` dispatches a verified
|
|
37
|
+
payload through `dispatchWebhookBody`, so a reply uses the cached reply token, or answers
|
|
38
|
+
`"malformed"` without dispatching. It answers `"no_handler"` (a member of `IngestResult`) when the
|
|
39
|
+
payload holds a text message for the handler and none is subscribed: before the runner started,
|
|
40
|
+
after it stopped, or when LINE's connect failed under `"isolate"`. Before, such a request answered
|
|
41
|
+
`"delivered"`, a route acknowledged it, and LINE did not redeliver the lost message.
|
|
42
|
+
`lineChannel.create` checks field types before the adapter's constructor.
|
|
43
|
+
|
|
44
|
+
`LineAdapter.dispatchWebhookBody` now resolves `"ok" | "no_handler"` instead of `void`. It answers
|
|
45
|
+
`"no_handler"`, dispatching nothing and caching no reply token, for a batch holding a text message
|
|
46
|
+
that passes the mention guard while no handler is subscribed; an empty or follow-only batch still
|
|
47
|
+
answers `"ok"`. It reads the handler once per batch, so a handler that unsubscribes while handling
|
|
48
|
+
one event still receives the rest of the batch. Code that ignores the value is unaffected; a
|
|
49
|
+
subclass overriding the method with `Promise<void>` fails with TS2416. `createWebhookServer` is
|
|
50
|
+
unchanged and still answers 200 before it dispatches.
|
|
51
|
+
|
|
52
|
+
Both descriptors are typed locally and import nothing `@theokit/gateway` 0.9.0 lacks, so the peer
|
|
53
|
+
range stays `>=0.9.0 <1.0.0`.
|
|
54
|
+
|
|
3
55
|
## 0.3.1
|
|
4
56
|
|
|
5
57
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -41,6 +41,27 @@ const runner = new GatewayRunner({
|
|
|
41
41
|
await runner.start();
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
+
## Channel descriptor
|
|
45
|
+
|
|
46
|
+
`telegramChannel` describes this channel as data, for `createChannels` in `@theokit/gateway`:
|
|
47
|
+
a `socket` channel (long polling, no webhook route) whose config has a required, secret `token`
|
|
48
|
+
and an optional `allowedUsers`.
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
import { createChannels } from "@theokit/gateway";
|
|
52
|
+
import { telegramChannel } from "@theokit/gateway-telegram";
|
|
53
|
+
|
|
54
|
+
const { adapters, rejected } = createChannels([
|
|
55
|
+
{ descriptor: telegramChannel, config: { token: process.env.TELEGRAM_BOT_TOKEN } },
|
|
56
|
+
]);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Through `createChannels`, an absent or empty token is caught before `create` runs, as a core
|
|
60
|
+
`GatewayConfigurationError` coded `missing_required_config`. `telegramChannel.create` itself
|
|
61
|
+
refuses a token that is not a string or is empty, and an `allowedUsers` that is not an array of
|
|
62
|
+
strings, with this package's `ConfigurationError` (also a `GatewayConfigurationError`), so
|
|
63
|
+
`createChannels` lists that channel in `rejected` too.
|
|
64
|
+
|
|
44
65
|
## Helpers
|
|
45
66
|
|
|
46
67
|
- `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.
|
package/dist/index.cjs
CHANGED
|
@@ -316,6 +316,65 @@ function mapSendError(err) {
|
|
|
316
316
|
}
|
|
317
317
|
return { ok: false, error: { code: "unknown", message: err.message } };
|
|
318
318
|
}
|
|
319
|
+
var ConfigurationError = class extends gateway.GatewayConfigurationError {
|
|
320
|
+
name = "ConfigurationError";
|
|
321
|
+
constructor(opts) {
|
|
322
|
+
super("gateway-telegram", opts);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
// src/channel.ts
|
|
327
|
+
function invalid(key, expected) {
|
|
328
|
+
return new ConfigurationError({
|
|
329
|
+
code: "invalid_config",
|
|
330
|
+
message: `gateway-telegram: config.${key} must be ${expected}`,
|
|
331
|
+
detail: key
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
function readToken(config) {
|
|
335
|
+
const token = config.token;
|
|
336
|
+
if (typeof token !== "string") throw invalid("token", "a string");
|
|
337
|
+
if (token.length === 0) {
|
|
338
|
+
throw new ConfigurationError({
|
|
339
|
+
code: "token_required",
|
|
340
|
+
message: "gateway-telegram: config.token is empty",
|
|
341
|
+
detail: "token"
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
return token;
|
|
345
|
+
}
|
|
346
|
+
function readAllowedUsers(config) {
|
|
347
|
+
const value = config.allowedUsers;
|
|
348
|
+
if (value === void 0 || value === null) return void 0;
|
|
349
|
+
if (!Array.isArray(value) || !value.every((id) => typeof id === "string")) {
|
|
350
|
+
throw invalid("allowedUsers", "an array of user id strings");
|
|
351
|
+
}
|
|
352
|
+
return value;
|
|
353
|
+
}
|
|
354
|
+
var CONFIG = [
|
|
355
|
+
{
|
|
356
|
+
key: "token",
|
|
357
|
+
required: true,
|
|
358
|
+
secret: true,
|
|
359
|
+
description: "The bot token BotFather issued for this bot."
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
key: "allowedUsers",
|
|
363
|
+
required: false,
|
|
364
|
+
secret: false,
|
|
365
|
+
description: "Telegram user ids allowed to reach the handler; absent or empty allows everyone."
|
|
366
|
+
}
|
|
367
|
+
];
|
|
368
|
+
var telegramChannel = {
|
|
369
|
+
platform: "telegram",
|
|
370
|
+
transport: "socket",
|
|
371
|
+
config: CONFIG,
|
|
372
|
+
create(config) {
|
|
373
|
+
const token = readToken(config);
|
|
374
|
+
const allowedUsers = readAllowedUsers(config);
|
|
375
|
+
return new TelegramAdapter(allowedUsers === void 0 ? { token } : { token, allowedUsers });
|
|
376
|
+
}
|
|
377
|
+
};
|
|
319
378
|
|
|
320
379
|
// src/group-policy.ts
|
|
321
380
|
function shouldRespondInChat(ctx, policy) {
|
|
@@ -335,10 +394,12 @@ function stripBotMention(text, botUsername) {
|
|
|
335
394
|
return text.replace(regex, "").trim();
|
|
336
395
|
}
|
|
337
396
|
|
|
397
|
+
exports.ConfigurationError = ConfigurationError;
|
|
338
398
|
exports.TelegramAdapter = TelegramAdapter;
|
|
339
399
|
exports.parseInbound = parseInbound;
|
|
340
400
|
exports.shouldRespondInChat = shouldRespondInChat;
|
|
341
401
|
exports.splitForTelegram = splitForTelegram;
|
|
342
402
|
exports.stripBotMention = stripBotMention;
|
|
403
|
+
exports.telegramChannel = telegramChannel;
|
|
343
404
|
//# sourceMappingURL=index.cjs.map
|
|
344
405
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError"],"mappings":";;;;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,IAAA,WAAA,GAAc,IAAA;AAAA,EAChB,CAAA,MAAA,IAAW,GAAA,CAAI,iBAAA,KAAsB,MAAA,EAAW;AAC9C,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB,CAAA,MAAO;AACL,IAAA,WAAA,GAAc,OAAA;AAAA,EAChB;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,CAAA,GAAA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U,GAAG,OAAO,IAAA;AACpD,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.cjs","sourcesContent":["/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\nconst TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await this.bot.api.sendMessage(chatIdNum, chunk, {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n });\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\nfunction mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts","../src/group-policy.ts"],"names":["BasePlatformAdapter","Bot","GrammyError","HttpError","GatewayConfigurationError"],"mappings":";;;;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,IAAA,WAAA,GAAc,IAAA;AAAA,EAChB,CAAA,MAAA,IAAW,GAAA,CAAI,iBAAA,KAAsB,MAAA,EAAW;AAC9C,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB,CAAA,MAAO;AACL,IAAA,WAAA,GAAc,OAAA;AAAA,EAChB;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,CAAA,GAAA,EAAM,IAAA,CAAK,EAAE,CAAA,CAAA,EAAI,IAAI,UAAU,CAAA,CAAA;AAAA,IACnC,QAAA,EAAU,UAAA;AAAA,IACV,MAAA,EAAQ;AAAA,MACN,EAAA,EAAI,MAAA,CAAO,IAAA,EAAM,EAAA,IAAM,WAAW,CAAA;AAAA,MAClC,GAAI,MAAM,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,EAAU,IAAA,CAAK,QAAA,EAAS,GAAI,EAAC;AAAA,MAClE,GAAI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D,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,IAAA;AACjC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAS,gBAAA;AAC7B,EAAA,IAAI,OAAA,EAAS,IAAA,EAAM,EAAA,KAAO,MAAA,CAAO,OAAO,OAAO,IAAA;AAC/C,EAAA,MAAM,UAAA,GAAa,CAAA,CAAA,EAAI,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA,CAAA;AACvD,EAAA,IAAI,KAAK,WAAA,EAAY,CAAE,QAAA,CAAS,UAAU,GAAG,OAAO,IAAA;AACpD,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.cjs","sourcesContent":["/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\nconst TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await this.bot.api.sendMessage(chatIdNum, chunk, {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n });\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\nfunction mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * Typed errors for `@theokit/gateway-telegram`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway\n * package's does, so `createChannels` reports a refused Telegram config as a rejected channel\n * rather than rethrowing it as a defect.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/**\n * Misconfiguration of the Telegram channel, raised before any network call.\n *\n * Carries a structured `code` the caller can branch on and, for a refused field, the field's key\n * in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it\n * is never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: GatewayConfigurationErrorOptions) {\n super(\"gateway-telegram\", opts);\n }\n}\n","/**\n * `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { TelegramAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-telegram: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\nfunction readToken(config: Readonly<Record<string, unknown>>): string {\n const token = config.token;\n if (typeof token !== \"string\") throw invalid(\"token\", \"a string\");\n if (token.length === 0) {\n // grammy's own `new Bot(\"\")` throws a plain Error, which `createChannels` would rethrow as a\n // defect instead of reporting the channel as rejected.\n throw new ConfigurationError({\n code: \"token_required\",\n message: \"gateway-telegram: config.token is empty\",\n detail: \"token\",\n });\n }\n return token;\n}\n\nfunction readAllowedUsers(config: Readonly<Record<string, unknown>>): string[] | undefined {\n const value = config.allowedUsers;\n if (value === undefined || value === null) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw invalid(\"allowedUsers\", \"an array of user id strings\");\n }\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"token\",\n required: true,\n secret: true,\n description: \"The bot token BotFather issued for this bot.\",\n },\n {\n key: \"allowedUsers\",\n required: false,\n secret: false,\n description: \"Telegram user ids allowed to reach the handler; absent or empty allows everyone.\",\n },\n];\n\n/**\n * The Telegram channel: a long-polling bot, so it needs no webhook route.\n *\n * `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is\n * not an array of strings, with this package's `ConfigurationError`; it performs no network call.\n *\n * @public\n */\nexport const telegramChannel = {\n platform: \"telegram\" as const,\n transport: \"socket\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n return new TelegramAdapter(allowedUsers === undefined ? { token } : { token, allowedUsers });\n },\n};\n","/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, TelegramMessageEvent } from '@theokit/gateway';
|
|
1
|
+
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from '@theokit/gateway';
|
|
2
2
|
import { Bot, Context } from 'grammy';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -67,6 +67,57 @@ declare class TelegramAdapter extends BasePlatformAdapter {
|
|
|
67
67
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
/**
|
|
71
|
+
* `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).
|
|
72
|
+
*
|
|
73
|
+
* Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as
|
|
74
|
+
* its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on
|
|
75
|
+
* that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the
|
|
76
|
+
* integration package assigns it to one, and its typecheck is where a drift between the two fails.
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */
|
|
80
|
+
interface ConfigField {
|
|
81
|
+
readonly key: string;
|
|
82
|
+
readonly required: boolean;
|
|
83
|
+
readonly secret: boolean;
|
|
84
|
+
readonly description: string;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The Telegram channel: a long-polling bot, so it needs no webhook route.
|
|
88
|
+
*
|
|
89
|
+
* `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is
|
|
90
|
+
* not an array of strings, with this package's `ConfigurationError`; it performs no network call.
|
|
91
|
+
*
|
|
92
|
+
* @public
|
|
93
|
+
*/
|
|
94
|
+
declare const telegramChannel: {
|
|
95
|
+
platform: "telegram";
|
|
96
|
+
transport: "socket";
|
|
97
|
+
config: readonly ConfigField[];
|
|
98
|
+
create(config: Readonly<Record<string, unknown>>): TelegramAdapter;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Typed errors for `@theokit/gateway-telegram`.
|
|
103
|
+
*
|
|
104
|
+
* `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway
|
|
105
|
+
* package's does, so `createChannels` reports a refused Telegram config as a rejected channel
|
|
106
|
+
* rather than rethrowing it as a defect.
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Misconfiguration of the Telegram channel, raised before any network call.
|
|
111
|
+
*
|
|
112
|
+
* Carries a structured `code` the caller can branch on and, for a refused field, the field's key
|
|
113
|
+
* in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it
|
|
114
|
+
* is never retried.
|
|
115
|
+
*/
|
|
116
|
+
declare class ConfigurationError extends GatewayConfigurationError {
|
|
117
|
+
readonly name = "ConfigurationError";
|
|
118
|
+
constructor(opts: GatewayConfigurationErrorOptions);
|
|
119
|
+
}
|
|
120
|
+
|
|
70
121
|
/**
|
|
71
122
|
* Group-chat policy for Telegram bots (T5.1).
|
|
72
123
|
*
|
|
@@ -154,4 +205,4 @@ declare function parseInbound(payload: unknown): TelegramMessageEvent | null;
|
|
|
154
205
|
*/
|
|
155
206
|
declare function splitForTelegram(text: string): string[];
|
|
156
207
|
|
|
157
|
-
export { type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention };
|
|
208
|
+
export { ConfigurationError, type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention, telegramChannel };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, TelegramMessageEvent } from '@theokit/gateway';
|
|
1
|
+
import { BasePlatformAdapter, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from '@theokit/gateway';
|
|
2
2
|
import { Bot, Context } from 'grammy';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -67,6 +67,57 @@ declare class TelegramAdapter extends BasePlatformAdapter {
|
|
|
67
67
|
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
/**
|
|
71
|
+
* `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).
|
|
72
|
+
*
|
|
73
|
+
* Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as
|
|
74
|
+
* its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on
|
|
75
|
+
* that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the
|
|
76
|
+
* integration package assigns it to one, and its typecheck is where a drift between the two fails.
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */
|
|
80
|
+
interface ConfigField {
|
|
81
|
+
readonly key: string;
|
|
82
|
+
readonly required: boolean;
|
|
83
|
+
readonly secret: boolean;
|
|
84
|
+
readonly description: string;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The Telegram channel: a long-polling bot, so it needs no webhook route.
|
|
88
|
+
*
|
|
89
|
+
* `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is
|
|
90
|
+
* not an array of strings, with this package's `ConfigurationError`; it performs no network call.
|
|
91
|
+
*
|
|
92
|
+
* @public
|
|
93
|
+
*/
|
|
94
|
+
declare const telegramChannel: {
|
|
95
|
+
platform: "telegram";
|
|
96
|
+
transport: "socket";
|
|
97
|
+
config: readonly ConfigField[];
|
|
98
|
+
create(config: Readonly<Record<string, unknown>>): TelegramAdapter;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Typed errors for `@theokit/gateway-telegram`.
|
|
103
|
+
*
|
|
104
|
+
* `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway
|
|
105
|
+
* package's does, so `createChannels` reports a refused Telegram config as a rejected channel
|
|
106
|
+
* rather than rethrowing it as a defect.
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Misconfiguration of the Telegram channel, raised before any network call.
|
|
111
|
+
*
|
|
112
|
+
* Carries a structured `code` the caller can branch on and, for a refused field, the field's key
|
|
113
|
+
* in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it
|
|
114
|
+
* is never retried.
|
|
115
|
+
*/
|
|
116
|
+
declare class ConfigurationError extends GatewayConfigurationError {
|
|
117
|
+
readonly name = "ConfigurationError";
|
|
118
|
+
constructor(opts: GatewayConfigurationErrorOptions);
|
|
119
|
+
}
|
|
120
|
+
|
|
70
121
|
/**
|
|
71
122
|
* Group-chat policy for Telegram bots (T5.1).
|
|
72
123
|
*
|
|
@@ -154,4 +205,4 @@ declare function parseInbound(payload: unknown): TelegramMessageEvent | null;
|
|
|
154
205
|
*/
|
|
155
206
|
declare function splitForTelegram(text: string): string[];
|
|
156
207
|
|
|
157
|
-
export { type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention };
|
|
208
|
+
export { ConfigurationError, type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention, telegramChannel };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BasePlatformAdapter } from '@theokit/gateway';
|
|
1
|
+
import { BasePlatformAdapter, GatewayConfigurationError } from '@theokit/gateway';
|
|
2
2
|
import { Bot, GrammyError, HttpError } from 'grammy';
|
|
3
3
|
|
|
4
4
|
// src/adapter.ts
|
|
@@ -314,6 +314,65 @@ function mapSendError(err) {
|
|
|
314
314
|
}
|
|
315
315
|
return { ok: false, error: { code: "unknown", message: err.message } };
|
|
316
316
|
}
|
|
317
|
+
var ConfigurationError = class extends GatewayConfigurationError {
|
|
318
|
+
name = "ConfigurationError";
|
|
319
|
+
constructor(opts) {
|
|
320
|
+
super("gateway-telegram", opts);
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
// src/channel.ts
|
|
325
|
+
function invalid(key, expected) {
|
|
326
|
+
return new ConfigurationError({
|
|
327
|
+
code: "invalid_config",
|
|
328
|
+
message: `gateway-telegram: config.${key} must be ${expected}`,
|
|
329
|
+
detail: key
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function readToken(config) {
|
|
333
|
+
const token = config.token;
|
|
334
|
+
if (typeof token !== "string") throw invalid("token", "a string");
|
|
335
|
+
if (token.length === 0) {
|
|
336
|
+
throw new ConfigurationError({
|
|
337
|
+
code: "token_required",
|
|
338
|
+
message: "gateway-telegram: config.token is empty",
|
|
339
|
+
detail: "token"
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
return token;
|
|
343
|
+
}
|
|
344
|
+
function readAllowedUsers(config) {
|
|
345
|
+
const value = config.allowedUsers;
|
|
346
|
+
if (value === void 0 || value === null) return void 0;
|
|
347
|
+
if (!Array.isArray(value) || !value.every((id) => typeof id === "string")) {
|
|
348
|
+
throw invalid("allowedUsers", "an array of user id strings");
|
|
349
|
+
}
|
|
350
|
+
return value;
|
|
351
|
+
}
|
|
352
|
+
var CONFIG = [
|
|
353
|
+
{
|
|
354
|
+
key: "token",
|
|
355
|
+
required: true,
|
|
356
|
+
secret: true,
|
|
357
|
+
description: "The bot token BotFather issued for this bot."
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
key: "allowedUsers",
|
|
361
|
+
required: false,
|
|
362
|
+
secret: false,
|
|
363
|
+
description: "Telegram user ids allowed to reach the handler; absent or empty allows everyone."
|
|
364
|
+
}
|
|
365
|
+
];
|
|
366
|
+
var telegramChannel = {
|
|
367
|
+
platform: "telegram",
|
|
368
|
+
transport: "socket",
|
|
369
|
+
config: CONFIG,
|
|
370
|
+
create(config) {
|
|
371
|
+
const token = readToken(config);
|
|
372
|
+
const allowedUsers = readAllowedUsers(config);
|
|
373
|
+
return new TelegramAdapter(allowedUsers === void 0 ? { token } : { token, allowedUsers });
|
|
374
|
+
}
|
|
375
|
+
};
|
|
317
376
|
|
|
318
377
|
// src/group-policy.ts
|
|
319
378
|
function shouldRespondInChat(ctx, policy) {
|
|
@@ -333,6 +392,6 @@ function stripBotMention(text, botUsername) {
|
|
|
333
392
|
return text.replace(regex, "").trim();
|
|
334
393
|
}
|
|
335
394
|
|
|
336
|
-
export { TelegramAdapter, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention };
|
|
395
|
+
export { ConfigurationError, TelegramAdapter, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention, telegramChannel };
|
|
337
396
|
//# sourceMappingURL=index.js.map
|
|
338
397
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/group-policy.ts"],"names":[],"mappings":";;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,IAAA,WAAA,GAAc,IAAA;AAAA,EAChB,CAAA,MAAA,IAAW,GAAA,CAAI,iBAAA,KAAsB,MAAA,EAAW;AAC9C,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB,CAAA,MAA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CAAY,aAAa,CAAA,CAAA;AACvD,EAAA,IAAI,KAAK,WAAA,EAAY,CAAE,QAAA,CAAS,UAAU,GAAG,OAAO,IAAA;AACpD,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.js","sourcesContent":["/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\nconst TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await this.bot.api.sendMessage(chatIdNum, chunk, {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n });\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\nfunction mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/parse-inbound.ts","../src/split.ts","../src/adapter.ts","../src/errors.ts","../src/channel.ts","../src/group-policy.ts"],"names":[],"mappings":";;;;;;AA+CO,SAAS,UAAA,CACd,IAAA,EACA,GAAA,EACA,IAAA,EACA,GAAA,EACsB;AACtB,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,IAAA,WAAA,GAAc,IAAA;AAAA,EAChB,CAAA,MAAA,IAAW,GAAA,CAAI,iBAAA,KAAsB,MAAA,EAAW;AAC9C,IAAA,WAAA,GAAc,QAAA;AAAA,EAChB,CAAA,MAAO;AACL,IAAA,WAAA,GAAc,OAAA;AAAA,EAChB;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,CAAA,GAAA,EAAM,IAAA,CAAK,EAAE,CAAA,CAAA,EAAI,IAAI,UAAU,CAAA,CAAA;AAAA,IACnC,QAAA,EAAU,UAAA;AAAA,IACV,MAAA,EAAQ;AAAA,MACN,EAAA,EAAI,MAAA,CAAO,IAAA,EAAM,EAAA,IAAM,WAAW,CAAA;AAAA,MAClC,GAAI,MAAM,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,EAAU,IAAA,CAAK,QAAA,EA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,OAAA,IAAW,EAAA;AAC1D,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,IAAA;AACjC,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAS,gBAAA;AAC7B,EAAA,IAAI,OAAA,EAAS,IAAA,EAAM,EAAA,KAAO,MAAA,CAAO,OAAO,OAAO,IAAA;AAC/C,EAAA,MAAM,UAAA,GAAa,CAAA,CAAA,EAAI,MAAA,CAAO,WAAA,CAAY,aAAa,CAAA,CAAA;AACvD,EAAA,IAAI,KAAK,WAAA,EAAY,CAAE,QAAA,CAAS,UAAU,GAAG,OAAO,IAAA;AACpD,EAAA,OAAO,KAAA;AACT;AAGO,SAAS,eAAA,CAAgB,MAAc,WAAA,EAA6B;AACzE,EAAA,MAAM,QAAQ,IAAI,MAAA,CAAO,CAAA,CAAA,EAAI,WAAW,IAAI,IAAI,CAAA;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,EAAE,EAAE,IAAA,EAAK;AACtC","file":"index.js","sourcesContent":["/**\n * Translating a raw Telegram `Update` into the canonical `MessageEvent`.\n *\n * This is the gateway's half of TheoKit's channel seam. `handleChannelWebhook` validates the\n * signature and hands the app `payload: unknown`, stating that the `@theokit/gateway-*` package\n * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is\n * fixed in core rather than extended per adapter.\n *\n * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its\n * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of\n * the same event — which is the failure this file exists to prevent, not merely a tidiness point.\n *\n * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on\n * a payload the adapter never saw, which is the entire point of a webhook.\n */\n\nimport type { TelegramMessageEvent } from \"@theokit/gateway\";\n\n/** The `chat` fields the mapping reads — structural, so grammy's `Chat` satisfies it too. */\ninterface ChatLike {\n readonly id: number;\n readonly type: string;\n}\n\n/** The `message` fields the mapping reads. */\ninterface MessageLike {\n readonly message_id: number;\n readonly date: number;\n readonly text?: string;\n readonly caption?: string;\n readonly message_thread_id?: number;\n readonly reply_to_message?: { readonly message_id?: number };\n}\n\n/** The `from` fields the mapping reads. */\ninterface UserLike {\n readonly id: number;\n readonly username?: string;\n readonly first_name?: string;\n}\n\n/**\n * The single mapping, shared by the polling loop and the webhook path.\n *\n * `raw` is whatever the caller held — a grammy `Context` when polling, the update object when\n * arriving by webhook. `TelegramMessageEvent.telegram.raw` is `unknown` precisely so both fit.\n */\nexport function buildEvent(\n chat: ChatLike,\n msg: MessageLike,\n from: UserLike | undefined,\n raw: unknown,\n): TelegramMessageEvent {\n let channelType: \"dm\" | \"group\" | \"thread\";\n if (chat.type === \"private\") {\n channelType = \"dm\";\n } else if (msg.message_thread_id !== undefined) {\n channelType = \"thread\";\n } else {\n channelType = \"group\";\n }\n\n return {\n id: `tg-${chat.id}-${msg.message_id}`,\n platform: \"telegram\",\n sender: {\n id: String(from?.id ?? \"anonymous\"),\n ...(from?.username !== undefined ? { username: from.username } : {}),\n ...(from?.first_name !== undefined ? { displayName: from.first_name } : {}),\n },\n channel: {\n id: String(chat.id),\n type: channelType,\n ...(msg.message_thread_id !== undefined ? { topicId: String(msg.message_thread_id) } : {}),\n },\n text: msg.text ?? msg.caption ?? \"\",\n // Telegram sends seconds; the canonical event is milliseconds.\n receivedAt: msg.date * 1000,\n ...(msg.reply_to_message?.message_id !== undefined\n ? { replyTo: String(msg.reply_to_message.message_id) }\n : {}),\n telegram: {\n chatId: chat.id,\n messageId: msg.message_id,\n ...(msg.message_thread_id !== undefined ? { threadId: msg.message_thread_id } : {}),\n raw,\n },\n };\n}\n\n/**\n * True when `value` is a non-null, non-array object — the only shape worth reading fields off.\n *\n * The `!Array.isArray` clause has **no observable effect at any current call site**, verified by\n * mutation: removing it leaves the whole suite green, because every array that reaches here fails\n * the field check on the next line anyway (`[].message` is `undefined`, `[].message_id` is\n * `undefined`). It is kept as a property of the helper rather than of its callers — a future caller\n * reading a field an array happens to have would need it — and this note exists so nobody reads its\n * surviving mutant as a coverage gap someone forgot to close.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Narrow the message's optional fields, dropping any that is not the type the event declares. */\nfunction narrowMessage(msg: Record<string, unknown>, messageId: number, date: number): MessageLike {\n const threadId = msg.message_thread_id;\n const replyTo = msg.reply_to_message;\n\n return {\n message_id: messageId,\n date,\n ...(typeof msg.text === \"string\" ? { text: msg.text } : {}),\n ...(typeof msg.caption === \"string\" ? { caption: msg.caption } : {}),\n ...(typeof threadId === \"number\" && Number.isFinite(threadId)\n ? { message_thread_id: threadId }\n : {}),\n ...(isRecord(replyTo) &&\n typeof replyTo.message_id === \"number\" &&\n Number.isFinite(replyTo.message_id)\n ? { reply_to_message: { message_id: replyTo.message_id } }\n : {}),\n };\n}\n\n/** Narrow the sender, or drop it entirely when it carries no usable id. */\nfunction narrowSender(value: unknown): UserLike | undefined {\n if (!isRecord(value)) return undefined;\n if (typeof value.id !== \"number\" || !Number.isFinite(value.id)) return undefined;\n\n return {\n id: value.id,\n ...(typeof value.username === \"string\" ? { username: value.username } : {}),\n ...(typeof value.first_name === \"string\" ? { first_name: value.first_name } : {}),\n };\n}\n\n/**\n * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.\n *\n * Returns `null` — never throws. The caller is `onMessage`, which TheoKit awaits BEFORE it builds\n * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely\n * and the 200 is never built. Measured against `theokit@0.48.14`; the original\n * rationale here (\"runs after the 200\") was measured false on 2026-08-24.\n *\n * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real\n * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:\n *\n * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —\n * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,\n * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,\n * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs\n * an error on every `null` will cry wolf.\n * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields\n * the mapping requires.\n *\n * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s\n * shipped translator returns a bare `undefined`, and diverging from the reference shape for a\n * distinction no consumer has asked for is the abstraction YAGNI refuses.\n *\n * @public\n */\nexport function parseInbound(payload: unknown): TelegramMessageEvent | null {\n if (!isRecord(payload)) return null;\n\n const msg = payload.message;\n if (!isRecord(msg)) return null;\n\n const messageId = msg.message_id;\n const date = msg.date;\n if (typeof messageId !== \"number\" || !Number.isFinite(messageId)) return null;\n // `Number.isFinite(date)` is not enough: `1e308` passes it and `date * 1000` then overflows to\n // `Infinity`, which is the same silent poisoning of every downstream ordering decision that\n // `NaN` produced. The conversion's RESULT is what has to be finite.\n if (typeof date !== \"number\" || !Number.isFinite(date * 1000)) return null;\n\n const chat = msg.chat;\n if (!isRecord(chat)) return null;\n if (typeof chat.id !== \"number\" || !Number.isFinite(chat.id)) return null;\n if (typeof chat.type !== \"string\") return null;\n\n return buildEvent(\n { id: chat.id, type: chat.type },\n narrowMessage(msg, messageId, date),\n narrowSender(msg.from),\n payload,\n );\n}\n","/**\n * Telegram's 4096-char per-message cap. Split agent responses on safe\n * boundaries before sending (T5.1, with EC-J markdown-pair preservation).\n */\n\nconst TELEGRAM_MAX_MESSAGE = 4096;\nconst SAFE_CHUNK = 4000;\n\n/**\n * Split a long text into Telegram-sized chunks, preferring paragraph,\n * line, then hard boundaries. EC-J: when a chunk ends in the middle of\n * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last\n * complete pair so neither chunk produces a \"markdown_parse_error\" 400.\n *\n * @public\n */\nexport function splitForTelegram(text: string): string[] {\n if (text.length <= TELEGRAM_MAX_MESSAGE) return [text];\n const parts: string[] = [];\n let remaining = text;\n while (remaining.length > 0) {\n if (remaining.length <= SAFE_CHUNK) {\n parts.push(remaining);\n break;\n }\n let boundary = remaining.lastIndexOf(\"\\n\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf(\"\\n\", SAFE_CHUNK);\n if (boundary < SAFE_CHUNK / 2) boundary = SAFE_CHUNK;\n const rawChunk = remaining.slice(0, boundary);\n const balanced = balanceMarkdownPairs(rawChunk);\n // Forward progress is not negotiable. `balanceMarkdownPairs` trims back to\n // before an unbalanced marker, and when the only such marker sits at index 0\n // there is nothing to trim back TO — it returns \"\". Taking that as the\n // boundary made `remaining.slice(0)` return the same string on every pass:\n // an unbounded array of \"\" and a pegged core. The loop is synchronous, so it\n // blocks the event loop and no test timeout can interrupt it; the process\n // has to be killed. Any agent reply over the cap that opened with an\n // unclosed code span hung the bot.\n //\n // When balancing would consume the whole chunk, emit the unbalanced one\n // instead. Telegram answers that with a markdown_parse_error the caller can\n // see and map; a hung process shows nothing at all. This mirrors the core\n // chunker's `cut <= 0 ? window : cut`.\n const chunk = balanced.length > 0 ? balanced : rawChunk;\n boundary = chunk.length;\n parts.push(chunk);\n remaining = remaining.slice(boundary).replace(/^\\n+/, \"\");\n }\n return parts;\n}\n\n/**\n * EC-J: trim back to before an unbalanced markdown marker so the\n * chunk passes Telegram MarkdownV1 parsing.\n */\nfunction balanceMarkdownPairs(chunk: string): string {\n const markers = [\"**\", \"__\", \"~~\", \"`\"];\n let out = chunk;\n for (const m of markers) {\n const count = countOccurrences(out, m);\n if (count % 2 === 1) {\n const lastIdx = out.lastIndexOf(m);\n out = out.slice(0, lastIdx).trimEnd();\n }\n }\n return out;\n}\n\nfunction countOccurrences(haystack: string, needle: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const found = haystack.indexOf(needle, pos);\n if (found === -1) break;\n count += 1;\n pos = found + needle.length;\n }\n return count;\n}\n","/**\n * `TelegramAdapter` — wraps grammy in the `@theokit/gateway`\n * `BasePlatformAdapter` contract (T5.1, ADR D171).\n *\n * - `connect()` calls `bot.start()` in the background; never throws on\n * bad token (EC-I — returns `false`).\n * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.\n * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`\n * never reaches the handler) — EC-K.\n * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by\n * chat/message/thread ids.\n *\n * @public\n */\n\nimport type { MessageEvent as GatewayMessageEvent, TelegramMessageEvent } from \"@theokit/gateway\";\nimport { BasePlatformAdapter, type OutboundMessage, type SendResult } from \"@theokit/gateway\";\nimport { Bot, type Context, GrammyError, HttpError } from \"grammy\";\nimport { buildEvent } from \"./parse-inbound.js\";\nimport { splitForTelegram } from \"./split.js\";\n\nexport interface TelegramAdapterOptions {\n /**\n * The Telegram bot token.\n *\n * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the\n * name here is theirs.\n * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.\n */\n readonly token: string;\n /** Optional allow-list filter applied at the adapter level. */\n readonly allowedUsers?: ReadonlyArray<string>;\n}\n\n/**\n * Telegram gateway adapter — long-polls for updates, so inbound needs no public URL.\n *\n * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate\n * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat\n * id therefore has to come from an inbound message, never from the token.\n */\nexport class TelegramAdapter extends BasePlatformAdapter {\n readonly platform = \"telegram\" as const;\n private readonly bot: Bot;\n private readonly allowedUsers: Set<string>;\n private handler?: (event: GatewayMessageEvent) => Promise<void>;\n private connected = false;\n private startPromise?: Promise<void>;\n\n constructor(opts: TelegramAdapterOptions) {\n super();\n this.bot = new Bot(opts.token);\n this.allowedUsers = new Set(opts.allowedUsers ?? []);\n this.bot.on(\"message\", async (ctx) => this.handleInbound(ctx));\n this.bot.catch((err) => {\n process.stderr.write(`[telegram] bot error: ${(err.error as Error)?.message ?? err}\\n`);\n });\n }\n\n /**\n * Expose the underlying grammy `Bot` so consumers can register\n * grammy-specific event handlers that don't fit the portable\n * contract — `callbackQuery`, `bot.on(\":voice\")`, `bot.command(...)`,\n * etc. Register BEFORE calling `runner.start()`.\n *\n * @public\n */\n getBot(): Bot {\n return this.bot;\n }\n\n override async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n await this.bot.init();\n } catch (err) {\n // EC-I: invalid token → return false, never throw.\n process.stderr.write(`[telegram] connect failed: ${(err as Error).message}\\n`);\n return false;\n }\n this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {\n process.stderr.write(`[telegram] polling stopped: ${(err as Error).message}\\n`);\n });\n this.connected = true;\n return true;\n }\n\n override async disconnect(): Promise<void> {\n if (!this.connected) return;\n this.connected = false;\n try {\n await this.bot.stop();\n } catch (cause) {\n // PV#7 / T8.1 of arch-review-fixes-2026-06-06: disconnect must remain\n // idempotent + safe (catch is intentional — bot may already be torn down\n // by Telegram or by a prior signal handler). The empty-swallow violated\n // Unbreakable Rule 8 by hiding the diagnostic. Emit a structured stderr\n // message including the underlying error while preserving the\n // never-throw contract callers depend on.\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(\n `[theokit-gateway-telegram] bot.stop() failed during disconnect: ${message}\\n`,\n );\n }\n if (this.startPromise !== undefined) {\n await this.startPromise.catch(() => undefined);\n this.startPromise = undefined;\n }\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.\n override async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"text is empty\" } };\n }\n const chatIdNum = Number(out.channel.id);\n if (Number.isNaN(chatIdNum)) {\n return {\n ok: false,\n error: { code: \"invalid_channel\", message: `channel.id \"${out.channel.id}\" not numeric` },\n };\n }\n const parseMode = mapFormat(out.format);\n const threadId = out.channel.topicId !== undefined ? Number(out.channel.topicId) : undefined;\n const chunks = splitForTelegram(out.text);\n let lastId: string | undefined;\n for (const chunk of chunks) {\n try {\n const msg = await this.bot.api.sendMessage(chatIdNum, chunk, {\n ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),\n ...(threadId !== undefined ? { message_thread_id: threadId } : {}),\n ...(out.replyTo !== undefined\n ? { reply_parameters: { message_id: Number(out.replyTo) } }\n : {}),\n });\n lastId = String(msg.message_id);\n } catch (err) {\n return mapSendError(err);\n }\n }\n return { ok: true, ...(lastId !== undefined ? { messageId: lastId } : {}) };\n }\n\n override onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace previous handler (do not stack).\n this.handler = handler;\n return () => {\n if (this.handler === handler) this.handler = undefined;\n };\n }\n\n override async startTyping(channelId: string): Promise<void> {\n const chatId = Number(channelId);\n if (Number.isNaN(chatId)) return;\n try {\n await this.bot.api.sendChatAction(chatId, \"typing\");\n } catch {\n /* cosmetic — swallow (EC-O) */\n }\n }\n\n private async handleInbound(ctx: Context): Promise<void> {\n if (this.handler === undefined) return;\n // EC-K: ignore messages from other bots.\n if (ctx.from?.is_bot === true) return;\n if (this.allowedUsers.size > 0) {\n const senderId = String(ctx.from?.id ?? \"\");\n if (!this.allowedUsers.has(senderId)) return;\n }\n const event = normalizeEvent(ctx);\n if (event === undefined) return;\n await this.dispatchEvent(event);\n }\n\n /**\n * Dispatch a pre-built event to the current handler, honouring EC-H replace\n * semantics.\n *\n * Mirrors the seam `gateway-sms` already exposes. It exists because the EC-H\n * contract had no honest test without it: a grammy `Context` cannot be\n * synthesized here, `handler` is private, and the test that claimed to cover\n * replacement asserted an empty array — true whether onInbound replaces,\n * stacks, or discards.\n *\n * @internal\n */\n async dispatchEvent(event: GatewayMessageEvent): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n if (this.handler === undefined) return \"no_handler\";\n try {\n await this.handler(event);\n } catch (err) {\n // Left uncaught, the rejection escaped into the platform's own error channel and was reported\n // as a client error — so a bug in the consumer's handler read as a fault in the platform\n // library, sending whoever debugged it to the wrong repository (#41). A handler is user code:\n // its failure is named as such, and delivery continues.\n const m = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[telegram] handler threw: ${m}\\n`);\n return \"handler_threw\";\n }\n return \"ok\";\n }\n\n /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.handler, event);\n }\n}\n\n/**\n * Adapt grammy's `Context` to the shared mapping in `parse-inbound.ts`.\n *\n * The mapping itself is NOT here: a polled update and a webhook-delivered one must produce the\n * same event, and the only way to guarantee that is for one function to build both.\n */\nfunction normalizeEvent(ctx: Context): TelegramMessageEvent | undefined {\n const chat = ctx.chat;\n const msg = ctx.message;\n if (chat === undefined || msg === undefined) return undefined;\n\n return buildEvent(chat, msg, ctx.from, ctx);\n}\n\nfunction mapFormat(\n format: \"plain\" | \"markdown\" | \"html\" | undefined,\n): \"Markdown\" | \"HTML\" | undefined {\n if (format === \"markdown\") return \"Markdown\";\n if (format === \"html\") return \"HTML\";\n return undefined;\n}\n\nfunction mapSendError(err: unknown): SendResult {\n if (err instanceof GrammyError) {\n const description = err.description.toLowerCase();\n if (description.includes(\"rate limit\") || err.error_code === 429) {\n return { ok: false, error: { code: \"rate_limited\", message: err.description } };\n }\n if (description.includes(\"forbidden\") || err.error_code === 403) {\n return { ok: false, error: { code: \"no_permission\", message: err.description } };\n }\n if (description.includes(\"parse\")) {\n return { ok: false, error: { code: \"markdown_error\", message: err.description } };\n }\n return {\n ok: false,\n error: { code: `telegram_${err.error_code}`, message: err.description },\n };\n }\n if (err instanceof HttpError) {\n return { ok: false, error: { code: \"network_error\", message: err.message } };\n }\n return { ok: false, error: { code: \"unknown\", message: (err as Error).message } };\n}\n","/**\n * Typed errors for `@theokit/gateway-telegram`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway\n * package's does, so `createChannels` reports a refused Telegram config as a rejected channel\n * rather than rethrowing it as a defect.\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/**\n * Misconfiguration of the Telegram channel, raised before any network call.\n *\n * Carries a structured `code` the caller can branch on and, for a refused field, the field's key\n * in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it\n * is never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: GatewayConfigurationErrorOptions) {\n super(\"gateway-telegram\", opts);\n }\n}\n","/**\n * `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { TelegramAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-telegram: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\nfunction readToken(config: Readonly<Record<string, unknown>>): string {\n const token = config.token;\n if (typeof token !== \"string\") throw invalid(\"token\", \"a string\");\n if (token.length === 0) {\n // grammy's own `new Bot(\"\")` throws a plain Error, which `createChannels` would rethrow as a\n // defect instead of reporting the channel as rejected.\n throw new ConfigurationError({\n code: \"token_required\",\n message: \"gateway-telegram: config.token is empty\",\n detail: \"token\",\n });\n }\n return token;\n}\n\nfunction readAllowedUsers(config: Readonly<Record<string, unknown>>): string[] | undefined {\n const value = config.allowedUsers;\n if (value === undefined || value === null) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw invalid(\"allowedUsers\", \"an array of user id strings\");\n }\n return value;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"token\",\n required: true,\n secret: true,\n description: \"The bot token BotFather issued for this bot.\",\n },\n {\n key: \"allowedUsers\",\n required: false,\n secret: false,\n description: \"Telegram user ids allowed to reach the handler; absent or empty allows everyone.\",\n },\n];\n\n/**\n * The Telegram channel: a long-polling bot, so it needs no webhook route.\n *\n * `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is\n * not an array of strings, with this package's `ConfigurationError`; it performs no network call.\n *\n * @public\n */\nexport const telegramChannel = {\n platform: \"telegram\" as const,\n transport: \"socket\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): TelegramAdapter {\n const token = readToken(config);\n const allowedUsers = readAllowedUsers(config);\n return new TelegramAdapter(allowedUsers === undefined ? { token } : { token, allowedUsers });\n },\n};\n","/**\n * Group-chat policy for Telegram bots (T5.1).\n *\n * In private chats: respond to everything.\n * In groups: respond only when:\n * 1. the user @-mentions the bot OR\n * 2. the message is a reply to one of the bot's earlier messages OR\n * 3. it's a slash command (Telegram auto-routes those to the bot).\n *\n * Without this filter, a Telegram bot in a group becomes a noisemaker.\n * Register as a `pre_inbound` hook on the runner.\n *\n * @public\n */\n\nimport type { Context } from \"grammy\";\n\n/** Policy state. Build once per bot at boot from `bot.botInfo`. */\nexport interface PolicyContext {\n /** The bot's username (without leading `@`). */\n readonly botUsername: string;\n /** The bot's user id. Used to detect reply-to-bot. */\n readonly botId: number;\n}\n\n/**\n * Decide whether the bot should respond to this update.\n * @public\n */\nexport function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean {\n const chat = ctx.chat;\n if (chat === undefined) return false;\n if (chat.type === \"private\") return true;\n const text = ctx.message?.text ?? ctx.message?.caption ?? \"\";\n if (text.startsWith(\"/\")) return true;\n const replyTo = ctx.message?.reply_to_message;\n if (replyTo?.from?.id === policy.botId) return true;\n const mentionTag = `@${policy.botUsername.toLowerCase()}`;\n if (text.toLowerCase().includes(mentionTag)) return true;\n return false;\n}\n\n/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */\nexport function stripBotMention(text: string, botUsername: string): string {\n const regex = new RegExp(`@${botUsername}`, \"gi\");\n return text.replace(regex, \"\").trim();\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-telegram",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Telegram (grammy) platform adapter for @theokit/gateway. ADR D171.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"types": "./dist/index.d.cts",
|
|
26
26
|
"default": "./dist/index.cjs"
|
|
27
27
|
}
|
|
28
|
-
}
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
29
30
|
},
|
|
30
31
|
"files": [
|
|
31
32
|
"dist",
|
|
@@ -46,12 +47,27 @@
|
|
|
46
47
|
"typescript": "5.9.3",
|
|
47
48
|
"vitest": "^4.1.11",
|
|
48
49
|
"zod": "^4.0.0",
|
|
49
|
-
"@theokit/gateway": "0.
|
|
50
|
+
"@theokit/gateway": "0.11.0"
|
|
50
51
|
},
|
|
51
52
|
"publishConfig": {
|
|
52
53
|
"access": "public",
|
|
53
54
|
"provenance": true
|
|
54
55
|
},
|
|
56
|
+
"sideEffects": false,
|
|
57
|
+
"bugs": {
|
|
58
|
+
"url": "https://github.com/usetheokit/theokit-gateways/issues"
|
|
59
|
+
},
|
|
60
|
+
"homepage": "https://github.com/usetheokit/theokit-gateways/tree/main/packages/gateway-telegram#readme",
|
|
61
|
+
"keywords": [
|
|
62
|
+
"theokit",
|
|
63
|
+
"gateway",
|
|
64
|
+
"telegram",
|
|
65
|
+
"grammy",
|
|
66
|
+
"platform",
|
|
67
|
+
"adapter",
|
|
68
|
+
"adr",
|
|
69
|
+
"d171"
|
|
70
|
+
],
|
|
55
71
|
"scripts": {
|
|
56
72
|
"build": "tsup",
|
|
57
73
|
"typecheck": "tsc --noEmit",
|