agentleFS
VercelKnown publishervercel/chat/packages/adapter-telegram/AGENTS.md

chat / adapter-telegram

AGENTS.md2.4k starsChanged 59 days agoMITView on GitHub

Guidance for coding agents working inside the Telegram adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls. @chat-adapter/telegram connects a Chat SDK bot to a Telegram bot account via the official Bot API. It covers: - HTTP webhook endpoint at /api/webhooks/telegram (or polling for long-running processes), validated with the optional secret_token header. - Inline keyboards for buttons (cards/actions are rendered as a text…

Trending

Quiet since March.thin dataabout the whole repository

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 1 mentionMar 2026: 4 mentionsApr 2026: 0 mentionsMay 2026: 0 mentionsJun 2026: 0 mentionsJul 2026: 0 mentionsAug 2026: 0 mentionsSep 2026: 0 mentionsOct 2026: 0 mentionsNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the vercel/chat repository that our weekly crawl found: only 5 in all, so this is a hint, not a trend. There is no adoption data for this file yet.

The file

We split this AGENTS.md into the rules it gives an agent

3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When you add support for a new update type, capture a fresh fixture in sample-messages.md.

    line 225
  2. Distinctive:

    Use named exports throughout.

    line 230
  3. Very specific:

    Always escape user-provided text before concatenation.

    line 237

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

AGENTS.md — @chat-adapter/telegram

Guidance for coding agents working inside the Telegram adapter package. The top-level repository AGENTS.md covers monorepo-wide build, lint, and release rules — read it first. This file documents the adapter-specific surface, conventions, and pitfalls.

Overview

@chat-adapter/telegram connects a Chat SDK bot to a Telegram bot account via the official Bot API. It covers:

  • HTTP webhook endpoint at /api/webhooks/telegram (or polling for long-running processes), validated with the optional secret_token header.
  • Inline keyboards for buttons (cards/actions are rendered as a text body plus an inline keyboard footer).
  • Native message edits — Telegram supports per-message edits, which pairs nicely with streaming.
  • Reactions, typing indicators, file uploads (photo, document, animation, video), and forwarded message handling.
  • Group chats with optional topic threads (Forums) and direct messages.

Directory layout

packages/adapter-telegram/
├── src/
│   ├── index.ts             # TelegramAdapter + createTelegramAdapter
│   ├── index.test.ts
│   ├── cards.ts             # Card → text + inline keyboard
│   ├── cards.test.ts
│   ├── markdown.ts          # TelegramFormatConverter (mdast ↔ MarkdownV2)
│   ├── markdown.test.ts
│   └── types.ts             # Bot API typings
├── sample-messages.md       # captured Telegram updates
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── vitest.config.ts
└── README.md

Build, test, typecheck

pnpm build
pnpm dev
pnpm test
pnpm test:watch
pnpm typecheck
pnpm clean

# from repo root
pnpm --filter @chat-adapter/telegram build
pnpm --filter @chat-adapter/telegram test

Replay tests live in packages/integration-tests/src/replay-telegram-*.test.ts.

Public surface

Main exports from src/index.ts:

  • createTelegramAdapter(config?) — primary factory. Auto-detects TELEGRAM_BOT_TOKEN, TELEGRAM_WEBHOOK_SECRET_TOKEN, and the optional TELEGRAM_BOT_USERNAME (used for mention detection in groups).
  • botToken accepts a static string or async resolver and is resolved for each Telegram Bot API or file-download request. This supports outbound-only Vercel Connect authentication while native webhooks keep secretToken. Webhook deduplication is scoped with the stable bot ID returned by getMe, never the potentially rotating token. Failed startup identity lookups retry lazily on later verified webhooks.
  • TelegramAdapter class — implements Adapter<TelegramThreadId, unknown>. Public methods: handleWebhook, postMessage, reply, editMessage, deleteMessage, addReaction, removeReaction, startTyping, fetchThread, fetchMessages, fetchSingleMessage, fetchChannelInfo, postChannelMessage, openDM, setWebhook, deleteWebhook, getMe.
  • Configuration: TelegramAdapterConfig, TelegramThreadId.
  • Helpers: cardToTelegramMessage, cardToFallbackText, TelegramFormatConverter, decodeThreadId, encodeThreadId, isDM.

Thread ID format

Telegram chats are identified by numeric chat_id. Forum threads (Telegram's term for topic threads) carry a message_thread_id. The adapter encodes both:

telegram:{chatId}                       # plain chat / DM
telegram:{chatId}:{messageThreadId}     # topic in a forum group
telegram:biz:{connectionId}:{chatId}    # Connected Business Bot chat

isDM(threadId) returns true when chat.type === "private".

Business threads are their own channel: channelIdFromThreadId returns the full telegram:biz:... ID, never the bare telegram:{chatId}, so they do not share lock or history keys with the customer's direct bot chat. Note that sharders keyed on the first two segments group every business thread under telegram:biz.

Webhook flow

TelegramAdapter.handleWebhook(request, options) is the entry point.

  1. Secret token verification — when webhookSecret is configured, the adapter checks the X-Telegram-Bot-Api-Secret-Token header with a timing-safe comparison.
  2. Update routing
    • message → chat.handleIncomingMessage. Mentions are detected by walking entities[].type === "mention" and matching the bot's @username.
    • edited_message → optional onMessageEdit hook.
    • callback_query → chat.handleAction (inline keyboard callbacks).
    • inline_query / chosen_inline_result → optional inline-mode hooks.
    • message_reaction → chat.handleReaction.
    • my_chat_member / chat_member → membership change hooks.
    • business_connection → cached in the state adapter (before the allowedUserIds gate, since it carries no customer id).
    • business_message / edited_business_message → resolve the connection from state (falling back to getBusinessConnection), drop owner-typed and sender_business_bot echoes, then route slash commands, media groups, and messages like message.
  3. waitUntil — outbound API calls (sendMessage, editMessageText, etc.) run inside waitUntil so the webhook response lands quickly.

Format conversion

Telegram supports two markup modes: MarkdownV2 (strict, with many escapes required) and HTML. TelegramFormatConverter (in markdown.ts) targets MarkdownV2:

  • mdast → MarkdownV2 — escapes the 18 reserved characters (_*[]()~\>#+-=|{}.!) inside text nodes, preserves emphasis (bold, italic, underline, strike, ||spoiler||), inline code (single backtick), code fences, blockquotes (>), links via label, and mentions via name`.
  • MarkdownV2 → mdast — round-trips the same constructs. Custom emoji arrive as separate entities[].type: "custom_emoji"; the converter embeds them inline with their fallback text.
  • Tables flatten to fixed-width code blocks (no native table support).

renderPostable builds the text body for outbound messages. When the target chat type is channel and the bot is the channel owner, the adapter falls back to HTML mode for richer rendering — a quirk worth knowing when debugging.

Cards (text + inline keyboard)

Telegram has no card primitive — instead, cards are rendered as a text body with an inline keyboard footer. cardToTelegramMessage emits:

  • Header / section text → MarkdownV2 paragraphs in the message body.
  • Image → photo attachment (uses sendPhoto instead of sendMessage).
  • Fields → bulleted MarkdownV2 lines.
  • Buttons → reply_markup.inline_keyboard[][] rows. Each button has either callback_data (callback id) or url (<LinkButton>).
  • LinkButton → url button.
  • Select → emitted as a row of buttons because Telegram has no native select widget. Use a modal-style flow for many options.

Tables flatten as in markdown.

Streaming

Telegram supports per-message edits cleanly, so streaming maps onto the post-then-edit pattern. The adapter posts a placeholder, then edits with editMessageText as deltas arrive. Min edit interval defaults to 800 ms to stay under the per-bot rate limit.

File uploads

postMessage accepts FileUpload objects ({ filename, content, contentType }). The adapter picks the appropriate Bot API method:

  • image/* → sendPhoto.
  • video/* → sendVideo.
  • audio/* → sendAudio or sendVoice depending on the codec.
  • image/gif → sendAnimation.
  • Everything else → sendDocument.

A single message can carry one attachment plus a caption. Multiple files or compatible attachments are sent with sendMediaGroup.

Telegram quirks worth remembering

  • MarkdownV2 escapes are mandatory. Forgetting to escape a . in user-provided text 400s the request. The converter handles this, but raw API users must too.
  • Privacy mode — group bots only see messages addressed to them unless privacy mode is disabled via @BotFather. The adapter surfaces this gotcha in getMe() output.
  • Reaction set is restricted to a small list of emoji per chat unless the chat is a paid premium channel. The Bot API rejects unsupported reactions with 400.
  • Forum topics behave like channels. The message_thread_id needs to be passed back on every reply; otherwise the bot posts at the chat root.
  • message_id is per-chat, not global. Persist it together with the chat_id.
  • secret_token is the only line of defence for HTTP webhooks — do not skip configuring it in production.

Testing approach

  • Unit tests colocated with each module (*.test.ts). The MarkdownV2 escape tests are extensive — extend them whenever you touch the converter.
  • Replay tests in packages/integration-tests/src/replay-telegram-*.test.ts consume recorded Update payloads.
  • Bot API client is mocked at the fetch boundary. Never hit api.telegram.org from unit tests.

When you add support for a new update type, capture a fresh fixture in sample-messages.md.

Coding conventions

  • Use named exports throughout. No default exports.
  • The Bot API typings live in types.ts — extend them in place rather than pulling a third-party dependency.
  • Errors map to @chat-adapter/shared (AuthenticationError, AdapterRateLimitError, NetworkError, ValidationError).
  • Top-level regex literals only — Telegram has many of them (MARKDOWN_V2_ESCAPES, MENTION_REGEX, etc.).
  • Always escape user-provided text before concatenation. Format helpers (escapeMarkdownV2) live in markdown.ts.

Releases

Behavioural changes need a changeset (pnpm changeset, choose @chat-adapter/telegram plus chat if a public type changed). Sample fixtures and AGENTS.md edits don't.

Where to look next

  • User-facing docs: apps/docs/content/adapters/official/telegram.mdx
  • README: packages/adapter-telegram/README.md
  • Shared error/utility helpers: packages/adapter-shared/src/index.ts
  • Core Adapter contract: packages/chat/src/adapter.ts
  • Sample webhook payloads: packages/adapter-telegram/sample-messages.md

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.