The Gateway

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.

Route one message

4

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

One Agent, Many Chat Apps

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.

Say it aloud

L-mesh equals N times M, and L-hub equals N plus M.

Lmesh
L-mesh the links to keep alive when every chat app connects to every device.
N
N the number of chat apps (channels), such as WhatsApp and Slack.
M
M the number of your devices or programs that talk to the agent.
Lhub
L-hub the links when each chat app and each device connects once, to the gateway.
In plain words

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 numbers

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.

Grow both sides

Grey is the mesh, orange is the hub. Drag the slider and watch the grey curve leave.

4

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.

The road

  1. One daemon owns the connections: why one long-lived process, and why only one per host.
  2. Everything else is a client: operators drive the gateway, nodes lend it hands.
  3. Channels behind adapters: many chat dialects in, one message shape out.
  4. Nodes and the capability check: what a device may do, and who decides.
  5. Pushed events and the sequence number: how clients stay current and spot a loss.
  6. Refresh, do not replay: what a client does after a gap, and why.
  7. Three rules and the strict door: the invariants, and the handshake that guards them.
  8. The whole gateway, live: every part in one picture.
  9. Field guide: terms, numbers, a checklist, the core code and where to go next.
Why can you not run a separate copy of each chat integration on every device?

Chapter 1

One Daemon Owns the Connections

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.

Boot a second gateway

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.

Why is "one gateway controls the WhatsApp session per host" a hard rule and not a preference?

Chapter 2

Everything Else Is a Client

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.

RoleWhat it isDirectionExamples
operatora control client that drives the gatewaysends requests, receives eventsCLI, macOS app, web UI, a script
nodea capability host that offers abilitiesreceives commands, returns resultsa phone's camera, a Mac's screen

Connect as a role

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.

You type commands into the desktop app. Your phone lets the agent take a photo. Which roles do they connect with?

Chapter 3

Channels Behind Adapters

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.

Normalize a message

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.

Why wrap each chat app in an adapter?

Chapter 4

Nodes and the Capability Check

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.

ListMeansOpenClaw example
capsbroad kinds of abilitycamera, canvas, screen, location, voice
commandsthe exact calls it acceptscamera.snap, canvas.navigate, screen.record, location.get
permissionsswitches 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.

Say it aloud

allow equals d times g times p.

allow
allow 1 if the command may run on this node, 0 if not.
d
d declared: 1 if the node listed the command when it connected.
g
g gateway policy: 1 if the gateway's allowlist permits the command and no deny rule blocks it.
p
p permission: 1 if the switch the command needs is on.
×
times multiplying 0s and 1s is a logical AND: one 0 makes the product 0.
In plain words

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.

With numbers

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.

Gate every node.invoke

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.

A node declares camera.snap, the gateway allows it, but the node's camera.capture switch is off. What happens on node.invoke?

Chapter 5

Pushed Events and the Sequence Number

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?

Say it aloud

missed equals s-new minus s-last minus one.

missed
missed how many events never arrived. 0 means in order.
snew
s-new the sequence number on the event that just arrived.
slast
s-last the sequence number on the last event the client applied.
1
one the normal step: the next event is s-last plus one.
In plain words

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.

With numbers

The client applied event 7 and then gets event 9. missed = 9 − 7 − 1 = 1. Event 8 is gone.

Drop an event in transit

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.

A client applied event 12 and the next event carries seq 16. How many events did it miss?

Chapter 6

Refresh, Do Not Replay

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.

Say it aloud

B equals r times T times b times C.

B
B the bytes the replay log must hold.
r
r the event rate, in events per second.
T
T the replay window: how far back a client may ask, in seconds.
b
b the size of one event, in bytes.
C
C the number of clients. Each needs its own copy, because each sees its own filtered stream.
In plain words

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 numbers

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.

Price a replay log

Drag the rate, the window and the clients. The bars use a log scale: each step up is ten times more.

20
60
5

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.

A client sees seq jump from 7 to 9. What does it do in OpenClaw?

Chapter 7

Three Rules and the Strict Door

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.

InvariantOpenClaw's wordingIf it breaks
1. One owner per loginexactly one gateway controls a single Baileys session per hosttwo owners flap and messages get lost (Chapter 1)
2. Handshake firstthe first frame must be connect; a non-JSON or non-connect first frame is a hard closea client acts before it says who it is
3. No replayevents are not replayed; clients must refresh on gapsa 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.

Knock on the door

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.

A client's first frame is a valid JSON request for status, not connect. What does the gateway do?

Chapter 8

The Whole Gateway, Live

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.

Run the gateway

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.

The agent wants a screenshot from a paired Mac. Which path does the request take?

Chapter 9

Field Guide

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.

TermMeaningOpenClaw value
gatewaythe one daemon that owns channels and the agentopenclaw gateway
bind addresswhere it listens127.0.0.1:18789, loopback by default
supervisorkeeps it runninglaunchd (macOS), systemd (Linux)
channelone chat appWhatsApp via Baileys, Telegram via grammY, Slack, Discord, Signal, iMessage, WebChat, and more
operatora control clientCLI, macOS app, web UI, automations
nodea capability hostdeclares caps, commands, permissions; called with node.invoke
eventa pushed change noticeagent chat presence health heartbeat cron, plus tick shutdown
ticka keepalive15,000 ms in the docs example
seqa counter on each eventone counter per connection
pre-connect caplargest frame before connect64 KiB

Checklist for any agent gateway

The core, in code

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)

Where each thread continues

The takeaway. Put one supervised daemon in the middle, make everything else a thin client, translate at the edges, check every node command three ways, number every event, and refresh on a gap.
In one sentence, what is the gateway?

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.

Anatomy of an Agent Gateway, Lesson 1: The Gateway
OpenClaw docs · Next: the wire protocol · Back to Gleams