Every message you send becomes a run: one ordered walk from intake to a saved transcript. In the middle, the model and its tools take turns until the model answers in text. A run that reads two files makes 3 model calls.
Pick a task and press Send the message. Watch the stages light, the model and the tool trade turns, and the transcript grow. Then pick Repeats itself and see what stops a model that never finishes. After that we build the run piece by piece.
You need Lesson 1 (one gateway owns the chat apps) and a rough idea of what a tool call is. A little Python helps for the labs. We build the rest from zero.
Lesson 4 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw's agent loop. We checked every OpenClaw detail here against its documentation.
Illustrative toy with made-up timing. The repeat guard numbers are OpenClaw's: a note on the 3rd identical call in a row, a stop on the 20th.
Chapter 0
Name the six stages every run walks, and keep a run apart from a session
You type "summarize my last three commits and post it to the team." Two seconds pass. Then a summary streams back, with a line saying it went to Slack. In between, the agent read files, called a git tool and called a messaging tool.
Lesson 1 drew the gateway and treated "the agent runs" as a black box. This lesson opens the box. Inside is a run: one execution of the agent on one inbound message, from intake to a saved transcript.
Every run walks the same six stages in the same order:
A run is not the conversation. The conversation is the session: the lasting transcript that many runs add to, one message at a time. Three messages in one chat make three runs and one session.
Each press sends one message. A new run walks the six stages, then adds its entries to the session on the right. Press New chat to open a second session.
Illustrative toy. Each run here adds three entries (your message, one tool result, the reply); a real run adds as many as it makes.
Why a fixed order? A run can read your files and post to Slack. Those acts are real and some cannot be undone. A fixed order means you always know which stage a run is in, what it may do there, and what comes next.
Chapter 1
Return a receipt at once, then let the caller watch events or wait for a status
An operator (the CLI, the desktop app, a script) asks the gateway to run the agent. In OpenClaw that request is an RPC named agent. The command openclaw agent "..." sends the same request.
The gateway checks the parameters, finds the session the message belongs to, and saves the session's metadata. Then it answers at once with a receipt: a new runId and an acceptedAt time. The receipt says "I took your request and named it." It does not say "here is the answer."
Why answer before the work is done? A run can take 50 ms or 50 minutes. If the caller's connection had to sit idle until the end, one slow run would freeze it. With a receipt, the connection stays free and the run goes on in the background.
The top lane is the caller, the bottom lane is the run. Choose how the caller starts the run, then drag the run's length.
Illustrative run lengths. The 30 s default wait of agent.wait is OpenClaw's.
So there are two ways to learn how a run went:
| Call | What the caller gets | Use it for |
|---|---|---|
agent | the receipt, then tool, assistant and lifecycle events tagged with the run id | a live chat screen |
agent.wait | {status, startedAt, endedAt, error?} for a run id, with status ok, error or timeout | a script that only needs to know when it is done |
Both watch the same run. They differ only in how the caller hears the outcome. The default wait is 30 seconds. Chapter 7 shows why "the wait timed out" is not "the run failed."
endedAt with the time the script gave up.lifecycle end event, or call agent.wait again.agent and get back {runId, acceptedAt} at once. What does that mean?Chapter 2
Make two runs on one chat take turns, and let runs on different chats go side by side
You message your agent from your phone. One second later you message the same chat from your laptop. Now two runs want to write to one transcript. If both write at once, run A's tool result lands in the middle of run B's reply. The transcript no longer makes sense.
The rule is one writer per session: in one session, runs take turns. The second run waits until the first is done. Runs in different sessions do not wait for each other.
How long does the second run wait? Call the time run A ends eA. Call the time run B arrives aB. Call B's wait wB.
w-B equals the larger of zero and e-A minus a-B.
Subtract B's arrival a-B from A's end e-A. If the result is positive, B waits that long. If not, B starts at once. A run in another session has w-B = 0.
With made-up numbers: A starts at 0 s and takes 8 s, so e-A = 8. B arrives at a-B = 1. w-B = max(0, 8 − 1) = 7 s. B starts at 8 s, and the transcript stays in order.
Run A takes 8 s. Drag when run B arrives. Turn the rule off to see the writes mix, or move B to another chat.
Illustrative timing. Each run is drawn as one block of writes; a real run writes many entries over its life.
OpenClaw enforces the rule in two layers. A session controller admits one turn per session at a time, before the gateway's global capacity check. Then every transcript write is fenced: each admitted run records itself as the session's activeWriterRunId, and each write carries an expectedWriterRunId that the commit checks. A run that lost its turn cannot commit stale entries. What happens to the waiting message (follow up, steer, interrupt) is Lesson 6.
Chapter 3
Collect what the model must see before the first call, and keep that picture fixed for the run
The model remembers nothing between calls. Each run must hand it a full picture: who is talking, what was said, which tools exist, what the agent is for. Building that picture is context assembly.
In OpenClaw it happens in this order, before any text streams:
The bar is what the model sees on its first call. Turn a piece off and read what the model gets wrong.
Illustrative sizes in thousands of tokens. The message is "move Friday's standup to 10 and tell the team."
Why build it once, up front? The tool list in the prompt and the tools the gateway will run must agree for the whole run. If the list changed between two model calls, the model could plan around a tool that is gone when it asks for it. One picture for the run keeps plan and action in step. OpenClaw prepares the settings once per session and refreshes them when the config, the workspace or the session changes.
Some requests are too big. OpenClaw's Codex runtime takes up to 1,048,576 characters per turn. A larger request is saved as a file the agent can read, or cut in the middle, and the transcript keeps the full text. How the pieces become the exact prompt is Lesson 5.
Chapter 4
Call the model, run the tool it asks for, call it again, and stop when it answers in text
This is the part that makes an agent an agent. The gateway calls the model. The model returns one of two things:
read_file with path a.txt." The gateway checks the arguments against the tool's schema, runs the tool, adds the result to the transcript, and calls the model again.The order is strict. The model never runs while a tool runs. The gateway adds each result before the next call, so each call sees the full history. The general pattern is in agents and tool use; here we follow the gateway's side of it.
How many model calls does a run make? Call a model reply that asks for tools a tool turn, and the number of them k. Call the number of model calls C.
C equals k plus one.
Each tool turn costs one model call, because the model must see the result. Add one call for the final text answer. That is C.
With made-up numbers: read three files and post one message, one tool per turn. k = 4, so C = 4 + 1 = 5 model calls. A reply with no tool has k = 0 and C = 1.
The model is in the middle, its tools around it. Press Step for one turn. Turn on Break the loop to see a gateway that calls the model once and stops.
Illustrative toy: one tool per turn. A real model can ask for several tools in one turn; that is still one tool turn.
How does the gateway know the model is done? The provider says so. On OpenAI Responses turns, a reply marked end_turn: false makes OpenClaw send another request. A messaging tool that sends the final reply to the current chat also ends the loop.
Now build the loop. The lab gives you a fake model that asks for two tools and then answers.
Chapter 5
Count identical calls in a row, warn the model early, and end the turn if it keeps going
Nothing in the loop forces the model to finish. A confused model can ask for the same tool, read the same result, and ask again. Each pass costs a model call and some money, and no answer comes.
Every agent harness needs a bound. Many use an iteration cap: at most N passes, then stop. The lab in Chapter 4 has one, MAXIT. OpenClaw bounds the loop in two ways. One is time (Chapter 7). The other is a repeat guard that watches for the same call again and again.
The repeat guard counts identical calls in a row: same tool, same arguments, back to back. It is on by default.
| Identical call in a row | What OpenClaw does | Log |
|---|---|---|
| 1st and 2nd | runs the call as normal | nothing |
| 3rd to 19th | runs the call, and adds a note to the result that names the tool and tells the model to change its approach | action=warn |
| 20th | does not run the call; ends the turn with the reason tool_repeat_limit | action=block |
A different call, or a new message from the user, sets the count back to zero.
Drag how many identical calls the stuck model would make. Turn the guard off, or let the model vary its call every so often.
The 3 and the 20 are OpenClaw's documented thresholds. The model's behaviour is a toy.
Why warn before you stop? Often the model is not broken. It missed a hint in the result. The note at call 3 gives it a chance to change course while the run is still cheap. The stop at call 20 is the seatbelt for when it does not.
detector=tool_repeat and count the calls in the streak.tools.loopDetection.enabled), and fix the tool result that the model keeps misreading.search with the same query 25 times in a row. With OpenClaw's repeat guard on, what happens?Chapter 6
Let plugins block or rewrite a tool call before it runs, and clean its result before it is saved
The loop has a fixed shape, but it is not closed. At named points, the gateway stops and asks registered functions whether they want to look or change something. Those points are hooks. Plugins register handlers on them with api.on(...).
Most hooks only observe: session_start, agent_end, after_tool_call. A few can change the run, and those carry the policy weight:
| Hook | When | What it can do |
|---|---|---|
before_tool_call | before a tool runs | block it (block: true, with a blockReason), rewrite its params, or ask a person to approve |
tool_result_persist | before a result is written to the transcript | replace the result by returning {message}; it must answer synchronously |
after_tool_call | after the tool ran | observe only; its return value is ignored |
message_sending | before a reply leaves | rewrite the text, or cancel the send |
Pick the call the model asks for. Turn each hook on or off and read what runs and what is saved.
Illustrative plugin: it blocks delete_all, adds limit 50 to search, and replaces the key sk-live-DEADBEEF with [REDACTED].
The order of handlers matters. In before_tool_call, block: true is final: lower-priority handlers are skipped. block: false means "no decision" and does not undo an earlier block. Trusted bundled policies run before ordinary plugins.
The model plans; the hooks approve. The model can ask for delete_all, but before_tool_call decides whether the ask becomes an act. That split lets you run a capable agent without a blank check. Tool policy and sandboxes are Lesson 10.
tool_result_persist, synchronously. An async handler's result is ignored, and after_tool_call cannot change anything.delete_all call and strip access tokens from results before they are saved. Which two hooks?Chapter 7
Tell a run that stopped from a caller that stopped waiting
A script calls agent.wait. After 30 seconds it gets status: "timeout" and logs "agent crashed." The agent did not crash. It is still reading files, and it finishes a minute later. The script stopped listening too early.
Keep two things apart: the run and the waiter (whoever waits on it). Three events end the run. One event ends only the wait:
| Event | What stops | OpenClaw detail |
|---|---|---|
| The model answers | the run, as a success | lifecycle end; agent.wait gives ok |
| Agent timeout | the model attempt | agents.defaults.timeoutSeconds, default 172,800 s (48 h) per attempt; a fallback model gets a fresh budget; 0 means no limit |
| Cancel (AbortSignal) | the whole run, fallback included | tool and approval rights end at once; bookkeeping still settles |
agent.wait timeout | only the waiter | default 30 s, set with timeoutMs; returns runId and status: "timeout"; the run goes on |
When does the waiter hear back? Call the run's length D. Call the wait window Tw. Call the time the waiter returns r.
r equals the smaller of D and T-w.
agent.wait returns, in seconds after the call.If the run ends first (D at most T-w), the waiter returns at D with status ok. If the window closes first, it returns at T-w with status timeout, and the run keeps going to D.
With made-up numbers: D = 75 s and T-w = 30 s. r = min(75, 30) = 30 s, status timeout. The run still ends at 75 s and saves its transcript. With D = 12 s, r = 12 s and the status is ok.
The top lane is the waiter, the bottom lane is the run. Drag the run's length and the wait window, then add a cancel.
Illustrative run lengths. The 30 s default and the rule that a wait timeout does not cancel the run are OpenClaw's.
Other early endings exist: a Gateway disconnect or an RPC timeout. A tool that times out is marked timeoutPhase: "tool_execution", and its outcome is unknown: it may have acted.
end event for the same run id.The lab encodes this rule: a cancel or an agent timeout stops the run; a wait timeout does not.
agent.wait call returns status: "timeout" after 30 seconds. What is true of the run?Chapter 8
Measure the time since the last sign of progress, and label a quiet run before you touch it
A run has shown nothing for three minutes. Is it thinking through a big model call, or is it dead? If you kill a busy run you throw away real work. If you wait on a dead one you waste the evening. You need a label before you act.
The signal is the progress gap: the time since the run last showed progress (a new token, a tool call starting or ending). Call the time now tnow, the time of the last progress tlast, and the gap g.
g equals t-now minus t-last.
Take the time now, t-now. Subtract the time of the last token or tool event, t-last. The result g is how long the run has been silent.
With made-up numbers: the last token came at 14:02:10 and it is now 14:05:40. g = 3 min 30 s = 210 s. That is past the 2 minute line, so the run gets a label.
With diagnostics on, OpenClaw labels quiet runs after a 2 minute gap. It also runs a watchdog, even with diagnostics off. Call the warning line θwarn and the watchdog's stall line θstall.
theta-stall equals the larger of 300 seconds and three times theta-warn.
Multiply the warning line theta-warn by 3. Compare it with 300 seconds. The bigger one is theta-stall.
With theta-warn = 120 s: 3 × 120 = 360, and max(300, 360) = 360 s, or 6 minutes. With a made-up theta-warn of 60 s: max(300, 180) = 300 s, the floor.
Drag how long the run has been quiet. The marks are the 2 minute warning line and the 6 minute stall line.
The 2 minute and 6 minute lines come from OpenClaw's docs. The exact switch from long-running to stalled depends on what the run waits for; this toy places it at the watchdog line.
| Label | What it means | What to do |
|---|---|---|
session.long_running | active work, quiet for a while, still inside its budget (a silent model call keeps this label until its abort threshold) | wait |
session.stalled | active work, no recent progress, past the abort threshold | look, then cancel if it is dead |
session.stuck | stale bookkeeping: an idle queued session with leftover activity that has no owner | recoverable; clear the leftover |
The labels only report. They do not cancel, retry or reset anything. Observing is kept apart from acting, so you can trust the label and decide yourself. Self-healing is Lesson 9.
session.long_running. What should you do?Chapter 9
Walk one run from receipt to saved transcript, and see where its time goes
Here is one run on one timeline. Where does its time go? Name the parts:
T-run equals T-ctx, plus the sum over i from 1 to k plus 1 of m-i, plus the sum over i from 1 to k of u-i, plus T-save.
Add the context time T-ctx. Add every model call m-i, one more than the tool turns. Add every tool turn u-i. Add the save time T-save. The model and the tools never overlap, so the times add.
With made-up numbers: T-ctx = 0.4 s and k = 2. The model calls take 1.2, 0.9 and 1.5 s (3.6 s). The tools take 0.3 and 2.0 s (2.3 s), and T-save = 0.1 s. T-run = 0.4 + 3.6 + 2.3 + 0.1 = 6.4 s. The model takes more than half.
Drag the playhead through the run. Choose how many tool turns it makes, and add an agent.wait caller with a short window.
Made-up times from the worked example. The 3 s window is shortened from OpenClaw's 30 s default so it lands inside a short run.
Read the timeline from left to right. The receipt comes first and costs nothing (Chapter 1). The writer claim keeps the session in order (2). Context is gathered once (3).
Then the model and tools alternate, C = k + 1 model calls (4), under the repeat guard (5) and the hooks (6). Text streams while the last model call writes, and the save closes the run. A short wait times out partway, and the run carries on (7).
Chapter 10
Keep the terms, the numbers, a checklist and the core code in one place
A run is one ordered walk: receipt, writer claim, context, model and tools until text, stream, save. A guard stops repeats. Hooks decide what runs and what is saved. Timeouts and cancels stop the run; a wait timeout stops only the waiter.
| Term | Meaning | OpenClaw value |
|---|---|---|
| run | one execution of the agent on one message | started by the agent RPC or openclaw agent |
| receipt | what intake returns at once | runId, acceptedAt |
| wait | block for a run's status | agent.wait: {status, startedAt, endedAt, error?}, default 30 s |
| events | what a watching caller receives | tool, assistant, lifecycle (start, finishing, end, error) |
| writer fence | one writer per session | activeWriterRunId checked against expectedWriterRunId |
| prompt limit | largest request per turn | 1,048,576 characters (Codex runtime) |
| repeat guard | stops identical calls in a row | note at the 3rd, stop at the 20th (tool_repeat_limit) |
| agent timeout | limit on one model attempt | agents.defaults.timeoutSeconds = 172,800 s (48 h) |
| model idle timeout | a model call that sends nothing | 120 s cloud, 300 s self-hosted |
| health lines | when quiet runs get labels | 2 min diagnostics; watchdog stall at max(5 min, 3 × warning) |
A toy loop with the writer fence, the repeat guard and the two hooks. It is a sketch for reading, not OpenClaw's code.
pythondef run_agent(session, message, model, tools, hooks, run_id): session.claim_writer(run_id) # one writer per session ctx = assemble(session, message) # gathered once, fixed for the run last, streak = None, 0 while True: step = model(ctx) # text or a tool call if step.kind == "text": session.append(run_id, ("assistant", step.text)) return "ok" key = (step.name, repr(step.params)) streak = streak + 1 if key == last else 1; last = key if streak >= 20: return "tool_repeat_limit" # repeat guard: stop d = hooks.before_tool_call(step) or {} if d.get("block"): result = "blocked: " + d["blockReason"] else: result = tools[step.name](d.get("params", step.params)) if streak >= 3: result += " [note: change your approach]" saved = hooks.tool_result_persist(result) # clean before saving session.append(run_id, ("tool_result", saved)) # checks run_id is the writer ctx.append(saved) # the next call sees it
Now press Present or Teach and explain it from memory. Cover the six stages, receipt against wait, one writer per session and C = k + 1. Then cover the repeat guard, the two hooks that change a run, and why a wait timeout leaves the run alive. Then go back to the hero and make the model repeat itself.