The Wire Protocol

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.

Put a frame on the wire

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

Why Push, Not Poll

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".

Say it aloud

w-bar equals I divided by two.

w̄
w-bar the average time a new message waits before the client sees it, in seconds.
I
I the poll interval: the seconds between two asks.
/ 2
divided by two a message lands, on average, halfway through an interval.
In plain words

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 numbers

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.

Poll or push the same messages

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.

2.0

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.

The road

  1. Three frame shapes: req, res and event, and the one field that tells them apart.
  2. Many questions in flight: send without waiting, match answers by id.
  3. The handshake, field by field: the challenge, connect, the version range and hello-ok.
  4. Discovery: read what the gateway speaks instead of hardcoding it.
  5. Send once, even on resend: idempotency keys and the dedupe cache.
  6. Frame size limits: the caps in hello-ok and the base64 trap.
  7. Backpressure: one slow client must not use up the gateway's memory.
  8. Ticks, silence and reconnects: prove the link is alive, back off when it is not.
  9. The whole wire, live: a full session, frame by frame.
  10. Field guide: terms, numbers, a checklist and the core code.
A client polls every 4 seconds. On average, how long does a new message wait before the client sees it?

Chapter 1

Three Frame Shapes

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.

FrameSenderFields in OpenClawJob
reqclienttype, id, method, paramsask the gateway to do one thing
resgatewaytype, id, ok, payload or erroranswer exactly one req
eventgatewaytype, event, payload, optional seq and stateVersionreport 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.

Route a frame by its tag

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.

Which field tells the receiver how to read the rest of a frame?

Chapter 2

Many Questions in Flight

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.

Say it aloud

T-seq equals the sum over i of t-i, and T-pipe equals the max over i of t-i.

Tseq
T-seq the total time when the client waits for each answer before it asks again.
Σi
the sum over i add one term for each request.
ti
t-i the time the gateway needs for request i, in milliseconds.
Tpipe
T-pipe the total time when the client sends every request at once.
maxi
the max over i keep only the largest t-i.
In plain words

One at a time, add every t-i to get T-seq. Pipelined, take the largest t-i: that is T-pipe.

With numbers

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.

Match the answers

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.

A client sends three requests at once and the answers return out of order. How does it know which answer belongs to which request?

Chapter 3

The Handshake, Field by Field

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.

  1. The gateway sends an event, connect.challenge, with a nonce (a random value used once) and a timestamp ts.
  2. The client sends 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.
  3. The gateway answers with a 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.

Say it aloud

accept is true when p-min is at most P, and P is at most p-max.

accept
accept true if the gateway lets the client in, false if it refuses.
pmin
p-min the lowest protocol version the client speaks: minProtocol.
≤
is at most the left number is less than or equal to the right one.
P
P the gateway's current protocol version: 4 in OpenClaw today.
pmax
p-max the highest protocol version the client speaks: maxProtocol.
In plain words

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.

With numbers

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.

Negotiate a version

The blue bar is the client's range. The orange mark is the gateway's version, 4. Drag the ends and switch the role.

3
4

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.

An operator client sends minProtocol 2 and maxProtocol 3. The gateway speaks version 4. What happens?

Chapter 4

Discovery: Ask What the Gateway Speaks

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.

Say it aloud

C equals K intersect A.

C
C the methods the client offers and calls.
K
K the methods the client's code knows how to use.
∩
intersect keep only what is in both sets.
A
A the methods the gateway lists in hello-ok, features.methods.
In plain words

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 numbers

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.

Mix old and new

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.

A newer gateway adds a method the old client has never heard of. The client reads features.methods. What happens?

Chapter 5

Send Once, Even on Resend

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?

Say it aloud

The expected sends equal one divided by one minus q.

E[sends]
the expected sends how many times the gateway acts for one message, on average over many messages.
1 /
one divided by the fewer replies get back, the more tries it takes.
1 − q
one minus q the chance that a reply gets back. q is the chance it is lost, from 0 to 1.
In plain words

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 numbers

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.

Retry 100 messages

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.

20

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.

The reply to a chat.send is lost, and the client retries with the same idempotency key. What does the gateway do?

Chapter 6

Frame Size Limits

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.

LimitOpenClaw valueApplies to
pre-connect cap64 KiBevery frame before hello-ok
maxPayload26,214,400 bytes (25 MiB)one frame after hello-ok
maxBufferedBytes52,428,800 bytes (50 MiB)data queued for one slow client (Chapter 7)
attachments.maxBytes20 MB by defaultone decoded chat attachment
attachments.maxImageBytes6 MBone 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.

Say it aloud

s-wire equals four thirds times s-file.

swire
s-wire the bytes the attachment takes inside the frame.
4/3
four thirds base64 writes 4 characters for each 3 bytes.
×
times multiply.
sfile
s-file the file's real size, in bytes.
In plain words

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.

With numbers

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.

Fit a file in one frame

Yellow is the file. Teal is the same file as base64 on the wire. Drag the size past the dashed lines.

20

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.

An 18 MB file goes into one chat.send as base64. Does it fit under a maxPayload of 26.2 MB?

Chapter 7

Backpressure: One Slow Client

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.

Say it aloud

t-full equals B-max divided by r-in minus r-out.

tfull
t-full the seconds until this client's queue is full.
Bmax
B-max the cap on queued bytes for one client: 52,428,800 in OpenClaw's example.
rin
r-in the bytes per second the gateway writes for this client.
−
minus the queue grows by the difference.
rout
r-out the bytes per second the client drains.
In plain words

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 numbers

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.

Fill a slow client's queue

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.

0.50

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.

The cap is 50 MB. The gateway writes 3 MB/s to a client that drains 1 MB/s. When is its queue full?

Chapter 8

Ticks, Silence and Reconnects

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.

Say it aloud

d-k equals the min of d-zero times two to the k, and d-max.

dk
d-k the wait before the next try, after k failed tries.
min
the min of take the smaller of the two values.
d0
d-zero the first wait: 1,000 ms in OpenClaw's client.
2k
two to the k 2 multiplied by itself k times: the wait doubles after each failure.
dmax
d-max the cap: 30,000 ms in OpenClaw's client.
In plain words

Double the first wait d-zero once for each failed try k. If the result passes d-max, wait d-max instead.

With numbers

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.

Cut the network

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.

hello-ok says tickIntervalMs is 15,000. When does OpenClaw's reference client close the socket with code 4000?

Chapter 9

The Whole Wire, Live

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.

Run a session

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.

The client sees seq jump from 4 to 6 on its socket. What does it do in OpenClaw?

Chapter 10

Field Guide

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.

TermMeaningOpenClaw value
frameone WebSocket text message, one JSON objectreq, res or event
idties a res to its reqa non-empty string
errorthe body of a failed rescode, message, details?, retryable?, retryAfterMs?
connect.challengefirst frame from the gatewaynonce, ts
protocolthe version both sides speak4; nodes may use 3
hello-okthe answer to connectprotocol, server, features, snapshot, auth, policy
idempotencyKeyone key per action, reused on retrysend, agent, poll, chat.send
maxPayloadlargest frame after hello-ok26,214,400 bytes
maxBufferedBytesqueue cap for one client52,428,800 bytes
pre-connect caplargest frame before hello-ok64 KiB
tickIntervalMskeepalive beat15,000 ms in the docs example
silence closeclient gives up on a quiet socketcode 4000 after 2 × tick
backoffwait between reconnect tries1,000 ms up to 30,000 ms
bad JSONclose for a malformed framecode 1007, "invalid JSON"

Checklist for any gateway protocol

The core, in code

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)

Where each thread continues

The takeaway. Tag every frame, give every request an id, check the version range at the door, read the method list, key every side effect, cap every frame and every queue, and treat silence as a dead link.
In one sentence, what is the wire protocol?

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.

Anatomy of an Agent Gateway, Lesson 2: The Wire Protocol
OpenClaw protocol docs · Previous: the gateway · Next: auth, pairing and trust · Back to Gleams