@mastra/telegram 0.0.0 → 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.
@@ -0,0 +1,421 @@
1
+ import { WaitUntilFn, StreamingConfig, ChannelHandlers, ChannelConfig, ChannelAdapterConfig, ChannelProvider, ChannelPlatformInfo, ChannelConnectResult, ChannelInstallationInfo } from '@mastra/core/channels';
2
+ import { Mastra } from '@mastra/core/mastra';
3
+ import { ApiRoute } from '@mastra/core/server';
4
+ import { TelegramAdapterConfig, TelegramAdapter, TelegramUser } from '@chat-adapter/telegram';
5
+ export { TelegramAdapter, createTelegramAdapter } from '@chat-adapter/telegram';
6
+ import { ChannelsStorage } from '@mastra/core/storage';
7
+
8
+ /** Default Telegram Bot API origin. */
9
+ declare const TELEGRAM_API_BASE_URL = "https://api.telegram.org";
10
+ /**
11
+ * Transport for receiving updates.
12
+ * - `webhook` — register a `setWebhook` and receive POSTs (default for hosted/serverless).
13
+ * - `polling` — long-poll `getUpdates` (the provider clears any webhook first).
14
+ * - `auto` — webhook when a `baseUrl` is available, otherwise polling.
15
+ */
16
+ type TelegramMode = 'auto' | 'webhook' | 'polling';
17
+ /**
18
+ * Default update types requested from Telegram. `message_reaction` must be
19
+ * listed explicitly (Telegram omits it otherwise).
20
+ */
21
+ declare const DEFAULT_ALLOWED_UPDATES: readonly ["message", "edited_message", "channel_post", "edited_channel_post", "callback_query", "message_reaction"];
22
+ /**
23
+ * A Telegram bot command as it goes over the wire (`setMyCommands`).
24
+ * @see https://core.telegram.org/bots/api#botcommand
25
+ */
26
+ interface BotCommand {
27
+ /** 1-32 chars, lowercase `[a-z0-9_]`, no leading slash. */
28
+ command: string;
29
+ /** 1-256 chars. */
30
+ description: string;
31
+ }
32
+ /** Command input accepted by {@link TelegramProvider} — a bare name or a `{ command, description }`. */
33
+ type TelegramCommand = string | {
34
+ command: string;
35
+ description?: string;
36
+ };
37
+ /**
38
+ * Deep link that opens BotFather so an operator can create a new bot with
39
+ * `/newbot`. Telegram has no OAuth: the resulting BotFather token is pasted
40
+ * back into {@link TelegramProvider.connect} to finish the installation.
41
+ */
42
+ declare const BOTFATHER_DEEP_LINK = "https://t.me/botfather";
43
+ /**
44
+ * Configuration for {@link TelegramProvider}.
45
+ *
46
+ * Telegram has no OAuth and no org-level parent credential: a BotFather bot
47
+ * token *is* the credential (one token per bot). Multi-tenancy is therefore a
48
+ * store of bot tokens — see {@link TelegramInstallation}.
49
+ */
50
+ interface TelegramProviderConfig {
51
+ /**
52
+ * Public HTTPS base URL used to register per-bot webhooks (`setWebhook`).
53
+ * May be omitted and auto-detected from the Mastra server config, or set later.
54
+ */
55
+ baseUrl?: string;
56
+ /**
57
+ * Persistence for bot installations. Defaults to Mastra's channels storage
58
+ * when the provider is attached to a Mastra instance with storage, and falls
59
+ * back to an in-memory store otherwise (dev/test — not persisted across restarts).
60
+ */
61
+ storage?: ChannelsStorage;
62
+ /**
63
+ * Override the Telegram Bot API origin (e.g. a self-hosted Bot API server or
64
+ * a test mock).
65
+ *
66
+ * @default 'https://api.telegram.org'
67
+ */
68
+ apiBaseUrl?: string;
69
+ /**
70
+ * Passphrase for encrypting `botToken`/`secretToken` at rest (AES-256-GCM).
71
+ * Defaults to the `MASTRA_ENCRYPTION_KEY` env var. When unset, secrets are
72
+ * stored in plaintext (fine for the in-memory dev store; set a key for any
73
+ * persistent backend).
74
+ */
75
+ encryptionKey?: string;
76
+ /**
77
+ * Receive transport. Setting a webhook and long-polling are mutually
78
+ * exclusive; the provider manages the switch per bot.
79
+ *
80
+ * @default 'auto'
81
+ */
82
+ mode?: TelegramMode;
83
+ /**
84
+ * Update types to request in `setWebhook`. Defaults to
85
+ * {@link DEFAULT_ALLOWED_UPDATES}.
86
+ */
87
+ allowedUpdates?: string[];
88
+ /**
89
+ * Long-polling tuning forwarded to the adapter's `getUpdates` loop when running
90
+ * in polling mode (`timeout`, `limit`, `allowedUpdates`, `retryDelayMs`, …).
91
+ * Ignored in webhook mode.
92
+ */
93
+ longPolling?: TelegramAdapterConfig['longPolling'];
94
+ /**
95
+ * Keep the serverless invocation alive while the agent stream runs after the
96
+ * webhook returns 200 (Vercel/AWS Lambda). Cloudflare/Netlify resolve this
97
+ * automatically. See `ChannelConfig.waitUntil`.
98
+ */
99
+ waitUntil?: WaitUntilFn;
100
+ /**
101
+ * Default commands registered via `setMyCommands` for every connected agent
102
+ * (a per-agent list can override via {@link TelegramConnectOptions.commands}).
103
+ * Defaults to the conventional `/start` `/help` `/settings` seed.
104
+ */
105
+ commands?: TelegramCommand[];
106
+ /**
107
+ * Command scope passed to `setMyCommands` (e.g. `{ type: 'all_private_chats' }`).
108
+ * Omitted → Telegram's default scope.
109
+ * @see https://core.telegram.org/bots/api#botcommandscope
110
+ */
111
+ commandScope?: Record<string, unknown>;
112
+ /**
113
+ * Stream agent text to Telegram as it generates, via the adapter's
114
+ * post-and-edit (`editMessageText`) loop. Telegram has no native token
115
+ * streaming, so this chunk-edits the reply (4096-char cap handled by the
116
+ * adapter).
117
+ *
118
+ * @default true
119
+ */
120
+ streaming?: StreamingConfig;
121
+ /**
122
+ * Keep a typing indicator alive during generation (`sendChatAction`, re-sent
123
+ * as it auto-clears). Set `false` to disable.
124
+ *
125
+ * @default true
126
+ */
127
+ typingStatus?: boolean;
128
+ /**
129
+ * Override built-in event handlers (`onDirectMessage`, `onMention`,
130
+ * `onSubscribedMessage`). Forwarded to `AgentChannels`.
131
+ */
132
+ handlers?: ChannelHandlers;
133
+ /** Which media types to send inline to the model. See `ChannelConfig.inlineMedia`. */
134
+ inlineMedia?: ChannelConfig['inlineMedia'];
135
+ /** Promote URLs in message text to file parts. See `ChannelConfig.inlineLinks`. */
136
+ inlineLinks?: ChannelConfig['inlineLinks'];
137
+ /** State adapter for deduplication, locking, and subscriptions. See `ChannelConfig.state`. */
138
+ state?: ChannelConfig['state'];
139
+ /** Fetch recent thread messages when the agent joins mid-conversation. See `ChannelConfig.threadContext`. */
140
+ threadContext?: ChannelConfig['threadContext'];
141
+ /** Additional options passed directly to the Chat SDK. See `ChannelConfig.chatOptions`. */
142
+ chatOptions?: ChannelConfig['chatOptions'];
143
+ /** Resolve the memory `resourceId` before a channel thread is created. See `ChannelConfig.resolveResourceId`. */
144
+ resolveResourceId?: ChannelConfig['resolveResourceId'];
145
+ /**
146
+ * Resolve `waitUntil` from the request's Hono `Context` (serverless runtimes
147
+ * whose `waitUntil` derives from the request). See `ChannelConfig.resolveWaitUntil`.
148
+ */
149
+ resolveWaitUntil?: ChannelConfig['resolveWaitUntil'];
150
+ /** CORS configuration for the generated Telegram webhook route. */
151
+ cors?: ChannelAdapterConfig['cors'];
152
+ /** Override how errors are rendered in Telegram messages. See `ChannelAdapterConfig.formatError`. */
153
+ formatError?: ChannelAdapterConfig['formatError'];
154
+ /**
155
+ * How tool calls are rendered in the reply. Telegram has no Block Kit, so
156
+ * `'cards'`/`'grouped'`/`'timeline'` degrade to plain fallback text — this
157
+ * defaults to `'text'` (unlike Slack's `'grouped'`). See `ChannelAdapterConfig.toolDisplay`.
158
+ *
159
+ * @default 'text'
160
+ */
161
+ toolDisplay?: ChannelAdapterConfig['toolDisplay'];
162
+ /**
163
+ * Whether to expose channel reaction tools (`add_reaction`/`remove_reaction`)
164
+ * to the agent. Set `false` for models without function calling. See `ChannelConfig.tools`.
165
+ *
166
+ * @default true
167
+ */
168
+ tools?: ChannelConfig['tools'];
169
+ /** Logger forwarded to the underlying `TelegramAdapter` for internal error reporting. */
170
+ logger?: TelegramAdapterConfig['logger'];
171
+ /** Called after an agent successfully connects a bot and the installation is persisted. */
172
+ onInstall?: (installation: TelegramInstallation) => void | Promise<void>;
173
+ }
174
+ /** Options accepted by {@link TelegramProvider.connect}. */
175
+ interface TelegramConnectOptions {
176
+ /**
177
+ * A BotFather bot token. When supplied it is validated via `getMe` and the
178
+ * installation becomes active immediately (`{ type: 'immediate' }`). Omit it
179
+ * to receive a BotFather deep link instead (`{ type: 'deep_link' }`).
180
+ */
181
+ botToken?: string;
182
+ /** Display name for the bot. Defaults to the bot's `@username` from `getMe`. */
183
+ name?: string;
184
+ /**
185
+ * Commands to register via `setMyCommands` for this agent. Overrides
186
+ * {@link TelegramProviderConfig.commands}. Defaults to the `/start` `/help`
187
+ * `/settings` seed when neither is set.
188
+ */
189
+ commands?: TelegramCommand[];
190
+ }
191
+ /**
192
+ * A registered Telegram bot bound to a single agent (one bot = one agent).
193
+ * Persisted through {@link TelegramInstallStore}.
194
+ */
195
+ interface TelegramInstallation {
196
+ /** Stable installation id. */
197
+ id: string;
198
+ /** The agent this bot is bound to. */
199
+ agentId: string;
200
+ /**
201
+ * Opaque id embedded in the webhook route path (`/telegram/events/:webhookId`).
202
+ * Never the secret — the secret travels only in the request header.
203
+ */
204
+ webhookId: string;
205
+ /** Whether a bot token has been ingested and validated. */
206
+ status: 'active' | 'pending';
207
+ /** BotFather bot token — the full credential. Present once ingested. */
208
+ botToken?: string;
209
+ /**
210
+ * Per-bot webhook shared secret, echoed by Telegram as the
211
+ * `X-Telegram-Bot-Api-Secret-Token` header on every inbound POST.
212
+ */
213
+ secretToken?: string;
214
+ /** The bot's `@username`, resolved from `getMe`. */
215
+ username?: string;
216
+ /** The webhook URL registered with `setWebhook` (M1 — issue `mastra-telegram-i2g.3`). */
217
+ webhookUrl?: string;
218
+ /** Normalized commands registered via `setMyCommands`. */
219
+ commands?: BotCommand[];
220
+ /** When the installation was created. */
221
+ installedAt: Date;
222
+ }
223
+
224
+ /**
225
+ * Resolve the per-adapter streaming/typing config the provider applies to the
226
+ * Telegram entry in `AgentChannels.adapters`. This is the wrapper's stream
227
+ * binding: enabling `streaming` runs the adapter's post-and-edit
228
+ * (`editMessageText`) chunking loop, and `typingStatus` keeps a `sendChatAction`
229
+ * indicator alive — both default on.
230
+ */
231
+ declare function resolveTelegramAdapterConfig(config: Pick<TelegramProviderConfig, 'streaming' | 'typingStatus'>): {
232
+ streaming: StreamingConfig;
233
+ typingStatus: boolean;
234
+ };
235
+ /**
236
+ * Telegram channel provider for Mastra — a {@link ChannelProvider} over
237
+ * `@chat-adapter/telegram`. The adapter handles the Bot API transport (webhook
238
+ * parse, send/edit, typing, rich messages); this provider adds the
239
+ * install/lifecycle layer.
240
+ *
241
+ * Implemented:
242
+ * - **`mastra-telegram-i2g.2`** — multi-token install store (one bot = one
243
+ * agent), `connect()`/`disconnect()`, `getMe` token ingestion.
244
+ * - **`mastra-telegram-i2g.3`** — per-bot `setWebhook` lifecycle,
245
+ * `X-Telegram-Bot-Api-Secret-Token` verification, webhook⇄polling exclusion,
246
+ * and a mounted POST route that delegates to `AgentChannels.handleWebhookEvent`.
247
+ *
248
+ * Later: `setMyCommands` + streaming (`mastra-telegram-i2g.4`).
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * const telegram = new TelegramProvider({ baseUrl: 'https://my-app.example.com' })
253
+ * const mastra = new Mastra({ agents: { myAgent }, channels: { telegram } })
254
+ * await telegram.connect('my-agent', { botToken: '123456:ABC-...' }) // → { type: 'immediate' }
255
+ * ```
256
+ */
257
+ declare class TelegramProvider implements ChannelProvider {
258
+ #private;
259
+ readonly id = "telegram";
260
+ constructor(config?: TelegramProviderConfig);
261
+ /**
262
+ * Called by Mastra when this channel is registered.
263
+ * @internal
264
+ */
265
+ __attach(mastra: Mastra): void;
266
+ /**
267
+ * Per-bot webhook route. A single POST endpoint keyed by an opaque
268
+ * `webhookId`; the per-bot secret is verified from the request header, never
269
+ * carried in the URL. Auto-initializes on first hit (mirrors `@mastra/slack`).
270
+ */
271
+ getRoutes(): ApiRoute[];
272
+ /** Discovery metadata for the editor UI. */
273
+ getInfo(): ChannelPlatformInfo;
274
+ /**
275
+ * Restore installations from storage: rebuild an adapter per active bot and
276
+ * inject `AgentChannels` so the agent can receive events immediately.
277
+ * Idempotent. Does not re-register webhooks (they persist server-side across
278
+ * restarts); reconnect an agent if its `baseUrl` changed.
279
+ */
280
+ initialize(): Promise<void>;
281
+ /**
282
+ * Update runtime provider settings. Telegram has no global auth credential to
283
+ * clear (per-bot tokens are managed via {@link connect}/{@link disconnect}),
284
+ * so `null` is a no-op; an object merges `apiBaseUrl`/`baseUrl` overrides.
285
+ */
286
+ configure(credentials: {
287
+ apiBaseUrl?: string;
288
+ baseUrl?: string;
289
+ } | null): Promise<void>;
290
+ /**
291
+ * Connect an agent to a Telegram bot.
292
+ *
293
+ * - With `options.botToken`: validate via `getMe`, mint a per-bot webhook
294
+ * secret, persist the installation, register the transport (webhook or
295
+ * polling), and return `{ type: 'immediate' }`.
296
+ * - Without a token: persist a pending installation and return
297
+ * `{ type: 'deep_link' }` pointing at BotFather.
298
+ */
299
+ connect(agentId: string, options?: TelegramConnectOptions): Promise<ChannelConnectResult>;
300
+ /** Disconnect an agent from Telegram, removing its webhook and installation. */
301
+ disconnect(agentId: string): Promise<void>;
302
+ /** List installations (public info only — no tokens or secrets). */
303
+ listInstallations(): Promise<ChannelInstallationInfo[]>;
304
+ /**
305
+ * Get the full installation for an agent (includes the bot token / secret).
306
+ * Returns `null` if the agent has no Telegram installation. Mirrors
307
+ * `SlackProvider.getInstallation`.
308
+ */
309
+ getInstallation(agentId: string): Promise<TelegramInstallation | null>;
310
+ /**
311
+ * Whether at least one bot is actively registered. Mirrors
312
+ * `SlackProvider.isConfigured` (Telegram has no global credential to check —
313
+ * "configured" means an active installation exists).
314
+ */
315
+ isConfigured(): boolean;
316
+ /**
317
+ * Get the live `TelegramAdapter` for an installation id, if one is active.
318
+ * Used for message formatting/posting. Mirrors `SlackProvider.getAdapter`.
319
+ */
320
+ getAdapter(installationId: string): TelegramAdapter | undefined;
321
+ }
322
+
323
+ /** Platform identifier used for every stored record and route. */
324
+ declare const PLATFORM = "telegram";
325
+ /**
326
+ * Persistence for Telegram bot installations, layered over the platform-agnostic
327
+ * `ChannelsStorage` (the same store `@mastra/slack` uses). Installations are
328
+ * keyed by agent — one bot = one agent — and the per-bot secret fields live in
329
+ * the record's `data` blob. When an `encryptionKey` is supplied, `botToken` and
330
+ * `secretToken` are AES-256-GCM encrypted at rest.
331
+ */
332
+ declare class TelegramInstallStore {
333
+ #private;
334
+ private readonly storage;
335
+ private readonly encryptionKey?;
336
+ constructor(storage: ChannelsStorage, encryptionKey?: string | undefined);
337
+ /** The active or pending installation for an agent, if any. */
338
+ getByAgent(agentId: string): Promise<TelegramInstallation | null>;
339
+ /** Look up an installation by the routing id in its webhook path (M1 dispatch). */
340
+ getByWebhookId(webhookId: string): Promise<TelegramInstallation | null>;
341
+ /** Insert or replace an installation. */
342
+ save(installation: TelegramInstallation): Promise<void>;
343
+ /** All Telegram installations (active and pending). */
344
+ list(): Promise<TelegramInstallation[]>;
345
+ /** Remove an agent's installation, if present. */
346
+ deleteByAgent(agentId: string): Promise<void>;
347
+ }
348
+ /** Project an installation to its public, secret-free info for the editor UI. */
349
+ declare function toInstallationInfo(install: TelegramInstallation): ChannelInstallationInfo;
350
+
351
+ /**
352
+ * Validate a bot token via `getMe` and resolve the bot's identity. Throws if
353
+ * the token is rejected or the returned user is not a bot.
354
+ *
355
+ * @see https://core.telegram.org/bots/api#getme
356
+ */
357
+ declare function getMe(botToken: string, apiBaseUrl?: string): Promise<TelegramUser>;
358
+ /** Options for {@link setWebhook}. */
359
+ interface SetWebhookOptions {
360
+ /** Public HTTPS URL Telegram will POST updates to. */
361
+ url: string;
362
+ /** Shared secret echoed back as `X-Telegram-Bot-Api-Secret-Token` on every POST. */
363
+ secretToken: string;
364
+ /** Update types to receive. Note: `message_reaction` must be listed explicitly. */
365
+ allowedUpdates?: string[];
366
+ /** Drop the backlog of updates queued while the bot was offline. */
367
+ dropPendingUpdates?: boolean;
368
+ }
369
+ /**
370
+ * Register a per-bot webhook. Setting a webhook disables `getUpdates`
371
+ * (long-polling) for that bot — the two transports are mutually exclusive.
372
+ *
373
+ * @see https://core.telegram.org/bots/api#setwebhook
374
+ */
375
+ declare function setWebhook(botToken: string, options: SetWebhookOptions, apiBaseUrl?: string): Promise<void>;
376
+ /**
377
+ * Remove a bot's webhook. Required before switching a bot to long-polling
378
+ * (`getUpdates` fails while a webhook is set).
379
+ *
380
+ * @see https://core.telegram.org/bots/api#deletewebhook
381
+ */
382
+ declare function deleteWebhook(botToken: string, dropPendingUpdates?: boolean, apiBaseUrl?: string): Promise<void>;
383
+ /** Options for {@link setMyCommands}. */
384
+ interface SetMyCommandsOptions {
385
+ /** The command list to publish (replaces the existing set for the scope). */
386
+ commands: BotCommand[];
387
+ /** Command scope (e.g. `{ type: 'all_private_chats' }`). Omit for the default scope. */
388
+ scope?: Record<string, unknown>;
389
+ /** Two-letter language code for a localized command set. */
390
+ languageCode?: string;
391
+ }
392
+ /**
393
+ * Publish the bot's command list for a scope.
394
+ *
395
+ * @see https://core.telegram.org/bots/api#setmycommands
396
+ */
397
+ declare function setMyCommands(botToken: string, options: SetMyCommandsOptions, apiBaseUrl?: string): Promise<void>;
398
+ /**
399
+ * Generate a webhook secret token within Telegram's `setWebhook` constraint:
400
+ * 1-256 chars from `[A-Za-z0-9_-]`. base64url of 32 random bytes yields 43
401
+ * such chars.
402
+ *
403
+ * @see https://core.telegram.org/bots/api#setwebhook
404
+ */
405
+ declare function generateSecretToken(): string;
406
+
407
+ /**
408
+ * Conventional command seed registered when a connect provides none.
409
+ * @see https://core.telegram.org/bots/features#commands
410
+ */
411
+ declare const DEFAULT_COMMANDS: readonly TelegramCommand[];
412
+ /**
413
+ * Map user-supplied commands (agent capabilities) to Telegram `BotCommand[]`,
414
+ * enforcing the Bot API constraints: `command` is lowercased, stripped of a
415
+ * leading slash, reduced to `[a-z0-9_]`, and clamped to 1-32 chars;
416
+ * `description` defaults to `Run /<command>` and is clamped to 256 chars.
417
+ * Empty or duplicate command names are dropped.
418
+ */
419
+ declare function normalizeCommands(raw: readonly TelegramCommand[] | undefined): BotCommand[];
420
+
421
+ export { BOTFATHER_DEEP_LINK, type BotCommand, DEFAULT_ALLOWED_UPDATES, DEFAULT_COMMANDS, PLATFORM, type SetMyCommandsOptions, type SetWebhookOptions, TELEGRAM_API_BASE_URL, type TelegramCommand, type TelegramConnectOptions, TelegramInstallStore, type TelegramInstallation, type TelegramMode, TelegramProvider, type TelegramProviderConfig, deleteWebhook, generateSecretToken, getMe, normalizeCommands, resolveTelegramAdapterConfig, setMyCommands, setWebhook, toInstallationInfo };