Everything between a gateway and its clients rides one WebSocket as one of three JSON frames. A request asks, a response answers with the same id, and an event arrives unasked with a sequence number.
Choose Request, Event or Lost reply and press Send. Watch which frames cross the socket and read the last one below. Then we build the protocol piece by piece: push, the three frames, ids, the handshake, discovery, retries, limits, backpressure and liveness.
You need Lesson 1, the gateway, and to know what JSON is. A little Python helps for the labs. We build the rest from zero.
Lesson 2 of 11 in Anatomy of an Agent Gateway. The running example is the OpenClaw gateway protocol. We checked every OpenClaw detail here against its protocol documentation.
Illustrative toy. The frame shapes and the method names health and chat.send are OpenClaw's. We made up the ids, keys and timing.
Chapter 0
Measure what polling costs, and see why one open socket removes both costs
A WhatsApp message reaches the gateway. Your laptop should show it now. But in ordinary web traffic, a server speaks only when a client asks.
A client can fake it by polling: it asks "anything new?" on a timer. Most asks come back empty. A message that lands just after an ask waits for the next one.
How long does a message wait? Call the time between two asks the poll interval, I. A message can land at any moment inside an interval, so on average it waits half of one. Call that average wait w̄, said "w-bar".
w-bar equals I divided by two.
Take the poll interval I and halve it. That is how long a message waits on average. The worst wait is a full I.
With made-up numbers: I = 2 s, so w-bar = 2 / 2 = 1 s and the worst wait is 2 s. The client also sends 3,600 / 2 = 1,800 asks an hour. With 10 messages an hour, 1,790 asks come back empty.
Three messages arrive in 20 seconds. Top: blue ticks are asks, grey ones came back empty, yellow bars are waits. Bottom: push. Drag the interval.
Illustrative arrival times: 3.3 s, 9.1 s and 14.6 s. Network time is left out, so push shows a wait of about 0 s.
A WebSocket removes both costs. It is one long-lived, two-way connection: once it is open, either side can send at any time. The gateway sends a message the moment it has one. Lesson 1 calls these pushed messages events.
Chapter 1
Read the one field that names each frame, and route every frame with a single branch
A WebSocket carries frames: separate messages with clear edges, so one message never runs into the next. OpenClaw sends text frames, and each frame holds one JSON object. Every object has one of three shapes.
| Frame | Sender | Fields in OpenClaw | Job |
|---|---|---|---|
req | client | type, id, method, params | ask the gateway to do one thing |
res | gateway | type, id, ok, payload or error | answer exactly one req |
event | gateway | type, event, payload, optional seq and stateVersion | report a change nobody asked about |
The field type is a tag: one field that names the shape of the rest of the object. The receiver reads type and branches three ways. It never guesses the shape from the other fields.
Pick a frame. The receiver reads type and sends the frame down one branch.
The three frames, the tick example and close code 1007 for malformed JSON come from OpenClaw's protocol docs. The gateway runs requests; the client handles res and event.
A failed request still gets a res, with ok false and an error object: code, message, and optional details, retryable and retryAfterMs. Clients branch on code. The message is text for people, and it can change.
type.type first. Keep or skip an unknown type; never crash on it.Chapter 2
Send requests without waiting, and match each answer to its question by id
Your desktop app starts. It needs the session list, the gateway's health and the chat history. It can ask one question, wait, and ask the next. Or it can send all three at once.
Sending without waiting is pipelining. Call the time the gateway needs for request number i ti. One at a time, the waits add up. Pipelined, they overlap, and you wait for the slowest one only.
T-seq equals the sum over i of t-i, and T-pipe equals the max over i of t-i.
One at a time, add every t-i to get T-seq. Pipelined, take the largest t-i: that is T-pipe.
With made-up times: sessions.list 300 ms, health 40 ms, chat.history 120 ms. T-seq = 300 + 40 + 120 = 460 ms. T-pipe = 300 ms: ready 160 ms sooner.
Overlap has a price. The gateway runs started requests at the same time, so the answers come back in the order they finish. Here health finishes first.
Orange bars are the gateway's work on each request. Choose how the client sends and how it matches. Read the right column.
Illustrative times. OpenClaw's docs say started requests complete concurrently, so responses can arrive out of order.
The id fixes the order problem. The client picks a fresh id for each req, such as "r2", and keeps a table of pending ids. The res copies that id, so the client finds the right caller. In OpenClaw an id is a non-empty string.
req and each res, and compare them.Chapter 3
Answer the challenge, agree on a protocol version, and read the rules in hello-ok
Lesson 1 showed the door: the first frame must be a connect request, or the gateway closes the socket. Here are the three frames of the handshake, opened up.
connect.challenge, with a nonce (a random value used once) and a timestamp ts.req connect. Its params carry minProtocol and maxProtocol, the client's name, and its role (operator or node). They also carry the scopes it asks for, an auth token, and a device block that signs the nonce.res whose payload is hello-ok: the agreed protocol, plus server, features, snapshot, auth and policy.A signature over a fresh nonce proves the client answers this challenge now. A recorded old handshake fails. Lesson 3 opens the device block.
Clients and gateways update on different days. So the client sends a range of versions, not one number. Call the client's lowest version pmin, its highest pmax, and the gateway's current version P.
accept is true when p-min is at most P, and P is at most p-max.
minProtocol.maxProtocol.Check that P sits inside the client's range, from p-min to p-max. If it does, both sides speak P. If not, the gateway refuses.
A client sends p-min 3 and p-max 4, and P is 4. 3 ≤ 4 ≤ 4 holds, so accept is true and hello-ok says protocol 4. The gateway refuses an operator that sends 3 to 3.
The blue bar is the client's range. The orange mark is the gateway's version, 4. Drag the ends and switch the role.
From OpenClaw's versioning docs: protocol 4 is current; operators must include it; nodes may use version 3. The hello-ok fields follow the docs example, shortened.
The control above shows OpenClaw's one exception. A node, a device that lends the agent hands, may still connect on version 3, one behind. Operators must include version 4.
The connect has a total deadline of 30 s. Right after connect, a client may send up to 15 small frames of at most 64 KiB each. The gateway holds them and runs them in order once hello-ok is out.
minProtocol and maxProtocol with the gateway's version.maxProtocol to the new version and ship the client.Chapter 4
Read the method list in hello-ok instead of hardcoding it, so old and new parts can mix
hello-ok carries features.methods, the methods this gateway accepts, and features.events, the events it can push. A client that reads these lists at connect time does discovery. A client that ships a fixed list is hardcoded.
The difference shows when versions drift. Call the set of methods the client's code knows K, and the set the gateway lists A. The client can safely offer only the methods in both sets.
C equals K intersect A.
features.methods.Start from the methods the client knows, K. Strike out each one that A does not list. What is left is C, the safe set.
With made-up lists: K = {health, chat.send, sessions.list} and A = {health, chat.send, chat.history}. C = {health, chat.send}. The client hides sessions.list and ignores chat.history.
Left: what the client knows. Right: what the gateway lists. Switch the gateway release, then switch discovery off.
Illustrative releases. The method names are OpenClaw's; chat.pin is a made-up future method.
OpenClaw defines every frame and payload once, in TypeBox: a TypeScript library that turns one type definition into a JSON Schema. The gateway checks every inbound frame against that schema before any handler runs. The same schemas generate Swift models for the Apple apps and Kotlin models for Android.
The Swift models keep a frame with an unknown type as raw data, so an older app survives a newer gateway. The advertised list is conservative: a few helper methods work but are not listed.
features.methods in hello-ok.Chapter 5
Tag every side effect with a key, so a retry returns the first answer instead of acting twice
The client sends chat.send. The gateway posts the message. The reply is lost on the way back. The client heard nothing, so it sends again. Without help, your friend gets the message twice.
A read such as health is safe to repeat. A side effect, a change in the world such as a post or an agent run, is not. Call the chance that a reply is lost q. If the client retries until a reply arrives, how many times does the gateway act?
The expected sends equal one divided by one minus q.
Each try reaches the gateway, and the gateway acts. A try ends the loop only if its reply gets back, with chance 1 − q. So the tries average 1 divided by 1 − q.
With made-up numbers: q = 0.2, so E[sends] = 1 / 0.8 = 1.25. Over 100 messages the gateway posts about 125 times: 25 duplicates.
Each square is one message. A red square shows how many times the gateway posted that message. A grey dot means a retry got the stored answer. Turn on the key.
Illustrative random run. We assume each try reaches the gateway and only the reply can be lost.
The fix is an idempotency key: a unique string the client makes once for one action and resends on every retry of that action. The gateway keeps a short-lived dedupe cache from key to response. A new key: act, store the response, return it. A known key: skip the action and return the stored response.
Now E[sends] is 1 for any q. In OpenClaw, side-effecting methods such as send, agent, poll and chat.send take an idempotencyKey in params. For chat.send, stored user messages and receipts block a duplicate even after the cache expires or the gateway restarts.
Chapter 6
Read the size caps in hello-ok, and check the encoded size of a frame before you send it
One process serves every client. A single huge frame could make it hold hundreds of megabytes. So the gateway caps frame sizes, and it tells each client the caps in hello-ok.policy.
| Limit | OpenClaw value | Applies to |
|---|---|---|
| pre-connect cap | 64 KiB | every frame before hello-ok |
maxPayload | 26,214,400 bytes (25 MiB) | one frame after hello-ok |
maxBufferedBytes | 52,428,800 bytes (50 MiB) | data queued for one slow client (Chapter 7) |
attachments.maxBytes | 20 MB by default | one decoded chat attachment |
attachments.maxImageBytes | 6 MB | one decoded image |
The trap is encoding. JSON carries a file as base64: text that spends 4 characters for every 3 bytes. Call the file's real size sfile and its size inside the frame swire.
s-wire equals four thirds times s-file.
Multiply the file size s-file by 4 and divide by 3. That is s-wire. Add the rest of the request, then compare the total with maxPayload.
OpenClaw's docs give this case: s-file = 20 MB, so s-wire = 4/3 × 20,000,000 ≈ 26.7 MB. That is above the 26.2 MB maxPayload. The largest file that fits is about 26,214,400 × 3/4 = 19,660,800 bytes, before the rest of the JSON.
Yellow is the file. Teal is the same file as base64 on the wire. Drag the size past the dashed lines.
Limits from OpenClaw's handshake docs. MB here means 1,000,000 bytes; the JSON around the file is left out.
The reference client checks the serialized size before it sends. A request that is too big fails locally with its size and the limit, and the socket stays open for a smaller try. With diagnostics on, an oversized frame makes the gateway emit a payload.large event. It holds the sizes, the limit and a reason code, never the body or a secret.
Chapter 7
Cap the send queue for each client, so one slow phone cannot use up the gateway's memory
The gateway pushes events to every client. A laptop on fibre takes them as fast as they come. A phone in a tunnel takes them slowly, and the rest waits in a send queue in the gateway's memory.
Backpressure is the rule that a slow reader slows or stops the writer, so the queue cannot grow forever. The gateway caps each client's queue at maxBufferedBytes. Call that cap Bmax, the rate the gateway writes for one client rin, and the rate that client drains rout.
t-full equals B-max divided by r-in minus r-out.
The queue grows by r-in minus r-out each second. Divide the cap B-max by that growth. If r-out is at least r-in, the queue never fills.
With made-up rates: r-in = 2 MB/s during a long agent reply and r-out = 0.5 MB/s. t-full = 52,428,800 / 1,500,000 ≈ 35 s.
The gateway writes 2 MB/s to each client. Grey bars are the queues, the dashed line is the cap. Drag the phone's speed and press Play.
Illustrative rates, time sped up four times. The 50 MiB cap is OpenClaw's example value.
At the cap, the gateway acts on that one client: it drops the frame or closes the connection. With diagnostics on, it emits payload.large first. The other clients never notice. When the phone reconnects, it gets a fresh snapshot, as Lesson 1 showed.
Chapter 8
Prove the link is alive with a steady tick, call it dead after two silent intervals, and wait longer between retries
A socket can die without a sound. A phone sleeps, or a router drops an idle connection. Both ends can still believe the socket is open.
The gateway sends a tick event on a steady beat. hello-ok names the beat in policy.tickIntervalMs: 15,000 ms in the docs example. OpenClaw's reference client watches for silence. Say no event and no response arrives for more than twice the tick interval. Then it closes the socket with code 4000, fails every pending request, and reconnects. It does not resend those requests.
Retrying in a tight loop would flood a gateway that just came back. So the client waits longer after each failed try. Call the first wait d0, the cap dmax, and the number of failed tries so far k.
d-k equals the min of d-zero times two to the k, and d-max.
Double the first wait d-zero once for each failed try k. If the result passes d-max, wait d-max instead.
With d-zero = 1 s and d-max = 30 s, the waits are 1, 2, 4, 8, 16, then 30, 30 s. The doubling is our assumption: OpenClaw's docs give only the start and the cap.
Orange dots are ticks. Press Cut the network and watch the silence bar reach 30 s. Then restore it between retries.
Time sped up four times. The 15 s tick, the silence limit, code 4000 and the 1 s to 30 s backoff come from OpenClaw's docs. The doubling is our assumption.
The new connection is a new start. It gets a new challenge, a new hello-ok with a fresh snapshot, and its own seq counter, which starts again. The client checks seq on every event, as Lesson 1 taught. The lab builds that check.
tickIntervalMs, then reconnect with backoff.Chapter 9
Run a full session: connect, ask, lose a reply, push, drop an event and go silent
Here is one connection from start to end. Time runs down. The client is on the left, the gateway on the right, and each arrow is one frame.
Press Ask health first and see the door close. Then Connect, and try every control.
Illustrative session. The frame names, the version, the 4000 close and the refresh rule are OpenClaw's. We made up the ids, keys and payloads.
Each control tests one chapter. Connect runs the handshake of Chapter 3. Ask health runs the id match of Chapter 2. chat.send with a lost reply runs the key of Chapter 5. Drop next event shows a seq gap, and Go silent runs Chapter 8.
Chapter 10
Keep the frames, the numbers, a checklist and the core code in one place
One WebSocket carries three frames. A req asks, a res answers with the same id, and an event reports a change with a seq. The handshake checks the version range and returns the methods, the snapshot and the limits. Keys make retries safe. Caps protect the gateway. Ticks prove the link is alive.
| Term | Meaning | OpenClaw value |
|---|---|---|
| frame | one WebSocket text message, one JSON object | req, res or event |
| id | ties a res to its req | a non-empty string |
| error | the body of a failed res | code, message, details?, retryable?, retryAfterMs? |
| connect.challenge | first frame from the gateway | nonce, ts |
| protocol | the version both sides speak | 4; nodes may use 3 |
| hello-ok | the answer to connect | protocol, server, features, snapshot, auth, policy |
| idempotencyKey | one key per action, reused on retry | send, agent, poll, chat.send |
| maxPayload | largest frame after hello-ok | 26,214,400 bytes |
| maxBufferedBytes | queue cap for one client | 52,428,800 bytes |
| pre-connect cap | largest frame before hello-ok | 64 KiB |
| tickIntervalMs | keepalive beat | 15,000 ms in the docs example |
| silence close | client gives up on a quiet socket | code 4000 after 2 × tick |
| backoff | wait between reconnect tries | 1,000 ms up to 30,000 ms |
| bad JSON | close for a malformed frame | code 1007, "invalid JSON" |
type tag; the receiver branches on it first.maxPayload before it sends.A toy client receive loop with every rule above. It is a sketch for reading, not OpenClaw's code.
pythonimport json, time, uuid class Client: def __init__(self, ws, known): self.ws, self.known = ws, set(known) # K: methods this code can use self.pending, self.n = {}, 0 # id -> callback self.last_seq, self.last_frame = 0, time.time() def call(self, method, params, cb, side_effect=False): if method not in self.offer: raise KeyError(method) # C = K ∩ A if side_effect: params.setdefault("idempotencyKey", str(uuid.uuid4())) self.n += 1; rid = "r%d" % self.n frame = json.dumps({"type": "req", "id": rid, "method": method, "params": params}) if len(frame.encode()) > self.max_payload: raise ValueError("too big") self.pending[rid] = cb; self.ws.send(frame) return params # reuse these params (same key) on retry def on_hello(self, hello): self.offer = self.known & set(hello["features"]["methods"]) self.max_payload = hello["policy"]["maxPayload"] self.tick = hello["policy"]["tickIntervalMs"] / 1000 self.last_seq = 0; self.apply_snapshot(hello["snapshot"]) def on_frame(self, raw): f = json.loads(raw); self.last_frame = time.time() if f["type"] == "res": # match by id, never by order cb = self.pending.pop(f["id"], None) if cb: cb(f["payload"] if f["ok"] else f["error"]) elif f["type"] == "event": s = f.get("seq") if s is not None: if s > self.last_seq + 1: return self.reconnect() # gap: refresh, no replay self.last_seq = s self.apply(f) # any other type: keep it raw and move on def watchdog(self): # run every second if time.time() - self.last_frame > 2 * self.tick: self.ws.close(4000); self.pending.clear(); self.reconnect() def backoff(self, k): # d_k = min(d0 * 2^k, dmax) return min(1.0 * 2 ** k, 30.0)
agent request starts, and how its reply streams back as events.Now press Present or Teach and explain it from memory. Cover push against polling, the three frames, the id, the version check, discovery, the idempotency key, the base64 trap, backpressure and the 4000 close. Then go back to the hero and lose a reply again.