loopzero-gateway-telegram 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +526 -0
- package/LICENSE +201 -0
- package/README.md +171 -2
- package/dist/index.cjs +975 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +261 -0
- package/dist/index.d.ts +261 -0
- package/dist/index.js +967 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { Bot, Context } from 'grammy';
|
|
2
|
+
import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, 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 edits a sent message's text through `editMessageText`. */
|
|
85
|
+
readonly supportsEdit = true;
|
|
86
|
+
/**
|
|
87
|
+
* Replace the text of a message this bot sent, through `editMessageText`.
|
|
88
|
+
*
|
|
89
|
+
* Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no
|
|
90
|
+
* Telegram edit adds an image), empty text, a message id that is not a safe positive integer,
|
|
91
|
+
* and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own
|
|
92
|
+
* checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit
|
|
93
|
+
* replaces one message. Telegram's "message is not modified" refusal is answered as a success,
|
|
94
|
+
* because the message already shows the text; a caller that treated it as a failure would send
|
|
95
|
+
* the same text again as a second message.
|
|
96
|
+
*/
|
|
97
|
+
editMessage(messageId: string, out: OutboundMessage): Promise<SendResult>;
|
|
98
|
+
private editText;
|
|
99
|
+
react(channelId: string, messageId: string, emoji: string): Promise<SendResult>;
|
|
100
|
+
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
101
|
+
startTyping(channelId: string): Promise<void>;
|
|
102
|
+
private handleInbound;
|
|
103
|
+
/**
|
|
104
|
+
* Marks whether the bot was addressed and applies the `requireMention` gate, shared by the
|
|
105
|
+
* polled and webhook paths. Returns `undefined` when the gate drops the event. A direct message
|
|
106
|
+
* is left unmarked; `addressed` stays unset while the bot's identity is not known.
|
|
107
|
+
*/
|
|
108
|
+
private gateMention;
|
|
109
|
+
/**
|
|
110
|
+
* The event with the voice note's audio when the message has one (B-715, ADR D1).
|
|
111
|
+
*
|
|
112
|
+
* The audio is deferred: no request leaves here, so a `pre_inbound` hook that refuses the event
|
|
113
|
+
* costs no download. An unreadable voice rejects `audio.read()` and writes the reason to stderr.
|
|
114
|
+
*/
|
|
115
|
+
private withVoice;
|
|
116
|
+
/**
|
|
117
|
+
* Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
|
|
118
|
+
*
|
|
119
|
+
* One line over `runHandler`, which owns the containment: a handler is user code, its throw is
|
|
120
|
+
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
121
|
+
*/
|
|
122
|
+
deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* `telegramChannel` — the Telegram channel described as data (FR-004 of B-018).
|
|
127
|
+
*
|
|
128
|
+
* Typed locally on purpose (ADR D4 of B-018): this package declares `loopzero-gateway >=0.9.0` as
|
|
129
|
+
* its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on
|
|
130
|
+
* that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the
|
|
131
|
+
* integration package assigns it to one, and its typecheck is where a drift between the two fails.
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */
|
|
135
|
+
interface ConfigField {
|
|
136
|
+
readonly key: string;
|
|
137
|
+
readonly env?: string;
|
|
138
|
+
readonly required: boolean;
|
|
139
|
+
readonly secret: boolean;
|
|
140
|
+
readonly description: string;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The Telegram channel: a long-polling bot, so it needs no webhook route.
|
|
144
|
+
*
|
|
145
|
+
* `create` refuses a token that is absent, empty or not a string, and an `allowedUsers` that is
|
|
146
|
+
* not an array of strings, with this package's `ConfigurationError`; it performs no network call.
|
|
147
|
+
*
|
|
148
|
+
* @public
|
|
149
|
+
*/
|
|
150
|
+
declare const telegramChannel: {
|
|
151
|
+
platform: "telegram";
|
|
152
|
+
transport: "socket";
|
|
153
|
+
senderIdentity: "authenticated";
|
|
154
|
+
config: readonly ConfigField[];
|
|
155
|
+
create(config: Readonly<Record<string, unknown>>): TelegramAdapter;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Typed errors for `loopzero-gateway-telegram`.
|
|
160
|
+
*
|
|
161
|
+
* `ConfigurationError` extends the shared core `GatewayConfigurationError`, as every gateway
|
|
162
|
+
* package's does, so `createChannels` reports a refused Telegram config as a rejected channel
|
|
163
|
+
* rather than rethrowing it as a defect.
|
|
164
|
+
*/
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Misconfiguration of the Telegram channel, raised before any network call.
|
|
168
|
+
*
|
|
169
|
+
* Carries a structured `code` the caller can branch on and, for a refused field, the field's key
|
|
170
|
+
* in `detail`. A missing or malformed token is a programmer error, not a transient failure, so it
|
|
171
|
+
* is never retried.
|
|
172
|
+
*/
|
|
173
|
+
declare class ConfigurationError extends GatewayConfigurationError {
|
|
174
|
+
readonly name = "ConfigurationError";
|
|
175
|
+
constructor(opts: GatewayConfigurationErrorOptions);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Group-chat policy for Telegram bots (T5.1).
|
|
180
|
+
*
|
|
181
|
+
* In private chats: respond to everything.
|
|
182
|
+
* In groups: respond only when:
|
|
183
|
+
* 1. the user @-mentions the bot OR
|
|
184
|
+
* 2. the message is a reply to one of the bot's earlier messages OR
|
|
185
|
+
* 3. it's a slash command (Telegram auto-routes those to the bot).
|
|
186
|
+
*
|
|
187
|
+
* Without this filter, a Telegram bot in a group becomes a noisemaker.
|
|
188
|
+
* Register as a `pre_inbound` hook on the runner.
|
|
189
|
+
*
|
|
190
|
+
* @public
|
|
191
|
+
*/
|
|
192
|
+
|
|
193
|
+
/** Policy state. Build once per bot at boot from `bot.botInfo`. */
|
|
194
|
+
interface PolicyContext {
|
|
195
|
+
/** The bot's username (without leading `@`). */
|
|
196
|
+
readonly botUsername: string;
|
|
197
|
+
/** The bot's user id. Used to detect reply-to-bot. */
|
|
198
|
+
readonly botId: number;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Decide whether the bot should respond to this update.
|
|
202
|
+
* @public
|
|
203
|
+
*/
|
|
204
|
+
declare function shouldRespondInChat(ctx: Context, policy: PolicyContext): boolean;
|
|
205
|
+
/** Strip the bot's @-mention from a message so the LLM doesn't see it. @public */
|
|
206
|
+
declare function stripBotMention(text: string, botUsername: string): string;
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Translating a raw Telegram `Update` into the canonical `MessageEvent`.
|
|
210
|
+
*
|
|
211
|
+
* This is the gateway's half of LoopZero's channel seam. `handleChannelWebhook` validates the
|
|
212
|
+
* signature and hands the app `payload: unknown`, stating that the `loopzero-gateway-*` package
|
|
213
|
+
* translates it — see `docs/adr/0001-message-event-closed-union.md` for why the event shape is
|
|
214
|
+
* fixed in core rather than extended per adapter.
|
|
215
|
+
*
|
|
216
|
+
* The mapping lives HERE and nowhere else. `adapter.ts` reaches for the same `buildEvent` from its
|
|
217
|
+
* polling loop, so a webhook-delivered update and a polled one cannot drift into two dialects of
|
|
218
|
+
* the same event — which is the failure this file exists to prevent, not merely a tidiness point.
|
|
219
|
+
*
|
|
220
|
+
* Everything here is pure: no transport, no credential, no clock. A caller may therefore run it on
|
|
221
|
+
* a payload the adapter never saw, which is the entire point of a webhook.
|
|
222
|
+
*/
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Translate one raw Telegram webhook body into a `TelegramMessageEvent`.
|
|
226
|
+
*
|
|
227
|
+
* Returns `null` — never throws. The caller is `onMessage`, which LoopZero awaits BEFORE it builds
|
|
228
|
+
* the 200, with nothing catching around it — so a throw here escapes `handleChannelWebhook` entirely
|
|
229
|
+
* and the 200 is never built. Measured against `loopzero@0.48.14`; the original
|
|
230
|
+
* rationale here ("runs after the 200") was measured false on 2026-08-24.
|
|
231
|
+
*
|
|
232
|
+
* **`null` answers two different questions, and a caller cannot tell them apart.** That is a real
|
|
233
|
+
* cost of this contract, so the ordinary half is enumerated here rather than left to be discovered:
|
|
234
|
+
*
|
|
235
|
+
* - **Ordinary traffic.** Telegram sends update kinds that carry no message to answer —
|
|
236
|
+
* `edited_message`, `edited_channel_post`, `callback_query`, `inline_query`,
|
|
237
|
+
* `chosen_inline_result`, `poll`, `poll_answer`, `my_chat_member`, `chat_member`,
|
|
238
|
+
* `chat_join_request`. A bot with an inline keyboard receives these constantly. An app that logs
|
|
239
|
+
* an error on every `null` will cry wolf.
|
|
240
|
+
* - **A malformed body.** Not an update at all, or an update whose `message` is missing the fields
|
|
241
|
+
* the mapping requires.
|
|
242
|
+
*
|
|
243
|
+
* A richer return type would separate the two. It is deliberately not used: `gateway-line`'s
|
|
244
|
+
* shipped translator returns a bare `undefined`, and diverging from the reference shape for a
|
|
245
|
+
* distinction no consumer has asked for is the abstraction YAGNI refuses.
|
|
246
|
+
*
|
|
247
|
+
* @public
|
|
248
|
+
*/
|
|
249
|
+
declare function parseInbound(payload: unknown): TelegramMessageEvent | null;
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Split a long text into Telegram-sized chunks, preferring paragraph,
|
|
253
|
+
* line, then hard boundaries. EC-J: when a chunk ends in the middle of
|
|
254
|
+
* a markdown pair (`**`, `__`, `~~`, `` ` ``), trim back to the last
|
|
255
|
+
* complete pair so neither chunk produces a "markdown_parse_error" 400.
|
|
256
|
+
*
|
|
257
|
+
* @public
|
|
258
|
+
*/
|
|
259
|
+
declare function splitForTelegram(text: string): string[];
|
|
260
|
+
|
|
261
|
+
export { ConfigurationError, type PolicyContext, TelegramAdapter, type TelegramAdapterOptions, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention, telegramChannel };
|