loopzero-gateway-telegram 0.0.0-stage → 0.2.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.
@@ -0,0 +1,283 @@
1
+ import { Bot, Context } from 'grammy';
2
+ import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, FileUploadCapability, ButtonCapability, StreamingPreviewCapability, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from 'loopzero-gateway';
3
+
4
+ /**
5
+ * `TelegramAdapter` — wraps grammy in the `loopzero-gateway`
6
+ * `BasePlatformAdapter` contract (T5.1, ADR D171).
7
+ *
8
+ * - `connect()` calls `bot.start()` in the background; never throws on
9
+ * bad token (EC-I — returns `false`).
10
+ * - `sendMessage` auto-splits text >4096 chars via `splitForTelegram`.
11
+ * - Bot-to-bot loops blocked at the adapter (`ctx.from.is_bot === true`
12
+ * never reaches the handler) — EC-K.
13
+ * - `normalizeEvent` produces a `TelegramMessageEvent` keyed by
14
+ * chat/message/thread ids.
15
+ *
16
+ * @public
17
+ */
18
+
19
+ interface TelegramAdapterOptions {
20
+ /**
21
+ * The Telegram bot token.
22
+ *
23
+ * @platform-term Telegram calls this a **bot token** and `grammy` names the field `token`, so the
24
+ * name here is theirs.
25
+ * @issued-at BotFather, in Telegram itself, when the bot is created or its token regenerated.
26
+ */
27
+ readonly token: string;
28
+ /** Optional allow-list filter applied at the adapter level. */
29
+ readonly allowedUsers?: ReadonlyArray<string>;
30
+ /**
31
+ * How updates arrive. `"polling"` (default) pulls them with long polling; `"webhook"` only marks
32
+ * the adapter connected, and updates arrive through `deliver()`.
33
+ */
34
+ readonly inbound?: "polling" | "webhook";
35
+ /**
36
+ * When true, a group or supergroup message reaches the handler only if it mentions the bot,
37
+ * replies to one of the bot's messages, or is a slash command. Private chats always pass.
38
+ * Default false (today's behaviour).
39
+ */
40
+ readonly requireMention?: boolean;
41
+ /**
42
+ * Bot API root, for a self-hosted Bot API server or a fake one in tests. Default
43
+ * `"https://api.telegram.org"`. Voice-note downloads use the same root. A trailing slash is ignored.
44
+ */
45
+ readonly apiBase?: string;
46
+ }
47
+ /**
48
+ * Telegram gateway adapter — long-polls for updates by default, so inbound needs no public URL.
49
+ * With `inbound: "webhook"` it does not poll; updates arrive through `deliver()`.
50
+ *
51
+ * Two platform rules shape what this can do, and neither has a workaround: a bot cannot enumerate
52
+ * the chats it belongs to, and it cannot speak into a chat that has not spoken to it first. A chat
53
+ * id therefore has to come from an inbound message, never from the token.
54
+ */
55
+ declare class TelegramAdapter extends BasePlatformAdapter {
56
+ get capabilities(): AdapterCapabilities;
57
+ readonly platform: "telegram";
58
+ private readonly bot;
59
+ private readonly allowedUsers;
60
+ private handler?;
61
+ private readonly inbound;
62
+ private readonly requireMention;
63
+ private readonly apiBase;
64
+ private warnedNoIdentity;
65
+ private connected;
66
+ private startPromise?;
67
+ constructor(opts: TelegramAdapterOptions);
68
+ /**
69
+ * Expose the underlying grammy `Bot` so consumers can register
70
+ * grammy-specific event handlers that don't fit the portable
71
+ * contract — `callbackQuery`, `bot.on(":voice")`, `bot.command(...)`,
72
+ * etc. Register BEFORE calling `runner.start()`.
73
+ *
74
+ * @public
75
+ */
76
+ getBot(): Bot;
77
+ connect(): Promise<boolean>;
78
+ disconnect(): Promise<void>;
79
+ sendMessage(out: OutboundMessage): Promise<SendResult>;
80
+ /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
81
+ readonly supportsAttachments = true;
82
+ /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
83
+ protected readonly attachmentKinds: readonly ["image", "audio"];
84
+ /** Telegram sends a file through `sendDocument`: any media type, up to 50 MiB. */
85
+ readonly fileUpload: FileUploadCapability;
86
+ /**
87
+ * Telegram shows rows of buttons under a message as an inline keyboard: URL buttons, and
88
+ * `web_app` buttons that open a Mini App in a private chat. A `callback` button is refused until
89
+ * the adapter receives `callback_query` updates.
90
+ */
91
+ readonly buttonSupport: ButtonCapability;
92
+ /** Telegram edits a sent message's text through `editMessageText`. */
93
+ readonly supportsEdit = true;
94
+ /**
95
+ * A streamed reply is previewed by editing one message. Telegram allows about one message per
96
+ * second in a chat, and an edit of up to 4096 characters is one `editMessageText`.
97
+ */
98
+ readonly streamingPreview: StreamingPreviewCapability;
99
+ /**
100
+ * Replace the text of a message this bot sent, through `editMessageText`.
101
+ *
102
+ * Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no
103
+ * Telegram edit adds an image), empty text, a message id that is not a safe positive integer,
104
+ * and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own
105
+ * checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit
106
+ * replaces one message. Telegram's "message is not modified" refusal is answered as a success,
107
+ * because the message already shows the text; a caller that treated it as a failure would send
108
+ * the same text again as a second message.
109
+ */
110
+ editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
111
+ private editText;
112
+ react(channelId: string, messageId: string, emoji: string): Promise<SendResult>;
113
+ onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
114
+ startTyping(channelId: string): Promise<void>;
115
+ private handleInbound;
116
+ /**
117
+ * Marks whether the bot was addressed and applies the `requireMention` gate, shared by the
118
+ * polled and webhook paths. Returns `undefined` when the gate drops the event. A direct message
119
+ * is left unmarked; `addressed` stays unset while the bot's identity is not known.
120
+ */
121
+ private gateMention;
122
+ /**
123
+ * The event with the voice note's audio when the message has one (B-715, ADR D1), or with the
124
+ * audio file's when it carries one instead (`message.audio`, OC-103). A message holds at most
125
+ * one of the two.
126
+ *
127
+ * The audio is deferred: no request leaves here, so a `pre_inbound` hook that refuses the event
128
+ * costs no download. An unreadable voice or audio file rejects `audio.read()` and writes the
129
+ * reason to stderr.
130
+ */
131
+ private withVoice;
132
+ /**
133
+ * The event with the message's document as `files`, when it has one. Deferred like the voice
134
+ * note: no request leaves here. An unreadable document rejects `read()` and writes the reason
135
+ * to stderr.
136
+ */
137
+ private withDocument;
138
+ /**
139
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
140
+ *
141
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
142
+ * named as the handler's failure rather than the platform's, and delivery continues.
143
+ */
144
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
145
+ }
146
+
147
+ /**
148
+ * `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).
149
+ *
150
+ * Typed locally on purpose (ADR D4 of B-018): this package declares `loopzero-gateway >=0.9.0` as
151
+ * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on
152
+ * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the
153
+ * integration package assigns it to one, and its typecheck is where a drift between the two fails.
154
+ */
155
+
156
+ /** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */
157
+ interface ConfigField {
158
+ readonly key: string;
159
+ readonly env?: string;
160
+ readonly required: boolean;
161
+ readonly secret: boolean;
162
+ readonly description: string;
163
+ }
164
+ /**
165
+ * The Telegram channel: a long-polling bot, so it needs no webhook route.
166
+ *
167
+ * `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is
168
+ * not an array of strings, with this package's `ConfigurationError`; it performs no network call.
169
+ *
170
+ * @public
171
+ */
172
+ declare const telegramChannel: {
173
+ platform: "telegram";
174
+ transport: "socket";
175
+ senderIdentity: "authenticated";
176
+ config: readonly ConfigField[];
177
+ create(config: Readonly<Record<string, unknown>>): TelegramAdapter;
178
+ };
179
+
180
+ /**
181
+ * Typed errors for `loopzero-gateway-telegram`.
182
+ *
183
+ * `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway
184
+ * package's does, so `createChannels` reports a refused Telegram config as a rejected channel
185
+ * rather than rethrowing it as a defect.
186
+ */
187
+
188
+ /**
189
+ * Misconfiguration of the Telegram channel, raised before any network call.
190
+ *
191
+ * Carries a structured `code` the caller can branch on and, for a refused field, the field's key
192
+ * in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it
193
+ * is never retried.
194
+ */
195
+ declare class ConfigurationError extends GatewayConfigurationError {
196
+ readonly name = "ConfigurationError";
197
+ constructor(opts: GatewayConfigurationErrorOptions);
198
+ }
199
+
200
+ /**
201
+ * Group-chat policy for Telegram bots (T5.1).
202
+ *
203
+ * In private chats: respond to everything.
204
+ * In groups: respond only when:
205
+ * 1. the user @-mentions the bot OR
206
+ * 2. the message is a reply to one of the bot's earlier messages OR
207
+ * 3. it's a slash command (Telegram auto-routes those to the bot).
208
+ *
209
+ * Without this filter, a Telegram bot in a group becomes a noisemaker.
210
+ * Register as a `pre_inbound` hook on the runner.
211
+ *
212
+ * @public
213
+ */
214
+
215
+ /** Policy state. Build once per bot at boot from `bot.botInfo`. */
216
+ interface PolicyContext {
217
+ /** The bot's username (without leading `@`). */
218
+ readonly botUsername: string;
219
+ /** The bot's user id. Used to detect reply-to-bot. */
220
+ readonly botId: number;
221
+ }
222
+ /**
223
+ * Decide whether the bot should respond to this update.
224
+ * @public
225
+ */
226
+ declare function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean;
227
+ /** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */
228
+ declare function stripBotMention(text: string, botUsername: string): string;
229
+
230
+ /**
231
+ * Translating a raw Telegram `Update` into the canonical `MessageEvent`.
232
+ *
233
+ * This is the gateway's half of LoopZero's channel seam. `handleChannelWebhook` validates the
234
+ * signature and hands the app `payload: unknown`, stating that the `loopzero-gateway-*` package
235
+ * translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is
236
+ * fixed in core rather than extended per adapter.
237
+ *
238
+ * The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its
239
+ * polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of
240
+ * the same event — which is the failure this file exists to prevent, not merely a tidiness point.
241
+ *
242
+ * Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on
243
+ * a payload the adapter never saw, which is the entire point of a webhook.
244
+ */
245
+
246
+ /**
247
+ * Translate one raw Telegram webhook body into a `TelegramMessageEvent`.
248
+ *
249
+ * Returns `null` — never throws. The caller is `onMessage`, which LoopZero awaits BEFORE it builds
250
+ * the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely
251
+ * and the 200 is never built. Measured against `loopzero@0.48.14`; the original
252
+ * rationale here ("runs after the 200") was measured false on 2026-08-24.
253
+ *
254
+ * **`null` answers two different questions, and a caller cannot tell them apart.** That is a real
255
+ * cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:
256
+ *
257
+ * - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —
258
+ * `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,
259
+ * `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,
260
+ * `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs
261
+ * an error on every `null` will cry wolf.
262
+ * - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields
263
+ * the mapping requires.
264
+ *
265
+ * A richer return type would separate the two. It is deliberately not used: `gateway-line`'s
266
+ * shipped translator returns a bare `undefined`, and diverging from the reference shape for a
267
+ * distinction no consumer has asked for is the abstraction YAGNI refuses.
268
+ *
269
+ * @public
270
+ */
271
+ declare function parseInbound(payload: unknown): TelegramMessageEvent | null;
272
+
273
+ /**
274
+ * Split a long text into Telegram-sized chunks, preferring paragraph,
275
+ * line, then hard boundaries. EC-J: when a chunk ends in the middle of
276
+ * a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last
277
+ * complete pair so neither chunk produces a "markdown_parse_error" 400.
278
+ *
279
+ * @public
280
+ */
281
+ declare function splitForTelegram(text: string): string[];
282
+
283
+ export { ConfigurationError, type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention, telegramChannel };