One long-lived process owns every chat-app connection. Four chat apps and three of your devices then need 7 links, not 12, and every device talks to the same agent with one memory.
Choose No gateway or One gateway, add chat apps, and press Send a message. Count the links, the memories and the fights over one login. Then we build the gateway piece by piece: the daemon, its clients, the adapters, the nodes, the event stream and its three rules.
You need to have used a chat app and a rough idea of what a server process is. A little Python helps for the labs. We build the rest from zero.
Lesson 1 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw, a self-hosted gateway between chat apps and an AI agent. We checked every OpenClaw detail here against its documentation.
Illustrative toy. The three devices are a terminal, a desktop app and a web page. The channel names are channels OpenClaw supports; we draw the message flow; we did not measure it.
Chapter 0
See why wiring every chat app to every device breaks, and put one hub in the middle
You want one assistant. You message it from WhatsApp on the bus, from Slack at work and from a terminal at home. You want the same assistant each time: the same memory, the same tools, the same conversation.
Build it with no central piece and each device runs its own bot for each chat app. Your terminal cannot see what your phone said. Worse, some chat connections allow only one owner. Three programs that share one WhatsApp login knock each other off.
The fix is a gateway: one process that owns every chat connection, while every device connects only to it. Count the links. Call the number of chat apps N and the number of your devices M.
L-mesh equals N times M, and L-hub equals N plus M.
Without a hub, multiply N by M: every pair needs its own link. With a hub, add N and M: every party needs one link.
With made-up numbers: N = 4 chat apps and M = 3 devices. L-mesh = 4 × 3 = 12. L-hub = 4 + 3 = 7. At 10 and 10 it is 100 against 20.
Grey is the mesh, orange is the hub. Drag the slider and watch the grey curve leave.
Both sides grow together here, so N = M. The count is exact; each link is also a socket to watch, retry and authenticate.
Links are only the visible cost. Each mesh link is a connection with its own login, retries and copy of the conversation. The hub gives you one place for each.
Chapter 1
Run the gateway as one supervised background process, and stop a second copy from stealing its logins
A daemon is a program that starts once and keeps running in the background with no terminal attached. sshd and dockerd are daemons. The gateway is one too.
Why not start a fresh process for each message? Because what it holds lives a long time. A logged-in WhatsApp session, an open socket to Slack and a running agent turn do not survive a restart for every message. The daemon keeps them alive between messages.
The rule is one gateway per host. It is the only process that opens each single-owner login. If a second copy opens the same login, the chat service keeps one and drops the other. The dropped copy reconnects and drops the first. This loop is a flap, and every flap can lose a message.
Gateway A owns the WhatsApp login. Press Boot gateway B with the rule off, then turn the rule on and try again. Crash A shows the supervisor.
Illustrative timing: one takeover every 1.2 s and a 2 s restart. The rule itself is OpenClaw's: exactly one gateway controls a single Baileys session per host.
OpenClaw drives WhatsApp through Baileys, an open-source WhatsApp Web library. Its docs state the rule: exactly one gateway controls a single Baileys session per host. The gateway is the only place that opens a WhatsApp session.
Because everything depends on this one process, a supervisor runs it: a system service that starts it at boot and restarts it after a crash. OpenClaw installs a launchd LaunchAgent on macOS and a systemd user unit on Linux. You can also start it by hand with openclaw gateway --port 18789.
The gateway is a server. By default it binds to 127.0.0.1:18789. Loopback, the 127.0.0.1 address, means only programs on the same machine can reach it. Lesson 3 covers opening it up safely.
Chapter 2
Split the world into thin clients and one fat hub, and give each client a role when it connects
If the gateway owns everything, every other program is a client: a program that connects to the gateway and asks it to act. The desktop app, the command line and the web page are all clients. Swap one for another and you still talk to the same agent.
Networking has words for this split. The control plane carries intent: "run the agent", "show the history", "change a setting". The data plane holds the heavy, stateful work: the chat connections, the agent run and the transcripts. Clients live in the control plane. The gateway is the data plane.
In OpenClaw each client opens one WebSocket, a two-way connection that stays open, to the gateway. Its first message declares a role. There are two roles that matter here.
| Role | What it is | Direction | Examples |
|---|---|---|---|
| operator | a control client that drives the gateway | sends requests, receives events | CLI, macOS app, web UI, a script |
| node | a capability host that offers abilities | receives commands, returns results | a phone's camera, a Mac's screen |
Pick a client. Watch which way the arrows point: an operator asks the gateway, the gateway asks a node.
The fields (role, caps, commands, permissions) and the example values come from OpenClaw's handshake docs. We trimmed the frames; a real connect carries more fields.
An operator asks; a node lets the gateway act on it. One laptop can connect twice: once as an operator for you to type, once as a node so the agent can capture its screen. OpenClaw also names a third role, worker, for cloud execution hosts; this series does not need it.
A browser tab is a client too. The gateway can serve small web pages of its own on the same port, under /__openclaw__/canvas/. The tab that shows them connects like any other operator.
Chapter 3
Translate every chat app's message into one shape at the edge, so the core never learns a dialect
Now look at the other side of the hub. A channel is one chat app the gateway connects to. OpenClaw's architecture page lists WhatsApp (through Baileys), Telegram (through the grammY library), Slack, Discord, Signal, iMessage and a built-in WebChat. Its channel list is longer, and each channel ships as a plugin.
Each channel speaks its own dialect. A new Telegram message and a new Slack message share almost no field names. If the core knew every dialect, each new feature would need code for every channel.
The fix is an adapter: a small piece of code at the edge that translates in both directions. Inbound, it turns the channel's event into one shape the core understands. Outbound, it turns "send this reply" into the channel's own API call.
Pick a channel and compare its raw message with the one shape the core sees. Turn the adapters off to see the core learn every dialect.
We trimmed each raw shape from the platform's public message format. The normalized shape is our own example, not OpenClaw's internal type. The four core features are illustrative.
The count has the same shape as Chapter 0. Take 4 channels and 4 core features: reply, history, agent run and presence. Direct wiring needs 4 × 4 = 16 pieces of channel code in the core. Adapters need 4 adapters plus 4 features that each read one shape: 8.
The adapter normalizes each message once. Then the gateway can hand it to the agent and also show it on every operator that watches. That is the fan-out you saw in the hero.
if channel == "slack". Each hit is a leak.Chapter 4
Let a device offer abilities to the agent, and let the gateway decide which of them may run
A node is a device that lends the agent hands: a phone with a camera, a Mac with a screen and a shell. It connects to the same WebSocket server with role: "node" and says what it can do, in three lists.
| List | Means | OpenClaw example |
|---|---|---|
| caps | broad kinds of ability | camera, canvas, screen, location, voice |
| commands | the exact calls it accepts | camera.snap, canvas.navigate, screen.record, location.get |
| permissions | switches the device owner turned on or off | {"camera.capture": true, "screen.record": false} |
The gateway treats these lists as claims, not proof, and enforces its own allowlist on top. When the agent wants a photo, the gateway sends node.invoke, which forwards one command to one node. So who may run a command? Call three yes-or-no answers d, g and p, each 1 for yes and 0 for no.
allow equals d times g times p.
Ask three questions: did the node declare it (d), does the gateway allow it (g), is the switch on (p)? Multiply the answers. Any single no blocks the command.
A webcam declares camera.snap, so d = 1. The gateway allows it, so g = 1. Its camera.capture switch is off, so p = 0. allow = 1 × 1 × 0 = 0: denied.
Each cell is one command on one node. Tap a cell for its d, g and p. Flip the toggles and watch cells change.
The command and permission names follow OpenClaw's examples. Which switch each command needs is our illustration; the docs do not publish that mapping.
Why so strict? A Mac node that accepts system.run lets the agent run shell commands on that Mac. That is remote code execution. In OpenClaw, an operator can block commands with the config key gateway.nodes.commands.deny, and node commands stay subject to pairing approval. Lesson 3 covers pairing; Lesson 10 covers approvals for running commands.
camera.snap, the gateway allows it, but the node's camera.capture switch is off. What happens on node.invoke?Chapter 5
Push every change to the clients the moment it happens, and number each event so a client can spot a loss
A WhatsApp message lands. Your desktop app shows it at once, with no refresh. How? The gateway does not wait for a question. It pushes an event, a message that says something changed, to every connected client.
OpenClaw's gateway emits events named agent, chat, presence (who is online), health, heartbeat and cron (scheduled jobs). Clients also receive tick, a keepalive, and shutdown. The handshake docs show a tick every 15,000 ms.
Each event frame can carry a sequence number, seq: a counter that goes up by one for each event on that connection. OpenClaw keeps a separate counter for each client, so the order on each socket is strict. A jump in the counter means a lost event. How many were lost?
missed equals s-new minus s-last minus one.
Subtract s-last from s-new, then subtract the normal step of 1. If the result is above 0, the client lost that many events.
The client applied event 7 and then gets event 9. missed = 9 − 7 − 1 = 1. Event 8 is gone.
Numbered events flow from the gateway to a client. Press Drop the next event and watch the client catch the gap.
Illustrative stream, sped up: one event every 0.9 s. The event names are OpenClaw's; we made up their order.
Chapter 6
After a gap, throw away the stale view and take a fresh snapshot, because a replay log costs far more
The client knows event 8 is lost. It could ask the gateway to send event 8 again. OpenClaw's rule says no: events are not replayed, and clients must refresh on gaps.
To refresh is to drop the stale view and fetch the current truth. In OpenClaw the client closes the connection and reconnects. The gateway's first reply to a new connection carries a snapshot: the current state, such as who is online, with a state version.
Why not keep old events for replay? A replay log must hold every event for every client for some time window. Call the event rate r, the window T, the size of one event b and the number of clients C. The log holds B bytes.
B equals r times T times b times C.
Multiply the events per second r by the seconds kept T to get events kept. Multiply by the size b and by the clients C. That is B.
With made-up numbers: r = 20, T = 3,600 s, b = 500 bytes, C = 5. B = 20 × 3,600 × 500 × 5 = 180,000,000 bytes, 180 MB. Five 50 KB snapshots are 0.25 MB.
Drag the rate, the window and the clients. The bars use a log scale: each step up is ten times more.
Illustrative sizes: 500 bytes per event and 50 KB per snapshot. Real sizes vary; the ratio is the point.
Cost is half the reason. The other half is truth. A replayed log rebuilds the state from pieces, and one wrong piece leaves the client wrong forever. A snapshot is the state itself, so a refreshed client cannot drift.
Chapter 7
Name the three invariants the gateway rests on, and test the handshake that closes the door on a bad first frame
An invariant is a rule a system keeps true at all times. The gateway rests on three. Each one, broken, is a specific failure.
| Invariant | OpenClaw's wording | If it breaks |
|---|---|---|
| 1. One owner per login | exactly one gateway controls a single Baileys session per host | two owners flap and messages get lost (Chapter 1) |
| 2. Handshake first | the first frame must be connect; a non-JSON or non-connect first frame is a hard close | a client acts before it says who it is |
| 3. No replay | events are not replayed; clients must refresh on gaps | a client acts on a view with holes (Chapters 5 and 6) |
Invariant 2 is the door. When a socket opens, the gateway first sends a connect.challenge event with a nonce, a random value used once. The client's first frame must then be a connect request. Anything else ends the connection.
Pick what the client sends first. Watch the exchange run top to bottom.
From OpenClaw's protocol docs: the challenge, the connect-first rule, close code 1007 for malformed JSON, and the 64 KiB cap on frames before connect. The docs give no single close code for a non-connect first frame.
Why so strict? A server that guesses what a bad frame meant has code paths that run before it knows who the client is. A hard close keeps that set empty. The 64 KiB cap does the same for size: a stranger cannot make the gateway buffer a huge frame.
connect as the first frame, then everything else.status, not connect. What does the gateway do?Chapter 8
Run every part at once: a message in, an agent turn, a node command, a fan-out, a gap and a rival process
Here is the map for the whole series. Channels sit on the left. The gateway is in the middle with the agent under it. Operators sit at the top right, nodes at the bottom right.
Press Inbound message. Pair the Mac node and send again: the agent now uses it. Then drop an event, or boot a rival gateway.
Illustrative flow and timing. Each part follows the rules above; we made up the messages.
Read one message end to end. The WhatsApp adapter normalizes it. The gateway starts an agent turn and pushes a chat event to every operator. If the agent needs the screen, the gateway checks d, g and p, then sends node.invoke. The reply goes out through the same adapter.
Each control breaks or tests one rule. Drop an event tests Invariant 3: the client refreshes. Boot a rival gateway tests Invariant 1: the rival finds the port taken and exits. Lesson 2 opens the socket and reads its frames.
Chapter 9
Keep the terms, the numbers, a checklist and the core code in one place
One daemon owns every single-owner connection. Everything else is a client: operators drive it, nodes lend it hands. Adapters turn many dialects into one shape. Events carry a counter, and a gap means refresh. Three invariants hold it together.
| Term | Meaning | OpenClaw value |
|---|---|---|
| gateway | the one daemon that owns channels and the agent | openclaw gateway |
| bind address | where it listens | 127.0.0.1:18789, loopback by default |
| supervisor | keeps it running | launchd (macOS), systemd (Linux) |
| channel | one chat app | WhatsApp via Baileys, Telegram via grammY, Slack, Discord, Signal, iMessage, WebChat, and more |
| operator | a control client | CLI, macOS app, web UI, automations |
| node | a capability host | declares caps, commands, permissions; called with node.invoke |
| event | a pushed change notice | agent chat presence health heartbeat cron, plus tick shutdown |
| tick | a keepalive | 15,000 ms in the docs example |
| seq | a counter on each event | one counter per connection |
| pre-connect cap | largest frame before connect | 64 KiB |
A toy gateway with all three invariants. It is a sketch for reading, not OpenClaw's code.
pythonimport json, fcntl class Gateway: def __init__(self, lock_path, deny): self.lock = open(lock_path, "w") # invariant 1: one owner per host fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB) # raises if another gateway holds it self.clients, self.deny = {}, deny # conn -> {"role", "seq", "node"} def on_first_frame(self, conn, raw): # invariant 2: handshake first try: f = json.loads(raw) except ValueError: return conn.close(1007, "invalid JSON") if f.get("method") != "connect": return conn.close(1008, "connect first") p = f["params"] self.clients[conn] = {"role": p["role"], "seq": 0, "node": p} conn.send({"type": "res", "ok": True, "payload": self.snapshot()}) def broadcast(self, event, payload): # push; one counter per connection for conn, c in self.clients.items(): c["seq"] += 1 # invariant 3: no log kept to replay conn.send({"type": "event", "event": event, "payload": payload, "seq": c["seq"]}) def allow(self, node, cmd, needs): # allow = d x g x p return (cmd in node["commands"]) and (cmd not in self.deny) and node["permissions"].get(needs[cmd], False) def on_event(client, frame): # client side: spot a gap, then refresh missed = frame["seq"] - client.last - 1 if missed > 0: return client.reconnect_and_snapshot() client.last = frame["seq"]; client.apply(frame)
Now press Present or Teach and explain it from memory. Cover why one process owns the connections, operator against node, what an adapter does, the d, g and p check, and the three invariants. Then go back to the hero and route a message both ways again.