When an Agent Loop Should Stop: Five Layers of Termination Semantics
An agent run can stop at several different layers, and those stops do not mean the same thing. This article uses a typical “submit a code-change pull request” task to separate model-stream end, tool-batch completion, turn completion, driver idle, and long-term goal termination, then shows who should decide, how a recoverable loop can be structured, and which engineering mistakes cause token burn or silent exits.
1. The real problem has moved down a layer
Early discussions of agent frameworks often focus on how many lines the loop takes or how many tool protocols it supports. Once that runtime enters a real business workflow, the harder question sits one level lower: inside a single run, who presses stop, and on what evidence?
This is a semantic problem, not a syntax problem. The same word, “stop,” means different things at different layers. Closing an HTTP stream does not mean the task is finished. Every tool returning does not mean the turn is over. An agent returning to idle does not mean the goal was achieved. Mixing these events together is the root of most incidents in which an agent burns tokens in a loop or quietly exits halfway through a task.
Using a typical task such as submitting a pull request for a code change, this article spreads termination into five layers and explains the decision basis and common misjudgments at each one.
2. Five layers of termination
2.1 Model stream end: only this request received an end signal
The lowest “stop” is the end of the model response stream. It carries one fact: this request will not produce more content. The reason can fall into at least four categories:
- Normal completion: the model itself emitted a termination marker.
- Length truncation: the output token limit was hit, so the content was cut off and is semantically incomplete.
- Error interruption: upstream rate limiting, a timeout, or a server-side failure.
- Active cancellation: the caller or the user aborted the request.
The key conclusion is that stream end is a signal whose cause still has to be judged, not a termination decision. The finish reason must be retained and passed upward. Otherwise the layers above cannot tell “the model finished speaking” from “the model was cut off.” Treating truncation as a normal ending makes later steps decide on incomplete content.
2.2 Tool-batch end: tools stopping does not end the turn
In one round, the model may issue several tool calls in parallel. When that batch has all returned, only the tool-call phase is over. The model’s typical behavior is to look at the results and then decide the next step: call another tool, correct parameters, or wrap up.
The correct handling of a finished tool batch is therefore “hand the results back to the model,” not “exit the loop.” The most common faulty implementation treats a tool return as the loop exit, so the agent can only ever take one step.
Partial failure inside a parallel batch needs extra care. If one tool errors, times out, or is skipped, the batch as a whole is still finished, but the result set must explicitly carry the status of every call so the model can retry or choose another path.
2.3 A turn ends only when there is no pending next step
A turn is truly finished only when several conditions hold at once: every tool result has been returned to the model, this round has no pending model reply, and the next-step queue contains no new messages.
“New messages” commonly come from two sources, either of which can reopen a turn that was about to close:
- Steering inserted by the user mid-run: the user sees the direction drift and adds a constraint.
- Context injected by a tool or the environment: for example, new evidence from retrieval, or a status callback from an external system.
Turn termination must therefore be revocable and based on queue state, not a one-shot check of a Boolean flag. The more reliable implementation rechecks the pending queue before closing each turn, rather than deciding only at the loop entrance.
2.4 The driver activity ends: idle means there is temporarily nothing to do
The driver decides whether another turn should run. Only when it finds no turn waiting to execute does the agent enter idle.
The boundary of idle matters: idle means there is currently no executable action. It is a runtime state, not a business conclusion. Equating idle with task completion is one of the hardest defects to see. The monitoring dashboard looks healthy while the task has already stopped.
2.5 A long-term goal ends by persistent state, not runtime state
The outermost question is whether the long-term goal has ended. The criterion is whether persisted state has become one of complete, blocked, or paused. The three have different engineering meanings:
complete: the goal was achieved and should not be woken again.blocked: a precondition is missing, such as permission, a dependency, or human confirmation, and external input is required.paused: the work was deliberately suspended while waiting for timing or quota.
If the state is none of these three, the goal driver may still call the task back through a follow-up on the next inspection, even if the agent is idle now. That is why long-running tasks must store state in an external persistence layer rather than process memory. After a process restart or instance move, that stored state remains authoritative.
3. Who owns the decision
Read across the five layers, control is layered:
| Layer | End signal | Who decides | Cost of a misjudgment |
|---|---|---|---|
| Model stream | Stream end plus reason | Model-call layer | Truncated content treated as a conclusion |
| Tool batch | All calls returned | Tool-execution layer | Exit after a single step |
| Turn | Queue drained | Session scheduler | Steering discarded |
| Driver | No turn left to run | Runtime | Idle treated as completion |
| Goal | Persistent state ended | Goal driver | Task stays silent forever |
The rule is simple: lower layers report facts; only upper layers decide to stop. If a lower layer overreaches and terminates on its own, the system loses recoverability.
4. A decidable, recoverable loop skeleton
The sketch below expresses control flow only. It is not tied to any specific product interface:
def run(goal_id):while True:goal = store.load(goal_id)if goal.status in ("complete", "blocked", "paused"):return goal.statusturn = {"pending": deque(), "next_step": deque()}while True:# 1. Model stream: the finish reason must be judgedstream = model.call(goal.context, turn["pending"])for chunk in stream:turn["pending"].append(chunk)if stream.finish_reason == "length":goal.context.truncate_and_mark() # do not close silentlyelif stream.finish_reason in ("error", "cancelled"):return retry_or_fail(stream.finish_reason)# 2. Tool batch: return results to the model instead of exitingcalls = collect_tool_calls(turn["pending"])if calls:turn["pending"].extend(tool_batch(calls))continue# 3. Recheck steering and injected context before closing the turnif turn["next_step"]:turn["pending"].extend(turn["next_step"])turn["next_step"].clear()continueif not turn["pending"]:break# 4. No turn left for the driver means idle, not necessarily a finished goaldriver.mark_idle()store.save(goal) # 5. Persist state for the goal driver's inspectionreturn "idle"
Three design points follow from this skeleton: finish reasons must be branched explicitly; tool results must flow back into the model; and the queue must be rechecked before a turn closes.
5. Engineering constraints
- Budget before round count: replace a crude “at most N rounds” cap with three budgets—tokens, tool-call count, and wall-clock time. When a budget is exceeded, mark the state
paused, notcomplete. - Idempotency and replay: every step needs a stable identifier so recovery does not repeat side effects such as submitting again or writing the database again.
- Observability: report the finish reason at each of the five layers as a structured event, and pair those events with logging and monitoring alerts. That is what distinguishes normal convergence, truncation, cancellation, and suspension. Recording only “the loop exited” has almost no diagnostic value.
- Externalized state: keep long-running task state in a persistence layer and keep the runtime stateless. The workload can then run safely on a container platform and tolerate instance rebuilds.
6. Common anti-patterns
- Using stream end as the loop exit, so the agent can execute only one step.
- Treating truncation as a normal ending, so later steps decide on incomplete content.
- Recording completion with an in-memory Boolean, so a process restart loses the task permanently.
- Not rechecking steering at close, so constraints the user added are dropped.
- Mapping idle directly to task success, so monitoring looks healthy while the business work has stopped.
7. Closing
There is no single answer to “when should it stop,” only a layered one. Split termination into the model stream, the tool batch, the turn, the driver, and the long-term goal. Let each layer report facts, let the layer above decide, and persist the final state outside the process. The agent runtime can then both converge and recover. When long-running tasks of this kind are deployed on a platform such as Baidu AI Cloud, ordinary logging, monitoring, and container capabilities turn “did it stop for the right reason?” into an observable, traceable engineering signal instead of a guess made by searching logs.
