The Agent Loop

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.

Run one message

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

What Happens Between Message and Reply

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:

  1. Intake. The gateway checks the request, accepts it and hands back a run id.
  2. Context. It gathers what the model must see: the conversation, the workspace, the skills, the files.
  3. Model. It calls the model. The model answers in text or asks for a tool.
  4. Tools. It runs the tool, adds the result, and calls the model again. This is the loop.
  5. Stream. Text flows back to your chat app as the model writes it.
  6. Persist. The gateway writes everything that happened to the transcript.

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.

Many runs, 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.

The road

  1. Accepted is not finished: why intake returns a receipt, and the two ways to start a run.
  2. One writer per session: why two runs on one chat take turns.
  3. Gather the world once: what the model sees, and why it is fixed for the run.
  4. Infer, tool, infer: the loop in the hero, built in code.
  5. Stop a loop that will not stop: the repeat guard in the hero.
  6. Hooks: where plugins block, rewrite and clean a tool call.
  7. Three ways a run ends, one way a wait ends: timeouts and cancels.
  8. Busy or hung: labels that tell a slow run from a dead one.
  9. The whole run, scrubbed: every stage on one timeline.
  10. Field guide: terms, numbers, a checklist and the core code.
What is a run?

Chapter 1

Accepted Is Not Finished

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.

Receipt or result

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.

12 s

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:

CallWhat the caller getsUse it for
agentthe receipt, then tool, assistant and lifecycle events tagged with the run ida live chat screen
agent.wait{status, startedAt, endedAt, error?} for a run id, with status ok, error or timeouta 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."

You call agent and get back {runId, acceptedAt} at once. What does that mean?

Chapter 2

One Writer per Session

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.

Say it aloud

w-B equals the larger of zero and e-A minus a-B.

wB
w-B how long run B waits before it may write, in seconds.
max(0, …)
the larger of zero and a wait is never negative: if A is already done, B starts at once.
eA
e-A the time run A ends, on the same clock.
aB
a-B the time run B arrives for the same session.
In plain words

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 numbers

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.

Two runs, one transcript

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.

1 s

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.

Two messages reach the same session before the first run ends. What does one writer per session guarantee?

Chapter 3

Gather the World Once

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:

  1. Workspace. Find or create the run's working folder. A sandboxed run can use a sandbox folder.
  2. Skills. Load the skills, from a snapshot or fresh, and put them into the environment and the prompt.
  3. Bootstrap and context files. Put standing instructions and project notes into the system prompt.
  4. Writer claim. Prepare the transcript target and the writer claim from Chapter 2.

Pack the context

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.

Why does the run fix its skills and settings before the first model call?

Chapter 4

Infer, Tool, Infer

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:

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.

Say it aloud

C equals k plus one.

C
C the number of model calls in the run.
k
k the number of tool turns: model replies that ask for one or more tools.
1
one the last call, the one that answers in text.
In plain words

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 numbers

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.

Step the loop

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.

The model returns a tool call instead of text. What does the gateway do next?

Chapter 5

Stop a Loop That Will Not Stop

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 rowWhat OpenClaw doesLog
1st and 2ndruns the call as normalnothing
3rd to 19thruns the call, and adds a note to the result that names the tool and tells the model to change its approachaction=warn
20thdoes not run the call; ends the turn with the reason tool_repeat_limitaction=block

A different call, or a new message from the user, sets the count back to zero.

Ride the ruler

Drag how many identical calls the stuck model would make. Turn the guard off, or let the model vary its call every so often.

26

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.

A model calls search with the same query 25 times in a row. With OpenClaw's repeat guard on, what happens?

Chapter 6

Hooks: the Agent Proposes, the Gateway Decides

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:

HookWhenWhat it can do
before_tool_callbefore a tool runsblock it (block: true, with a blockReason), rewrite its params, or ask a person to approve
tool_result_persistbefore a result is written to the transcriptreplace the result by returning {message}; it must answer synchronously
after_tool_callafter the tool ranobserve only; its return value is ignored
message_sendingbefore a reply leavesrewrite the text, or cancel the send

Run the gauntlet

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.

A plugin must stop every delete_all call and strip access tokens from results before they are saved. Which two hooks?

Chapter 7

Three Ways a Run Ends, One Way a Wait Ends

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:

EventWhat stopsOpenClaw detail
The model answersthe run, as a successlifecycle end; agent.wait gives ok
Agent timeoutthe model attemptagents.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 includedtool and approval rights end at once; bookkeeping still settles
agent.wait timeoutonly the waiterdefault 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.

Say it aloud

r equals the smaller of D and T-w.

r
r when agent.wait returns, in seconds after the call.
min(…)
the smaller of whichever comes first: the run ends or the window closes.
D
D how long the run takes from start to end.
Tw
T-w the wait window, 30 s by default.
In plain words

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 numbers

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.

Who stopped?

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.

75 s
30 s

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.

The lab encodes this rule: a cancel or an agent timeout stops the run; a wait timeout does not.

Your agent.wait call returns status: "timeout" after 30 seconds. What is true of the run?

Chapter 8

Busy or Hung

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.

Say it aloud

g equals t-now minus t-last.

g
g the progress gap: how long the run has been quiet, in seconds.
tnow
t-now the current time on the gateway's clock.
tlast
t-last the time of the run's last sign of progress.
In plain words

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 numbers

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.

Say it aloud

theta-stall equals the larger of 300 seconds and three times theta-warn.

θstall
theta-stall the gap at which the watchdog calls a run stalled.
max(…)
the larger of take whichever of the two numbers is bigger.
300 s
300 seconds a floor of 5 minutes, so a short warning line never makes a hair trigger.
3
three times the stall line sits at least three warning lines out.
θwarn
theta-warn the warning line, 120 s with diagnostics on.
In plain words

Multiply the warning line theta-warn by 3. Compare it with 300 seconds. The bigger one is theta-stall.

With numbers

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.

Read the gap

Drag how long the run has been quiet. The marks are the 2 minute warning line and the 6 minute stall line.

3:30

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.

LabelWhat it meansWhat to do
session.long_runningactive work, quiet for a while, still inside its budget (a silent model call keeps this label until its abort threshold)wait
session.stalledactive work, no recent progress, past the abort thresholdlook, then cancel if it is dead
session.stuckstale bookkeeping: an idle queued session with leftover activity that has no ownerrecoverable; 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.

A run has been silent for 3 minutes on one long model call. Diagnostics label it session.long_running. What should you do?

Chapter 9

The Whole Run, Scrubbed

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:

Say it aloud

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.

Trun
T-run the run's total time, from receipt to saved transcript.
Tctx
T-ctx time to assemble the context (Chapter 3).
Σi=1..k+1
the sum over i from 1 to k plus 1 add one term for each of the C = k + 1 model calls.
mi
m-i the time of model call number i.
Σi=1..k
the sum over i from 1 to k add one term for each tool turn.
ui
u-i the time of tool turn number i.
Tsave
T-save time to write the last entries to the transcript.
In plain words

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 numbers

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.

Scrub one run

Drag the playhead through the run. Choose how many tool turns it makes, and add an agent.wait caller with a short window.

0.0 s

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

A run makes k = 3 tool turns. How many model calls does it make, and why do model and tool times simply add?

Chapter 10

Field Guide

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.

TermMeaningOpenClaw value
runone execution of the agent on one messagestarted by the agent RPC or openclaw agent
receiptwhat intake returns at oncerunId, acceptedAt
waitblock for a run's statusagent.wait: {status, startedAt, endedAt, error?}, default 30 s
eventswhat a watching caller receivestool, assistant, lifecycle (start, finishing, end, error)
writer fenceone writer per sessionactiveWriterRunId checked against expectedWriterRunId
prompt limitlargest request per turn1,048,576 characters (Codex runtime)
repeat guardstops identical calls in a rownote at the 3rd, stop at the 20th (tool_repeat_limit)
agent timeoutlimit on one model attemptagents.defaults.timeoutSeconds = 172,800 s (48 h)
model idle timeouta model call that sends nothing120 s cloud, 300 s self-hosted
health lineswhen quiet runs get labels2 min diagnostics; watchdog stall at max(5 min, 3 × warning)

Checklist for any agent loop

The core, in code

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

Where each thread continues

The takeaway. The model only proposes. The gateway runs the loop: it accepts, orders, gathers, calls, checks, bounds, saves, and tells a stopped run from a caller who stopped waiting.
In one sentence, what is the agent loop?

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.

Anatomy of an Agent Gateway, Lesson 4: The Agent Loop
OpenClaw docs · Next: context and streaming · Back to Gleams