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.updateevent carries aqrstring.requestPairingCode(phone)takes the number as digits alone, country code first, and is called only whilecreds.registeredis false (Events, Pairing code, both fetched 2026-12-02). - Storage.
useMultiFileAuthStatekeeps 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 everycreds.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.
makeWASocketruns on the versionfetchLatestBaileysVersionreturns. - Events.
connection.updatecarriesqr,openandclosewithlastDisconnect.messages.upserthas atype:notifyis "messages received while the socket was online", andappendis "messages loaded from history or backfill".creds.updateasks 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.
generateMessageIDV2makes the id, so Taji knows it before the send. - Presence.
sendPresenceUpdate("unavailable")is sent on every open, reconnects included. - The timelock.
fetchAccountReachoutTimelockanswers aReachoutTimelockState{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>@lidthat "WhatsApp treats … as the canonical identifier going forward"; :Nmarks one device;- groups are
@g.us, broadcasts@broadcast, statusstatus@broadcast, channels@newsletter; remoteJidAltcarries a direct chat's other form.
- a user is
- Close codes (DisconnectReason, fetched 2026-12-02):
loggedOut401;timedOutandconnectionLost408;connectionReplaced440;restartRequired515;- 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.
| Capability | Why |
|---|---|
| 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 channels | The owner rule: Taji hears only you, and the sidecar drops these JIDs. |
| Inbound images, voice notes and other media | Not 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 messages | Not 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 receipts | Not yet built. |
Code map
| File | What it owns | Read first |
|---|---|---|
plugins/whatsapp/taji-plugin.toml | The 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.toml | The crate taji-whatsapp: taji-plugin, tokio (process, io-util), base64 | — |
plugins/whatsapp/src/lib.rs | The 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.ts | The 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.ts | Bun tests of the sidecar's pure parts, plus one spawned-process test | describe("inbound") |
plugins/whatsapp/sidecar/package.json, plugins/whatsapp/sidecar/tsconfig.json | The package @taji/whatsapp-sidecar, the Baileys pin, bun test, tsc --noEmit | — |
plugins/whatsapp/ui/mark.svg | The mark on WhatsApp's Connections row | — |
The kernel side, outside the crate:
engine/crates/taji/src/wire/channels.rsholds linking, the owner rule, rendering, cutting and asking.engine/crates/taji/src/wire/markup.rsholdsMarkup::WhatsApp.engine/crates/taji-open/src/lib.rsadds the plugin, as.add(taji_whatsapp::WhatsApp::default).agent/src/mcp/link.tsistaji-link whatsapp.- The
whatsapptarget ofMakefileandengine/crates/taji/scripts/stage.shbuild 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()).
Defaultfinds the sidecar:TAJI_WHATSAPP_SIDECAR, run underbunwhen it ends in.ts, elsetaji-whatsappbeside the kernel. Its auth directory is<state dir>/whatsapp/.idiswhatsapp;nameisWhatsApp.fieldsis empty: nothing is sealed in the vault, and the row is neverlocked.capsis{inbound: true, images: true, text_limit: 4000}.markupisMarkup::WhatsApp.- It does not override
send_framedortyping.
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(phoneoptional),send(to,text,image_b64optional),logout(sent byunlink),quit. - Events on stdout:
qr,code,linked(jid,e164),status(open,reconnecting,logged_outorconflict),message, andsent(anid, or anerrorwith optionalrefused). - Each
sendis answered by exactly onesent, in order. This is why the arm matches answers to callers with a FIFO,waiting. mainredirectsconsole.*to stderr, because libsignal logs throughconsoleand stdout carries the protocol. The arm skips any stdout line that does not parse as an event.
| Taji surface | Behind it | Made in |
|---|---|---|
POST /verb/channels/link {channel: "whatsapp"}, the sheet's Show the QR, and taji-link whatsapp | A 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, state | What link reported, and how run ended | engine/crates/taji/src/wire/channels.rs |
Each alert's desk note, POST /verb/channels/send, and the agent's reply to a phone turn | send sends a send command through run's sidecar, which calls sock.sendMessage | WhatsApp::send and call; Sidecar.sendOne |
| A text you type in your self-chat | messages.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.
-
Baileys. The socket emits
messages.upsertwith typenotify. -
The sidecar.
inboundkeeps the message only if all of these hold:- the type is
notifyorappend; - 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
appendolder than the replay floor; - it is not an echo in
Outbound; - it has text after trimming.
chatOffolds the LID and device forms of your own chat into your phone-number JID. AfromMemessage'ssenderis that JID. The sidecar then emits{"type":"message",…}. - the type is
-
The arm.
run's loop reads the line.heardpasses it only when all of these hold:fromMeis set;chatequals the JID from the lastlinked;senderequalschat;- the id is not one a send returned in the last 20 minutes.
It calls
inbox.heard(Inbound {id, sender, at_utc: ts, text}). -
The kernel.
Channels::heardappliesowner_rule: the sender must equal the owner thatlinkreturned. 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
tajicommand is answered by the kernel; - anything else goes to
Agent::askon the attached desk's chat.
One message out. The agent's last message comes back.
- The kernel.
send_torenders the Markdown withrender(text, Markup::WhatsApp)and cuts it withchunkat 4,000 characters. It callsWhatsApp::sendonce per piece, with the PNG on the first piece only. - The arm.
sendbuilds{"cmd":"send","to":<owner>,"text":…,"image_b64"?}and passes it through thelivedoor torun. If norunis up, the answer is "WhatsApp is not connected." asUnreached.runhands the command to a writer task and pushes the reply slot ontowaiting.- The writer task exists because the sidecar stops when its stdout is full, so stdout must keep draining while a large picture is written.
- The sidecar.
sendruns one send at a time.sendOnedoes 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
OutboundbeforesendMessage, because Baileys upserts its own message before the send resolves; - sends the text, or the picture with
caption,mimetype: "image/png", an emptyjpegThumbnailand the PNG's IHDR size; - emits
{"type":"sent","id":…}.
- checks
- The arm.
runreadssentand records the id insentbefore it answers the caller, because the echo can be the very next line. It pops the oldest slot inwaiting. The kernel stores the id, setslast_sent_utc, and clearserror.
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 at9270515d). The file names are in the header ofmain.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-whatsappbundles 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_dropties 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
sendnever spawns a sidecar; it borrowsrun's. The kernel also stopsrunbefore it starts a link (channels.rs: "A session holds one socket"). - Self-chat only, so linking needs no pairing code. Only you can write
fromMeinto your own self-chat, and WhatsApp authenticates that on the linked number. Solinkreturnsowner = Some(jid), and the kernel marks the rowlinkedat 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 ofengine/crates/taji/src/wire/channels.rs). That is why the arm checksfromMe,chatandsender, and the kernel then checkssenderagainst 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
sentreturned, so the rule holds whatever the sidecar does.
- The sidecar drops echoes by
- No key in the vault. No credential is typed, so
fieldsis empty. The session files live in<state dir>/whatsapp/, a 0700 directory, and the sidecar writescreds.jsonwith mode 0600. No client and no process plugin ever reads them (0005). - Credentials are saved safely. Every
creds.updateis saved through one queue, by temp file,fsyncand rename. The goodcreds.jsonis first copied tocreds.json.bak, and it is restored at the next open whencreds.jsondoes not parse. A link succeeds only oncecreds.jsonis on disk ("Socket open only proves in-memory auth").linksendsquitrather than killing the sidecar, so the credentials are flushed first. - Phone push stays on.
markOnlineOnConnect: falseandsendPresenceUpdate("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
linkreports each QR throughReport::scan, the kernel serves it as the row'sqr, and the sheet andtaji-link whatsappboth draw from that one field. - A QR during
runmeans the session is gone. No one is there to scan it, sorunends withlogged_outrather than waiting. - Line-buffered output and no thumbnail.
emitwrites synchronously, so a line written just beforeprocess.exitstill reaches the arm. The emptyjpegThumbnailkeeps 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::WhatsAppwrites:*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'serror. -
Reconnects (
Sidecar.monitor):- 401 ends with
logged_outand 440 ends withconflict; - 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_outbecomesFailed::Word("logged_out");conflictbecomesFailed::Refusedwith the 440 sentence; a sidecar exit becomesUnreached. The kernel runs anUnreachedarm again after 5 s, and leaves a refused one inerroruntil you link again. - 401 ends with
-
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,linkanswersno_scan; when it ends before one,Unreached. How long an unscanned link waits is unmeasured. -
Replay floor. An
appendis 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/unlinkstopsrun, forgets the owner, then calls the arm'sunlink. With<state dir>/whatsapp/present, that spawns a sidecar, sendslogin, and once it reportslinkedsendslogout. The sidecar sends the frame Baileys'logoutbuilds (remove-companion-device) through Baileys'queryrather thanlogout, which sends it without waiting for an answer, and awaits WhatsApp's reply. On aresultreply, 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 orlogged_outinstead 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 afterlogout(the arm then kills it), the answer is 502channeland 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
| What | Command | Needs |
|---|---|---|
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 ends | cargo test -p taji-whatsapp | Unix (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 quit | pnpm --filter @taji/whatsapp-sidecar test (also part of make test) | bun |
| The sidecar's types | pnpm --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 cutting | cargo test -p taji --lib -- channels markup | — |
taji-link whatsapp against a fake kernel | bun test agent/src/mcp/link.test.ts | bun |
| Build the sidecar beside a dev kernel | make 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:
- Run
make whatsapp, thenFRESH=1 make dev. - Open WhatsApp's row under Channels, choose Show the QR, and scan it from the phone.
- 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:
- WhatsApp:
- Baileys:
- Taji: