Skip to main content

WhatsApp: how it works

WhatsApp is Meta's messaging service. Taji uses it as a two-way channel: it sends alerts and your agent's replies into the chat you have with yourself, and it hears the texts you type there. The integration is the crate taji-whatsapp (plugins/whatsapp/). Its Rust arm implements taji_plugin::channel::Channel, and it drives a TypeScript sidecar, taji-whatsapp. The sidecar runs Baileys, an unofficial WhatsApp Web client, as one linked device of your own number. Taji calls no WhatsApp host of its own: Baileys holds the only connection, a WebSocket to WhatsApp's servers.

The vendor​

No official API reaches a personal number. WhatsApp's own clients link up to four companion devices to a primary phone, by QR code or by an eight-character pairing code (Link a device, Link with phone number, both fetched 2026-12-02). Baileys speaks that companion protocol: "the same binary WebSocket protocol as WhatsApp Web", and "Baileys is an unofficial library and is not affiliated with WhatsApp" (Baileys, fetched 2026-12-02). Taji pins baileys 7.0.0-rc14 in plugins/whatsapp/sidecar/package.json.

Terms. WhatsApp's terms bar you from creating "software or APIs that function substantially the same as our Services", and from "bulk messaging, auto-messaging, auto-dialing, and the like". They also say "we may take action with respect to your account, including disabling or suspending your account" (Terms of Service, fetched 2026-12-02). This is why the manifest's risk line tells you to use a separate number.

Environments. There is one: production. WhatsApp has no sandbox for a personal account.

Auth model.

  • Linking. A companion device holds Signal-protocol credentials. The phone grants them when you scan the companion's QR code, or when you type its pairing code. While Baileys holds no credentials, its connection.update event carries a qr string. requestPairingCode(phone) takes the number as digits alone, country code first, and is called only while creds.registered is false (Events, Pairing code, both fetched 2026-12-02).
  • Storage. useMultiFileAuthState keeps the credentials and Signal keys as JSON files in a folder. Baileys says it "is not recommended for deployment in production", and that you must save on every creds.update (Session management, fetched 2026-12-02).
  • Lifetime. There is no token to expire. The link lasts until the phone or WhatsApp removes the device, or until the phone has not logged in for 14 days (Link a device).

What Taji uses, all through Baileys (Socket config, Media messages, JIDs, all fetched 2026-12-02):

  • The socket. makeWASocket runs on the version fetchLatestBaileysVersion returns.
  • Events. connection.update carries qr, open and close with lastDisconnect. messages.upsert has a type: notify is "messages received while the socket was online", and append is "messages loaded from history or backfill". creds.update asks you to save the credentials.
  • Sending. sendMessage(jid, {text}) sends a text. sendMessage(jid, {image, caption, mimetype, jpegThumbnail, width, height}, {messageId}) sends a picture.
  • Message ids. generateMessageIDV2 makes the id, so Taji knows it before the send.
  • Presence. sendPresenceUpdate("unavailable") is sent on every open, reconnects included.
  • The timelock. fetchAccountReachoutTimelock answers a ReachoutTimelockState {isActive?, timeEnforcementEnds?, enforcementType?} (ReachoutTimelockState, fetched 2026-12-02). WhatsApp documents no timelock publicly.
  • Addresses. A JID is local@server:
    • a user is <digits>@s.whatsapp.net, or an opaque <lid>@lid that "WhatsApp treats … as the canonical identifier going forward";
    • :N marks one device;
    • groups are @g.us, broadcasts @broadcast, status status@broadcast, channels @newsletter;
    • remoteJidAlt carries a direct chat's other form.
  • Close codes (DisconnectReason, fetched 2026-12-02):
    • loggedOut 401;
    • timedOut and connectionLost 408;
    • connectionReplaced 440;
    • restartRequired 515;
    • others 403, 411, 428, 500 and 503.

Accounts. One WhatsApp account is one phone number. Every companion device sees the same chats. A message you type on the phone into your chat with yourself reaches a companion with key.fromMe set.

Stated limits.

  • WhatsApp states four linked devices and the 14-day rule. It publishes no send rate for a personal account.
  • Baileys' socket defaults are a 30 s keep-alive, a 20 s connect timeout and a 60 s query timeout. Taji sets 25 s, 60 s and 60 s.
  • Baileys warns that sending to a group fetches its member list on every send, which leads to rate limiting (FAQ, fetched 2026-12-02). Taji sends to no group.

What Taji leaves unused.

CapabilityWhy
WhatsApp Business Platform Cloud API, the official API (overview, fetched 2026-12-02)It needs a business portfolio and a business phone number, and it reaches people outside a customer-service window only through templates. It cannot act as your own number in your own self-chat.
Other chats, groups, broadcasts, status and channelsThe owner rule: Taji hears only you, and the sidecar drops these JIDs.
Inbound images, voice notes and other mediaNot yet built.
History sync (syncFullHistory)Taji answers only what you send now: false.
Typing presence (composing)Not yet built: the arm keeps the trait's default typing, which sends nothing.
Buttons and framed messagesNot yet built: the arm keeps the default send_framed, which sends the frame as text. You answer a card by typing yes <token>.
WhatsApp's `inline code` and * / - list markers (Format your messages, fetched 2026-12-02)Not yet built. The kernel writes monospace as ``` and bullets as •.
Reactions, edits, deletes and read receiptsNot yet built.

Code map​

FileWhat it ownsRead first
plugins/whatsapp/taji-plugin.tomlThe manifest: the whatsapp link form, its one scan step, the optional phone field, and the refusal words no_scan and logged_out[[link]]
plugins/whatsapp/Cargo.tomlThe crate taji-whatsapp: taji-plugin, tokio (process, io-util), base64—
plugins/whatsapp/src/lib.rsThe arm WhatsApp. It spawns the sidecar and speaks JSON lines to it. link, run and unlink each own one sidecar. send borrows run's through the live door. It also holds the arm's own echo filter (sent, heard) and maps events to Failed.impl Channel for WhatsApp, then run
plugins/whatsapp/sidecar/main.tsThe sidecar, run as taji-whatsapp <auth dir>. Its header is the protocol. It holds the Baileys session (Session), the login and reconnect rules (Sidecar.login, monitor), the inbound filter (inbound) and the echo cache (Outbound), and it sends (sendOne).the header, then inbound
plugins/whatsapp/sidecar/main.test.tsBun tests of the sidecar's pure parts, plus one spawned-process testdescribe("inbound")
plugins/whatsapp/sidecar/package.json, plugins/whatsapp/sidecar/tsconfig.jsonThe package @taji/whatsapp-sidecar, the Baileys pin, bun test, tsc --noEmit—
plugins/whatsapp/ui/mark.svgThe mark on WhatsApp's Connections row—

The kernel side, outside the crate:

  • engine/crates/taji/src/wire/channels.rs holds linking, the owner rule, rendering, cutting and asking.
  • engine/crates/taji/src/wire/markup.rs holds Markup::WhatsApp.
  • engine/crates/taji-open/src/lib.rs adds the plugin, as .add(taji_whatsapp::WhatsApp::default).
  • agent/src/mcp/link.ts is taji-link whatsapp.
  • The whatsapp target of Makefile and engine/crates/taji/scripts/stage.sh build the sidecar.

How it plugs into Taji​

The trait. WhatsApp implements Channel (engine/crates/taji-plugin/src/channel.rs; the contract is in Write a channel), and Plugin::build registers it with b.channel(Self::default()).

  • Default finds the sidecar: TAJI_WHATSAPP_SIDECAR, run under bun when it ends in .ts, else taji-whatsapp beside the kernel. Its auth directory is <state dir>/whatsapp/.
  • id is whatsapp; name is WhatsApp.
  • fields is empty: nothing is sealed in the vault, and the row is never locked.
  • caps is {inbound: true, images: true, text_limit: 4000}.
  • markup is Markup::WhatsApp.
  • It does not override send_framed or typing.

The plugin has no Source, venue, FACTS, VenueFacts or OFFER. It feeds no hub product.

The link form is whatsapp, of kind start, in group Channels (taji-plugin.toml; the steps and words are there). The phone field is an on field of step scan. The kernel hands it to link and never seals it. link removes it from the secret before it returns.

The sidecar protocol is in the header of plugins/whatsapp/sidecar/main.ts. Each side writes one JSON object per line.

  • Commands on stdin: login (phone optional), send (to, text, image_b64 optional), logout (sent by unlink), quit.
  • Events on stdout: qr, code, linked (jid, e164), status (open, reconnecting, logged_out or conflict), message, and sent (an id, or an error with optional refused).
  • Each send is answered by exactly one sent, in order. This is why the arm matches answers to callers with a FIFO, waiting.
  • main redirects console.* to stderr, because libsignal logs through console and stdout carries the protocol. The arm skips any stdout line that does not parse as an event.
Taji surfaceBehind itMade in
POST /verb/channels/link {channel: "whatsapp"}, the sheet's Show the QR, and taji-link whatsappA fresh sidecar sends login. Each qr goes to report.scan, and a code (from requestPairingCode) goes to report.code. On linked, the arm sends quit and returns owner = jid.WhatsApp::link; Sidecar.login and pairingRequester
GET /read/channels row qr, code, error, stateWhat link reported, and how run endedengine/crates/taji/src/wire/channels.rs
Each alert's desk note, POST /verb/channels/send, and the agent's reply to a phone turnsend sends a send command through run's sidecar, which calls sock.sendMessageWhatsApp::send and call; Sidecar.sendOne
A text you type in your self-chatmessages.upsert, then inbound, then a message line. run checks it with heard, then hands it to Inbox::heard.Sidecar.socket; WhatsApp::run

One message in. You type "what is AAPL at?" in your chat with yourself on the phone.

  1. Baileys. The socket emits messages.upsert with type notify.

  2. The sidecar. inbound keeps the message only if all of these hold:

    • the type is notify or append;
    • the message has an id and a remoteJid;
    • the chat is not a group, broadcast, status or newsletter JID;
    • it is not a ciphertext placeholder;
    • it is not an append older than the replay floor;
    • it is not an echo in Outbound;
    • it has text after trimming.

    chatOf folds the LID and device forms of your own chat into your phone-number JID. A fromMe message's sender is that JID. The sidecar then emits {"type":"message",…}.

  3. The arm. run's loop reads the line. heard passes it only when all of these hold:

    • fromMe is set;
    • chat equals the JID from the last linked;
    • sender equals chat;
    • the id is not one a send returned in the last 20 minutes.

    It calls inbox.heard(Inbound {id, sender, at_utc: ts, text}).

  4. The kernel. Channels::heard applies owner_rule: the sender must equal the owner that link returned. It drops an id already seen, and answers "Not run: Taji heard this late." to a message more than 120 s old. Otherwise it routes the text:

    • a card reply goes to that card;
    • a taji command is answered by the kernel;
    • anything else goes to Agent::ask on the attached desk's chat.

One message out. The agent's last message comes back.

  1. The kernel. send_to renders the Markdown with render(text, Markup::WhatsApp) and cuts it with chunk at 4,000 characters. It calls WhatsApp::send once per piece, with the PNG on the first piece only.
  2. The arm. send builds {"cmd":"send","to":<owner>,"text":…,"image_b64"?} and passes it through the live door to run. If no run is up, the answer is "WhatsApp is not connected." as Unreached.
    • run hands the command to a writer task and pushes the reply slot onto waiting.
    • The writer task exists because the sidecar stops when its stdout is full, so stdout must keep draining while a large picture is written.
  3. The sidecar. send runs one send at a time. sendOne does the following, in order:
    • checks activeTimelock, fetching it again when it is inactive, and refuses while it holds;
    • makes the id with generateMessageIDV2;
    • records the id in Outbound before sendMessage, because Baileys upserts its own message before the send resolves;
    • sends the text, or the picture with caption, mimetype: "image/png", an empty jpegThumbnail and the PNG's IHDR size;
    • emits {"type":"sent","id":…}.
  4. The arm. run reads sent and records the id in sent before it answers the caller, because the echo can be the very next line. It pops the oldest slot in waiting. The kernel stores the id, sets last_sent_utc, and clears error.

Why it is built this way​

  • OpenClaw's integration, copied. The user ruled on 2026-11-16: "exactly OpenClaw's integration". The sidecar's session, login, reconnect, inbound and echo rules are taken file for file from OpenClaw's extensions/whatsapp (MIT, read at 9270515d). The file names are in the header of main.ts, with the licence notice. The 4,000-character chunk and the 20-minute echo window are OpenClaw's numbers (TEXT_LIMIT, SENT_TTL).
  • A separate process. Baileys is a JavaScript library. A built taji-whatsapp bundles libsignal, which is GPL-3.0, so that binary ships as a separate program, and the kernel speaks to it only over a pipe (LICENSING.md). kill_on_drop ties the sidecar's life to the future that spawned it, which meets the trait's rule that "a child process dies with it".
  • One socket per session. A second socket on the same credentials knocks the first off with 440. So send never spawns a sidecar; it borrows run's. The kernel also stops run before it starts a link (channels.rs: "A session holds one socket").
  • Self-chat only, so linking needs no pairing code. Only you can write fromMe into your own self-chat, and WhatsApp authenticates that on the linked number. So link returns owner = Some(jid), and the kernel marks the row linked at once, with no pairing code. The owner rule is the only guard between a chat account and a card that can run a shell (the header of engine/crates/taji/src/wire/channels.rs). That is why the arm checks fromMe, chat and sender, and the kernel then checks sender against the owner again.
  • Echo filtered twice. The trait requires that an arm's own sends never reach inbox.
    • The sidecar drops echoes by jid:id, including the LID alias, as OpenClaw does.
    • The arm drops any id that a sent returned, so the rule holds whatever the sidecar does.
  • No key in the vault. No credential is typed, so fields is empty. The session files live in <state dir>/whatsapp/, a 0700 directory, and the sidecar writes creds.json with mode 0600. No client and no process plugin ever reads them (0005).
  • Credentials are saved safely. Every creds.update is saved through one queue, by temp file, fsync and rename. The good creds.json is first copied to creds.json.bak, and it is restored at the next open when creds.json does not parse. A link succeeds only once creds.json is on disk ("Socket open only proves in-memory auth"). link sends quit rather than killing the sidecar, so the credentials are flushed first.
  • Phone push stays on. markOnlineOnConnect: false and sendPresenceUpdate("unavailable") keep the phone sending notifications: Baileys says an online socket stops them.
  • The QR in the window. The user ruled the terminal-only link "a poor experience" (2026-11-17). So link reports each QR through Report::scan, the kernel serves it as the row's qr, and the sheet and taji-link whatsapp both draw from that one field.
  • A QR during run means the session is gone. No one is there to scan it, so run ends with logged_out rather than waiting.
  • Line-buffered output and no thumbnail. emit writes synchronously, so a line written just before process.exit still reaches the arm. The empty jpegThumbnail keeps Baileys from looking for an image library.

Constraints and limits​

  • Text. At most 4,000 characters per message (caps().text_limit). The kernel cuts at a line end, else at a space, and closes and reopens a code fence across pieces. A picture rides on the first piece only.

  • Markup. Markup::WhatsApp writes:

    • *bold*, _italic_ and ~strike~;
    • ```code``` for both inline and block code;
    • • bullets and ─── rules;
    • links as text (url).

    WhatsApp has no escape, so a marker keeps its backslash (engine/crates/taji/src/wire/markup.rs).

  • Send rate. Taji sets no budget. There is no ratelimit.rs; a send rate limit is not yet built. Sends are serial within the sidecar.

  • The reachout timelock. While WhatsApp holds it, every send is refused as Failed::Refused("WhatsApp reachout timelock is active; direct messages are temporarily blocked"). The kernel shows this as the row's error.

  • Reconnects (Sidecar.monitor):

    • 401 ends with logged_out and 440 ends with conflict;
    • any other close retries after a backoff from 2 s to 30 s (×1.8, plus up to 25 % jitter);
    • on the 12th failure the sidecar exits 1 (11 reconnects are tried);
    • the attempt count resets after a connection that lasted 60 s.

    The arm maps the endings: logged_out becomes Failed::Word("logged_out"); conflict becomes Failed::Refused with the 440 sentence; a sidecar exit becomes Unreached. The kernel runs an Unreached arm again after 5 s, and leaves a refused one in error until you link again.

  • Login (Sidecar.login): 515 and 408 each restart once. A first 401 wipes the auth directory and asks once more. Anything else exits 1. When the sidecar ends after a QR was shown, link answers no_scan; when it ends before one, Unreached. How long an unscanned link waits is unmeasured.

  • Replay floor. An append is heard only if it is under 20 minutes old once history has synced, or no more than 60 s older than the connection before that. The kernel's 120 s late rule applies after this one.

  • Unlink. POST /verb/channels/unlink stops run, forgets the owner, then calls the arm's unlink. With <state dir>/whatsapp/ present, that spawns a sidecar, sends login, and once it reports linked sends logout. The sidecar sends the frame Baileys' logout builds (remove-companion-device) through Baileys' query rather than logout, which sends it without waiting for an answer, and awaits WhatsApp's reply. On a result reply, the device is gone from the phone's Linked devices list: the sidecar closes the socket, deletes the directory and exits 0. On an error reply, no reply within the 60 s query timeout, or a closed socket, it keeps the directory and exits 1. A QR or logged_out instead means the phone already dropped the device: the arm kills the sidecar and deletes the directory. No directory means nothing to do. If the session does not connect within 90 s, the sidecar exits non-zero, or it has not exited 90 s after logout (the arm then kills it), the answer is 502 channel and the directory stays; the channel is unlinked all the same, and unlinking again retries.

  • Approvals. An order's approval cannot come from the phone. On this, the README and Connect your agent own the user-facing words.

The plugin has no coverage page and no measured ### sections. The user-facing failures are in the README's table.

Examples​

No capture of WhatsApp's own traffic exists. Baileys' binary WebSocket frames are never logged (logger: silent). A capture would come from a human round trip (the QR link, then a self-chat round trip), with Baileys' logger at debug. engine/crates/taji/scripts/channels_walk.py walks Discord only. The examples below are test bodies, their values made up and the wire fixture. Phone numbers are masked: p1 is yours and p2 a stranger's.

The link form, as GET /read/link/forms serves it (engine/crates/taji/tests/fixtures/wire/link-forms.json, trimmed):

{
"act": "Show the QR",
"fields": [{ "name": "phone", "kind": "text", "on": "scan", "label": "Your WhatsApp number", … }],
"form": "whatsapp",
"kind": "start",
"post": { "body": { "channel": "whatsapp" }, "route": "channels/link" },
"refusals": {
"logged_out": "WhatsApp signed this linked device out. Scan a new code on your phone to link again.",
"no_scan": "No phone scanned the code. Point WhatsApp on your phone at the code, then try again."
},
…
}

A link by pairing code, arm to sidecar (plugins/whatsapp/src/lib.rs, link_sends_digits_of_phone_and_reports_code_without_returning_phone). You typed +1 (555) … in the phone field, and the arm keeps only the digits:

→ {"cmd":"login","phone":"p1"}
← {"type":"qr","data":"2@a"} report: At("scan"), Scan("2@a")
← {"type":"code","data":"ABCD-1234"} report: Code("ABCD-1234")
← {"type":"linked","jid":"<ACCT>@s.whatsapp.net","e164":"+<ACCT>"}
→ {"cmd":"quit"}

link returns Linked { secret: {}, owner: Some("<ACCT>@s.whatsapp.net") }: the phone number is not in the secret.

Baileys to the sidecar (plugins/whatsapp/sidecar/main.test.ts, "a self-chat text is heard as the owner's"). Baileys hands over this upsert of type notify:

{ "key": { "id": "MSG1", "remoteJid": "<ACCT>@s.whatsapp.net", "fromMe": true },
"message": { "conversation": "hello" }, "messageTimestamp": 1800000000 }

and the sidecar emits:

{"type":"message","id":"MSG1","chat":"<ACCT>@s.whatsapp.net","sender":"<ACCT>@s.whatsapp.net","fromMe":true,"text":"hello","ts":1800000000}

What the arm hears (plugins/whatsapp/src/lib.rs, only_the_accounts_own_self_chat_texts_are_heard). Of these lines, only mine and last reach the inbox. BEFORE arrives before linked names the account, so it is dropped too:

message BEFORE chat p1 sender p1 fromMe true "before linked"
linked <ACCT>@s.whatsapp.net
message A chat p1 sender p1 fromMe true "mine" heard
message B chat p2 sender p2 fromMe false "a stranger"
message C chat p1 sender p2 fromMe false "spoofed into my chat"
message D chat p2 sender p1 fromMe true "mine to someone else"
message E chat p1 sender p1 fromMe false "not from me"
message F chat p1 sender p1 fromMe true "last" heard

A send and its echo (plugins/whatsapp/src/lib.rs, a_send_goes_through_runs_sidecar_and_its_echo_is_never_heard):

→ {"cmd":"send","to":"<ACCT>@s.whatsapp.net","text":"**Up** 2%"}
← {"type":"sent","id":"S1"} send returns "S1"
← {"type":"message","id":"S1",…,"text":"echo of my send"} dropped: S1 was sent
← {"type":"message","id":"M9",…,"text":"after"} heard

Before run is up, the same send answers Failed::Unreached("WhatsApp is not connected.").

What the kernel renders for WhatsApp (engine/crates/taji/src/wire/markup.rs, markdown_becomes_whatsapp_markers, a few rows):

**bold** and __bold__ → *bold* and *bold*
*it* and _it_ and ~~gone~~ → _it_ and _it_ and ~gone~
`code` → ```code```
- one\n* two → • one\n• two
[Taji](https://example.org) → Taji (https://example.org)

Testing​

WhatCommandNeeds
The arm, against a fake sh sidecar: link by QR and code, no_scan, logged_out, the owner filter, the echo, pictures, refused and unreached sends, and how run endscargo test -p taji-whatsappUnix (the tests are cfg(unix))
The sidecar: self and JIDs, the inbound filters, the echo cache, backoff, toJid, the timelock, pngSize, the pairing code, and a spawned sidecar that answers a send before login and exits on quitpnpm --filter @taji/whatsapp-sidecar test (also part of make test)bun
The sidecar's typespnpm --filter @taji/whatsapp-sidecar type-check (also part of make type-check)—
The kernel's side with a fake arm: linking, a pending QR and code, owner and pairing, WhatsApp markup and cuttingcargo test -p taji --lib -- channels markup—
taji-link whatsapp against a fake kernelbun test agent/src/mcp/link.test.tsbun
Build the sidecar beside a dev kernelmake whatsapp (OUT=target/debug)bun

No test reaches WhatsApp. There is no tests/live.rs and no walk. The live check is a human one, on a spare number:

  1. Run make whatsapp, then FRESH=1 make dev.
  2. Open WhatsApp's row under Channels, choose Show the QR, and scan it from the phone.
  3. Send yourself a text, and see the agent's reply.

FRESH=1 keeps your own state out of the run. The test is never against your own Taji (AGENTS.md).

References​

Fetched 2026-12-02: