chat / adapter-whatsapp
AGENTS.md2.4k starsChanged 2 months agoMITView on GitHub
Guidance for coding agents working inside the WhatsApp 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/whatsapp connects a Chat SDK bot to the WhatsApp Cloud API (Meta-hosted Business Platform). It covers: - HTTP webhook endpoint at /api/webhooks/whatsapp with the GET challenge handshake plus the POST event delivery (signed by Meta with HMAC-SHA256). - Outbound messages via the Cloud API: text, media…
- Reads credentials
Trending
Quiet since March.thin dataabout the whole repository
Who's talking about vercel/chat
- @camilleroux.com“Un SDK TypeScript unifié pour créer des chatbots qui fonctionnent sur Slack, Teams, Google Chat, Discord, …”Bluesky · Mar 3, 2026 · 3 likes
- @technews4869.bsky.social“github.com/vercel/chat GitHub - vercel/chat: A unified TypeScript SDK for building chat bots across Slack, …”Bluesky · Mar 7, 2026 · 1 likes
- @yug1224.com“チャットアプリ開発に使える統一SDKを提供するツールらしい 様々なプラットフォーム対応で便利そうだな yug1224 starred vercel/chat https://github.com/vercel/chat”Bluesky · Mar 7, 2026 · 1 likes
- @news.humancoders.com“Vercel lance Chat SDK : un SDK TypeScript unifié pour créer des bots multi-plateformes”Bluesky · Mar 5, 2026 · 1 likes
- @github-trending-js.bsky.social“🔥 Hot Repo! 🔥 (100+ new stars) 📦 vercel / chat ⭐ 871 (+121) 🗒 TypeScript A unified TypeScript SDK for …”Bluesky · Feb 27, 2026 · 1 likes
The biggest 5 of 5 mentions linking to the repository that our crawl found. Each line is their own headline.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository44 other files it gives its agents.
- AGENTS.mdAGENTS.md
- apps/docs/AGENTS.mdAGENTS.md
- chat-sdkAGENTS.md
- packages/adapter-discord/AGENTS.mdAGENTS.md
- packages/adapter-gchat/AGENTS.mdAGENTS.md
- packages/adapter-github/AGENTS.mdAGENTS.md
- packages/adapter-instagram/AGENTS.mdAGENTS.md
- packages/adapter-linear/AGENTS.mdAGENTS.md
- packages/adapter-messenger/AGENTS.mdAGENTS.md
- packages/adapter-notion/AGENTS.mdAGENTS.md
- packages/adapter-slack/AGENTS.mdAGENTS.md
- packages/adapter-teams/AGENTS.mdAGENTS.md
- packages/adapter-telegram/AGENTS.mdAGENTS.md
- packages/adapter-web/AGENTS.mdAGENTS.md
- packages/chat/src/adapters/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/AGENTS.mdAGENTS.md
- packages/create-chat-sdk/_template/AGENTS.mdAGENTS.md
- packages/state-ioredis/AGENTS.mdAGENTS.md
- packages/state-memory/AGENTS.mdAGENTS.md
- packages/state-pg/AGENTS.mdAGENTS.md
- packages/state-redis/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- packages/adapter-discord/CLAUDE.mdCLAUDE.md
- packages/adapter-gchat/CLAUDE.mdCLAUDE.md
- packages/adapter-github/CLAUDE.mdCLAUDE.md
- packages/adapter-linear/CLAUDE.mdCLAUDE.md
- packages/adapter-messenger/CLAUDE.mdCLAUDE.md
- packages/adapter-slack/CLAUDE.mdCLAUDE.md
- packages/adapter-teams/CLAUDE.mdCLAUDE.md
- packages/adapter-telegram/CLAUDE.mdCLAUDE.md
- packages/adapter-web/CLAUDE.mdCLAUDE.md
- packages/adapter-whatsapp/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/CLAUDE.mdCLAUDE.md
- packages/create-chat-sdk/_template/CLAUDE.mdCLAUDE.md
- packages/state-ioredis/CLAUDE.mdCLAUDE.md
- packages/state-memory/CLAUDE.mdCLAUDE.md
- packages/state-pg/CLAUDE.mdCLAUDE.md
- packages/state-redis/CLAUDE.mdCLAUDE.md
- add-adapterSkill
- technical-writerSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
- chat-sdkSkill
The file
We split this AGENTS.md into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 180
When a card does render as an interactive button message, any LinkButton URLs are appended to the body as Label: url lines so they stay …
- Distinctive: line 231
Cards + files: When the card renders as an interactive message (reply buttons or a list), media is sent without a caption and the …
- Very specific: line 264
Stickers, voice notes, and PDFs: all arrive as separate event shapes — extend index.ts thoughtfully when adding support.
- Very specific: line 281
When you add support for a new event subtype, capture a fresh fixture in sample-messages.md.
- Distinctive: line 286
Use named exports throughout.
- Very specific: line 289
Every Graph API call goes through graphFetchJson.
≈ “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.
Files
AGENTS.md — @chat-adapter/whatsapp
Guidance for coding agents working inside the WhatsApp 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/whatsapp connects a Chat SDK bot to the WhatsApp Cloud
API (Meta-hosted Business Platform). It covers:
- HTTP webhook endpoint at
/api/webhooks/whatsappwith the GET challenge handshake plus the POST event delivery (signed by Meta with HMAC-SHA256). - Outbound messages via the Cloud API: text, media (image, document, video, audio, sticker), interactive (buttons, lists), templates, reactions, and read receipts.
- Phone-number-driven addressing — WhatsApp threads are 1:1 between the bot's phone number and the customer's E.164 number.
- 24-hour conversation window — outside it, only approved templates can be sent.
- Multiple phone-number-id support (run a single bot across multiple WhatsApp Business Accounts).
Directory layout
packages/adapter-whatsapp/
├── src/
│ ├── index.ts # WhatsAppAdapter + createWhatsAppAdapter
│ ├── index.test.ts
│ ├── cards.ts # PostableMessage / Card → interactive payloads
│ ├── cards.test.ts
│ ├── errors.ts # WhatsAppApiError (Meta Graph error envelope)
│ ├── errors.test.ts
│ ├── markdown.ts # WhatsAppFormatConverter (mdast ↔ WA formatting)
│ ├── markdown.test.ts
│ └── types.ts # Cloud API typings
├── sample-messages.md # captured Cloud API webhook events
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── vitest.config.ts
└── README.mdBuild, test, typecheck
pnpm build
pnpm dev
pnpm test
pnpm test:watch
pnpm typecheck
pnpm clean
# from repo root
pnpm --filter @chat-adapter/whatsapp build
pnpm --filter @chat-adapter/whatsapp testReplay tests live in
packages/integration-tests/src/replay-whatsapp-*.test.ts.
Public surface
Main exports from src/index.ts:
createWhatsAppAdapter(config?)— primary factory. Auto-detectsWHATSAPP_ACCESS_TOKEN,WHATSAPP_APP_SECRET,WHATSAPP_PHONE_NUMBER_ID,WHATSAPP_VERIFY_TOKEN, and the optionalWHATSAPP_WABA_ID(used for cross-number reads).WhatsAppAdapterclass — implementsAdapter<WhatsAppThreadId, unknown>. Public methods:handleWebhook,postMessage,reply,editMessage,deleteMessage,addReaction,removeReaction,startTyping,markRead,fetchThread,fetchMessages,fetchSingleMessage,fetchChannelInfo,postChannelMessage,openDM,sendTemplate.- Configuration:
WhatsAppAdapterConfig,WhatsAppThreadId,WhatsAppTemplateMessage. - Errors:
WhatsAppApiError(non-2xx Graph API responses) plus theWhatsAppGraphError/WhatsAppGraphErrorBodyenvelope types. - Helpers:
cardToInteractive,cardToFallbackText,WhatsAppFormatConverter,decodeThreadId,encodeThreadId,isDM.
Thread ID format
WhatsApp threads are scoped by the bot's phone-number-id and the
customer's E.164 number (without the leading +):
whatsapp:{phoneNumberId}:{customerPhone}isDM(threadId) always returns true — WhatsApp Cloud API has no
group concept (groups exist only on the on-prem API and are not
supported by this adapter).
Webhook flow
WhatsAppAdapter.handleWebhook(request, options) is the entry point.
- Verification handshake (GET) — Meta sends
?hub.mode=subscribe&hub.verify_token=…&hub.challenge=…. The adapter checksverify_tokenagainstWHATSAPP_VERIFY_TOKENand echoes the challenge. - Event delivery (POST) — Meta signs every body with HMAC-SHA256
using
appSecret. The adapter verifies before parsing. - Event routing
messages(text,image,audio,document,video,sticker,location,interactive,button) →chat.handleIncomingMessage. Mentions are detected by matching the bot's display phone number againsttext.body.statuses(sent,delivered,read,failed) → optional delivery hooks. The adapter keeps alastUserMessageAtcache so it can decide when the 24-hour window has expired.errors→chat.logger.errorwith the Cloud API error payload.user_id_update(a separatefieldfrommessages) → alias the previous and current BSUID to the same canonical user so the thread survives the rotation.user_changed_numberanduser_changed_user_idsystem messages undermessagesupdate identity state the same way, then skip message dispatch.
waitUntil— the 200 response must land within 20 s; longer work goes throughwaitUntil.
Authentication
Two flavours of access token:
- System User token — long-lived, recommended. Generate via Business Manager → System Users → token assignment for the WhatsApp Business product.
- App user token — short-lived (60 days). Use for development only.
The adapter never refreshes tokens; rotate them out-of-band when
they expire and update WHATSAPP_ACCESS_TOKEN.
Format conversion
WhatsApp uses a small set of formatting markers: *bold*, _italic_,
~strike~, `inline code`, and triple-backtick code fences.
WhatsAppFormatConverter (in markdown.ts):
- mdast → WA formatting — preserves the supported markers and strips unsupported ones (headings collapse to bold lines, lists become plain paragraphs with bullet prefixes).
- WA formatting → mdast — round-trips the same constructs. Mentions
are not recognised by the Cloud API except in a very limited
context (
Hey @[+1234567890]), so the converter treats them as plain text. - Tables flatten to fixed-width text in a code fence.
Cards (interactive payloads)
WhatsApp supports two interactive shapes that map onto Chat SDK cards:
- Reply buttons — up to 3 buttons.
cardToInteractivebuilds aninteractive.type: "button"message when the card has 1–3<Button>children with no<Select>. - List messages — up to 10 sections, each with up to 10 rows.
Used when the card has more than 3 actions or any
<Select>. - CTA URL messages —
interactive.type: "cta_url"when the card's only interactive element, across every actions row including rows nested in sections, is a singleLinkButtonwith a non-empty label and anhttp://orhttps://URL. Promotion is skipped when the card has a headerimageUrlor any image, table, chart, or inline link children (the interactive body cannot carry them), or when the post includes files or attachments (the captioned media send wins). Text, fields, sections, and dividers are fine.display_texttruncates to 20 chars, the header to 60, the body to 1024.
Outside those shapes, cards fall back to plain text built from
cardToFallbackText, where link buttons render as Label: url.
When a card does render as an interactive button message, any
LinkButton URLs are appended to the body as Label: url lines so
they stay reachable. The same lines are added to media captions,
since the shared fallback text excludes action elements.
Templates
Outside the 24-hour conversation window, the Cloud API only accepts
approved templates. sendTemplate is the way to drive them:
await adapter.sendTemplate(threadId, {
name: "appointment_reminder",
language: "en",
components: [
{
type: "body",
parameters: [{ type: "text", text: "Tomorrow at 2pm" }],
},
],
});The adapter does not auto-substitute templates for outbound text posts — handlers must opt in explicitly when they detect the window is closed.
File uploads
postMessage accepts both files (FileUpload[]) and attachments
(Attachment[]). Binary payloads upload via
POST /{phoneNumberId}/media to obtain a media_id; URL-only
attachments use WhatsApp link passthrough (HTTPS required, no upload).
One media object per API message. Multiple files or attachments
in a single post() call are sent as sequential messages. The last
message ID is returned (same convention as long-text chunking).
Captions. Markdown or card fallback text is attached as a caption
on the first media message when possible (max 1024 characters). A
separate leading text message is sent when the caption is too long,
or when the first media is audio (audio messages do not support
captions).
MIME mapping. image/jpeg and image/png map to image;
other image/* types (e.g. GIF) map to document. video/mp4 and
video/3gpp map to video; audio/* maps to audio; everything
else maps to document. Pre-flight size checks throw
ValidationError when binary size is known (image 5 MB, audio/video
16 MB, document 100 MB).
Cards + files. When the card renders as an interactive message
(reply buttons or a list), media is sent without a caption and the
interactive message that follows carries the title, body, and
buttons. Text-fallback cards caption the first media with the
fallback text plus a Label: url line per link button. A card
with only a link button is never promoted to a CTA URL message
when media is attached; it takes this captioned path. Card validation runs before
media upload, so ValidationError is thrown before any media is
sent.
Media IDs expire after 30 days. For inbound media, the adapter
exposes a lazy fetchData() that downloads the binary on demand.
Streaming
WhatsApp does not support message edits via the Cloud API in the
free tier (paid tiers added support late 2024). The adapter falls
back to the buffered streaming pattern: accumulate the stream and
post once when it completes. For markets with edit support, set
enableEdit: true in the adapter config to switch to post-then-edit.
WhatsApp quirks worth remembering
- 24-hour window. Free-form messages fail outside it with a 131047 error. Use approved templates to re-engage.
- Phone-number formatting. Cloud API expects E.164 without the
leading
+.decodeThreadIdalready handles this; raw API users must too. - Webhook signature includes the entire body. Forwarding through a proxy that mutates the body breaks verification.
- Read receipts are sent via
messagesAPI withstatus: "read". The adapter exposesmarkRead(threadId)for handlers that want explicit control. - Stickers, voice notes, and PDFs all arrive as separate event
shapes — extend
index.tsthoughtfully when adding support. - Interactive button limits. 3 reply buttons, 20-character
labels, 256-character
ids. The adapter throwsValidationErrorbefore sending if you exceed them.
Testing approach
- Unit tests colocated with each module (
*.test.ts). The interactive-payload tests incards.test.tscover reply buttons vs lists vs fallback text. - Replay tests in
packages/integration-tests/src/replay-whatsapp-*.test.tsconsume recordedmessagesandstatusesevents. - Cloud API client is mocked at the
fetchboundary; never hitgraph.facebook.comfrom unit tests.
When you add support for a new event subtype, capture a fresh fixture
in sample-messages.md.
Coding conventions
- Use named exports throughout. No default exports.
- Cloud API typings live in
types.ts. Extend them rather than pulling a third-party dependency. - Every Graph API call goes through
graphFetchJson. Non-2xx responses throwWhatsAppApiErrorfromerrors.ts, which maps status and Meta codes onto the sharedAdapterError.codetaxonomy; extend that mapping rather than throwingAdapterRateLimitError/AuthenticationErrordirectly. Transport and JSON parse failures throwNetworkError, and bad input throwsValidationError. - Top-level regex literals only.
- Phone-number sanitization belongs in one helper — never inline
replace(/\\+/, "")calls.
Releases
Behavioural changes need a changeset (pnpm changeset, choose
@chat-adapter/whatsapp 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/whatsapp.mdx - README:
packages/adapter-whatsapp/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-whatsapp/sample-messages.md
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
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.

