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

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

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

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
  1. Very specific:

    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 …

    line 180
  2. Distinctive:

    Cards + files: When the card renders as an interactive message (reply buttons or a list), media is sent without a caption and the …

    line 231
  3. Very specific:

    Stickers, voice notes, and PDFs: all arrive as separate event shapes — extend index.ts thoughtfully when adding support.

    line 264
  4. Very specific:

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

    line 281
  5. Distinctive:

    Use named exports throughout.

    line 286
  6. Very specific:

    Every Graph API call goes through graphFetchJson.

    line 289

≈ “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/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/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 (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.md

Build, 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 test

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

Public surface

Main exports from src/index.ts:

  • createWhatsAppAdapter(config?) — primary factory. Auto-detects WHATSAPP_ACCESS_TOKEN, WHATSAPP_APP_SECRET, WHATSAPP_PHONE_NUMBER_ID, WHATSAPP_VERIFY_TOKEN, and the optional WHATSAPP_WABA_ID (used for cross-number reads).
  • WhatsAppAdapter class — implements Adapter<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 the WhatsAppGraphError / WhatsAppGraphErrorBody envelope 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.

  1. Verification handshake (GET) — Meta sends ?hub.mode=subscribe&hub.verify_token=…&hub.challenge=…. The adapter checks verify_token against WHATSAPP_VERIFY_TOKEN and echoes the challenge.
  2. Event delivery (POST) — Meta signs every body with HMAC-SHA256 using appSecret. The adapter verifies before parsing.
  3. 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 against text.body.
    • statuses (sent, delivered, read, failed) → optional delivery hooks. The adapter keeps a lastUserMessageAt cache so it can decide when the 24-hour window has expired.
    • errors → chat.logger.error with the Cloud API error payload.
    • user_id_update (a separate field from messages) → alias the previous and current BSUID to the same canonical user so the thread survives the rotation. user_changed_number and user_changed_user_id system messages under messages update identity state the same way, then skip message dispatch.
  4. waitUntil — the 200 response must land within 20 s; longer work goes through waitUntil.

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. cardToInteractive builds an interactive.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 single LinkButton with a non-empty label and an http:// or https:// URL. Promotion is skipped when the card has a header imageUrl or 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_text truncates 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 +. decodeThreadId already 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 messages API with status: "read". The adapter exposes markRead(threadId) for handlers that want explicit control.
  • Stickers, voice notes, and PDFs all arrive as separate event shapes — extend index.ts thoughtfully when adding support.
  • Interactive button limits. 3 reply buttons, 20-character labels, 256-character ids. The adapter throws ValidationError before sending if you exceed them.

Testing approach

  • Unit tests colocated with each module (*.test.ts). The interactive-payload tests in cards.test.ts cover reply buttons vs lists vs fallback text.
  • Replay tests in packages/integration-tests/src/replay-whatsapp-*.test.ts consume recorded messages and statuses events.
  • Cloud API client is mocked at the fetch boundary; never hit graph.facebook.com from 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 throw WhatsAppApiError from errors.ts, which maps status and Meta codes onto the shared AdapterError.code taxonomy; extend that mapping rather than throwing AdapterRateLimitError / AuthenticationError directly. Transport and JSON parse failures throw NetworkError, and bad input throws ValidationError.
  • 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

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.