AI & Machine Learning

A Step Cap Does Not Stop a Looping Agent. It Sets the Price

Three loop shapes, repeat, oscillate and drift, and the defences that catch each one: hierarchical budgets, call and result fingerprints, state hashes, a wind-down paid from a reserve, and an external kill switch. Tested with scripted models.

Khalid Aboubakr
17 min read
Ai EngineeringLlmReliabilityProduction
AI Engineering Masterclass, part 8 of 50: agent loops that never end, beside a diagram of three loop shapes, repeat, oscillate and drift, on step timelines

Set max_steps=50 on an agent and the problem looks solved: nothing can run forever. Then a run gets stuck searching for a document that does not exist, and it stops exactly where it was told to, fifty model calls later, each call re-reading everything the previous ones wrote. The cap worked. The bill for that run is the bill for fifty steps of the longest transcript the system has ever produced, and the user receives nothing.

That is the uncomfortable property of the usual fix for an AI agent infinite loop: a step cap bounds the damage without noticing the loop. Noticing takes a different kind of signal, and the difficulty is that the guard has no idea what the task is. It can only see calls, results and, if you let it, the state the agent is changing. This article builds loop defences from those three observables: about 240 lines of Python covering layered budgets, detection of three loop shapes, a wind-down that still produces something useful, and a kill switch that the run itself cannot influence.

Three shapes of an AI agent infinite loop

Loops in agents are not all the same failure, and a detector built for one shape is blind to the others.

Repeat. The model issues the same call and gets the same result, again and again. A search returns a page that does not answer the question, and the model searches again with identical arguments. The stall check in the agent loop built in the first article of this series catches it by counting identical calls.

Oscillate. Two or more steps undo each other. The agent sets a timeout to 60 because a test is slow, then back to 30 because another test now fails, then to 60 again. No call repeats consecutively, so a "same call three times in a row" rule never fires, and each step looks like a reasonable reaction to the last observation.

Drift. Every call is different and none of them teaches the agent anything. The query becomes "refund policy 2021", then "refund policy 2022", then 2023. Each call has a fingerprint that has never been seen, each result is a string that has never been seen, because the tool politely echoes the query back in its "no results" message. By any test based on exact equality, this run is making steady progress.

Three timelines of agent steps for the repeat, oscillate and drift loops, each marked where the run is nudged and then wound downFigure 1. Three loop shapes. Each needs its own signal, and none of the signals requires knowing what the task is.

Anthropic's guidance on agents recommends stopping conditions such as a maximum number of iterations, and describes agents as depending on ground truth from the environment at each step. The cap is the backstop; the ground truth is the detector's raw material: a loop is a run whose environment has stopped telling it anything new.

Why one number is the wrong budget

Before detection, the backstop has to be right, and a single step counter is not. Steps measure how many times the model was called. They do not measure what was spent, because the cost of step n includes re-reading the transcript of steps 1 to n−1. Google's SRE book makes the same point about server capacity: counting requests is a poor proxy when requests differ in cost, and the limit should be expressed in the resource actually consumed. For an agent that resource is tokens, then money, then wall-clock time, and agent budget limits should exist in each.

It should also be bounded at more than one level. A run that spawns sub-agents, or a tenant that starts two hundred runs, can exhaust a shared allowance while every individual run stays inside its own limit.

@dataclass class Budget: """One level of a hierarchy. A charge is applied to this level and to every ancestor.""" name: str limits: dict[str, float] # any of "steps", "tokens", "cost", "seconds" parent: Budget | None = None spent: dict[str, float] = field(default_factory=dict) def charge(self, **amounts: float) -> None: node: Budget | None = self while node is not None: for dimension, amount in amounts.items(): node.spent[dimension] = node.spent.get(dimension, 0) + amount node = node.parent def exhausted(self, reserve: dict[str, float] | None = None) -> str | None: """The first limit reached at any level, e.g. "run.tokens" or "tenant.cost". `reserve` is held back from this level only: it is what a wind-down is allowed to spend. """ node: Budget | None = self while node is not None: for dimension, limit in node.limits.items(): held_back = (reserve or {}).get(dimension, 0) if node is self else 0 if node.spent.get(dimension, 0) >= limit - held_back: return f"{node.name}.{dimension}" node = node.parent return None

A charge propagates to every ancestor, so a sub-agent spends its parent's tokens and its tenant's money as it spends its own. exhausted walks the same chain and returns the name of the first limit reached, such as run.tokens or tenant.cost. That string becomes the termination reason, and "this run was too long" calls for a different response than "this tenant is out of budget".

The reserve parameter is the part that is easy to misread. It is subtracted from the limits of the level being asked and from no other. A run with a 5,000-token limit and a 1,000-token reserve stops working at 4,000 and keeps 1,000 back for its last words. It does not get to hold back part of its tenant's budget: when the tenant is exhausted, the run stops with nothing in hand, which is the correct behaviour when one customer's loops are consuming an allowance. The SRE book states the same aim for per-customer limits: under overload, only the misbehaving customer should see errors.

Two limits of this implementation are deliberate. A charge is recorded after the model call, because that is when the usage is known, so a limit can be overshot by at most one call; the check before each call is what keeps it to one. And the tree lives in process memory. A tenant-level budget shared by many workers needs an atomic counter in a shared store, with a reservation before the call and a settlement after it. That is not built here.

Detecting no progress without knowing the task

The detector sees three things per tool call: what was asked, what came back, and whether the call was a read or a write. From those it builds two fingerprints.

def call_fingerprint(call: ToolCall) -> str: return call.name + ":" + json.dumps(call.arguments, sort_keys=True, ensure_ascii=False) def result_fingerprint(call: ToolCall, text: str) -> str: """Digest of a result with the call's own argument values masked out. Tools echo their input ("No results for 'refund policy 2021'"), which makes every result of a drifting loop look new. Masking the echo makes them identical again. """ for value in sorted((str(v) for v in call.arguments.values() if isinstance(v, (str, int, float))), key=len, reverse=True): if len(value) >= 2: text = text.replace(value, "§") return digest(call.name + "\x1f" + text) def tail_period(history: list[str], max_period: int = 4, cycles: int = 3) -> int | None: """Smallest p for which the last p*cycles entries are `cycles` copies of one block of length p. p == 1 is plain repetition (A A A); p >= 2 is oscillation (A B A B A B). """ for period in range(1, max_period + 1): span = period * cycles if len(history) >= span: tail = history[-span:] if all(tail[i] == tail[i % period] for i in range(span)): return period return None

call_fingerprint is the tool name with canonically serialised arguments, the same idea as in the first article. On its own it produces a false positive that matters in practice: an agent that polls. Calling run_tests() five times with no arguments is a loop only if the result stays the same. So the history entry is the call fingerprint joined to the result fingerprint, and repetition means the pair recurred.

result_fingerprint is where drift is handled. Before hashing, every argument value of at least two characters is replaced in the result text by a placeholder. "No results for 'refund policy 2021'" and "No results for 'refund policy 2022'" then hash to the same value, because the only thing that distinguished them was the agent's own input reflected back. This is a heuristic with known edges. A result that embeds a timestamp or a request ID will look new on every call; such tools need their results normalised before they reach the detector.

tail_period finds the smallest block length p such that the end of the history is that block three times over. A period of 1 is repetition; 2 to 4 is oscillation. It looks only at the tail, so a pattern that was tried early and abandoned does not count against the run, and it requires three full cycles before it convicts.

@dataclass class Progress: """Detects a run that is busy but going nowhere, without knowing what the task is.""" max_period: int = 4 cycles: int = 3 patience: int = 4 # consecutive steps that produced nothing new history: list[str] = field(default_factory=list) seen_results: set[str] = field(default_factory=set) seen_states: set[str] = field(default_factory=set) stale: int = 0 def observe(self, call: ToolCall, text: str, mutates: bool, state: str | None) -> None: result = result_fingerprint(call, text) self.history.append(call_fingerprint(call) + "=>" + result) if mutates and state is not None: # a write is progress only if it reaches a state not seen before fresh = state not in self.seen_states else: # a read is progress only if it returned something not seen before fresh = result not in self.seen_results self.seen_results.add(result) if state is not None: self.seen_states.add(state) self.stale = 0 if fresh else self.stale + 1 def verdict(self) -> str | None: period = tail_period(self.history, self.max_period, self.cycles) if period == 1: return "repeat" if period is not None: return f"oscillation:{period}" return "no_progress" if self.stale >= self.patience else None

Progress combines the periodic check with a staleness counter, and the definition of "fresh" is different for reads and writes. A read is fresh if its masked result has not been seen before in this run. A write is fresh only if the state it leaves behind has not been seen before, whatever the tool printed. That distinction closes a hole that result hashing cannot: a write tool that returns "written at tick 14" produces a new result every time while moving the system between the same two states.

The state comes from state_fn, a function the caller supplies that returns a string identifying what the task is working on: a hash of the working-tree diff, a record's version number, the serialised form of a draft. The guard only compares it. Where no such function exists, writes fall back to being judged like reads, and the periodic check and the budgets carry the load.

What the detector will get wrong

It is a heuristic, and both kinds of error are possible. An agent that pages through a large result set and finds nothing useful sees a new result on every call and is never flagged; only the budget stops it. An agent that legitimately tries five queries in a row against an empty index is flagged as drifting after patience stale steps although it was doing what a careful person would do. The second error is why the first verdict does not end the run.

One warning, then a wind-down

Here is the loop with all the defences in place, small enough that every exit can be driven from a test.

def run(model: Model, tools: dict[str, Tool], task: str, budget: Budget, prices: Prices, *, reserve: dict[str, float] | None = None, progress: Progress | None = None, kill: KillSwitch | None = None, run_id: str = "run-1", tenant: str = "tenant-1", state_fn: Callable[[], str] | None = None, clock: Callable[[], float] = time.monotonic) -> Outcome: progress, kill = progress or Progress(), kill or KillSwitch() transcript: list[dict] = [{"role": "user", "content": task}] last_tick, nudged = clock(), False def call_model(offered: list[str]) -> ModelTurn: nonlocal last_tick turn = model.complete(transcript, offered) now = clock() budget.charge(steps=1, tokens=turn.input_tokens + turn.output_tokens, cost=prices.cost(turn), seconds=now - last_tick) last_tick = now calls = turn.tool_calls if offered else () # with nothing on offer, a tool call is not honoured transcript.append({"role": "assistant", "content": turn.text, "tool_calls": [vars(c) for c in calls]}) return turn def done(status: str, reason: str, answer: str = "") -> Outcome: spent = budget.spent return Outcome(status, reason, answer, int(spent.get("steps", 0)), int(spent.get("tokens", 0)), spent.get("cost", 0.0), transcript) def wind_down(reason: str) -> Outcome: """One last model call, with no tools on offer, paid for out of the reserve.""" if (killed := kill.tripped(run_id, tenant)) is not None: # a stop that arrived during this step's tools return done("stopped", killed) if budget.exhausted() is not None: # nothing was held back: there is no budget left to say goodbye with return done("stopped", reason) transcript.append({"role": "user", "content": WIND_DOWN.format(reason=reason)}) return done("wound_down", reason, call_model([]).text) while True: if (reason := kill.tripped(run_id, tenant)) is not None: return done("stopped", reason) if (reason := budget.exhausted(reserve)) is not None: return wind_down("budget:" + reason) turn = call_model(sorted(tools)) if turn.stop != "tool_calls": return done("completed" if turn.stop == "final" else "stopped", turn.stop, turn.text) observations = [] for call in turn.tool_calls: if kill.tripped(run_id, tenant) is not None: # checked before EVERY side effect, not once per turn observations.append({"tool_call_id": call.id, "content": "Not executed: the run was stopped.", "is_error": True}) continue tool = tools.get(call.name) try: text, failed = (str(tool.fn(**call.arguments)), False) if tool else (f"Unknown tool '{call.name}'.", True) except Exception as exc: text, failed = f"{type(exc).__name__}: {exc}", True observations.append({"tool_call_id": call.id, "content": text, "is_error": failed}) progress.observe(call, text, bool(tool and tool.mutates), state_fn() if state_fn else None) transcript.append({"role": "tool", "content": observations}) if (reason := progress.verdict()) is not None: if nudged: # it was told once and did the same thing again return wind_down(reason) nudged = True transcript.append({"role": "user", "content": NUDGE.format(reason=reason)})

Read the top of the while body first. The kill switch is checked before the budget, and both before the model is called. A stopped run must not spend a wind-down call, and an exhausted run must not start a step it cannot pay for.

When progress.verdict() first returns a reason, the loop does not stop. It appends a user message saying that recent calls are producing nothing new and that the model should try something else or answer with what it has. In the test suite a scripted model that heeds the warning completes normally at step four. For a run that is truly stuck the warning costs one extra step, which is cheap insurance against the false positives described above. The nudged flag is never reset: a run that needed one warning and then loops again, in any shape, has used its allowance.

The second verdict, or a budget limit minus its reserve, leads to wind_down. A run that cannot finish should still report what it established, so the model is called once more with an instruction to summarise and with no tools on offer, and the call is paid for from the reserve. Three details keep this honest:

  • If nothing was reserved, the hard limit has already been reached and there is no wind-down. The run ends as stopped. A graceful exit that overdraws the budget is not graceful.
  • If the model answers the wind-down prompt with a tool call anyway, call_model drops it. The transcript records an assistant turn with no tool calls, so every recorded call still has exactly one observation.
  • The wind-down call is the most expensive call of the run, since it reads the whole transcript. A token reserve sized for an average step will be too small at exactly the moment it is needed.

Flow diagram of one guarded step: kill-switch check, budget check, model call and tools, no-progress verdict, then a nudge, a wind-down or a hard stopFigure 2. One guarded step. Only two paths end without a final model call: the kill switch, and a budget with no reserve.

Agent termination therefore has three statuses, completed, wound_down and stopped, each with a reason. A wound_down answer is partial by construction and should be labelled as such wherever it is shown. A model turn that was cut off or refused ends the run as stopped with that reason; it is never reported as an answer.

Withholding tools on a real API

"No tools on offer" needs care against a real provider, because by the time a run winds down its history is full of tool-call blocks. The adapter below, for the Anthropic Messages API, keeps the full tool declarations in the request and forbids their use with tool_choice:

class AnthropicModel: def __init__(self, definitions: list[dict], client: anthropic.Anthropic | None = None, model: str | None = None, max_tokens: int = 1024): self.definitions = definitions # name, description, input_schema for every tool self.client = client or anthropic.Anthropic() self.model = model or os.environ["AGENT_MODEL"] # a model ID is configuration, never a literal self.max_tokens = max_tokens def complete(self, transcript: list[dict], tools: list[str]) -> ModelTurn: offered = [d for d in self.definitions if d["name"] in tools] if offered: choice = {"type": "auto"} else: # wind-down: the history still contains tool blocks, offered, choice = self.definitions, {"type": "none"} # so keep the declarations and forbid the calls response = self.client.messages.create(model=self.model, max_tokens=self.max_tokens, messages=to_messages(transcript), tools=offered, tool_choice=choice) text = "".join(b.text for b in response.content if b.type == "text") calls = tuple(ToolCall(b.id, b.name, dict(b.input)) for b in response.content if b.type == "tool_use") return ModelTurn(STOP.get(response.stop_reason or "", "truncated"), text, calls, response.usage.input_tokens, response.usage.output_tokens)

The documentation describes {"type": "none"} as preventing the model from using any tools, and version 2.8.0 of the SDK types it as one of four tool_choice variants. Keeping the declarations identical to earlier requests is the conservative choice, since the history refers to those tools. The same page notes a cost: with prompt caching enabled, a change to tool_choice invalidates the cached message blocks, so the wind-down call re-reads the transcript uncached. That is one more reason to size the reserve for the largest call of the run. The same adapter folds the nudge or wind-down text into the user message that carries the tool results, after the tool_result blocks, so that roles alternate strictly. A test asserts all of this against the request bodies the SDK actually sends through a mock transport. Whether a live model always obeys the instruction was not tested, which is why the loop also discards any tool call made in that turn.

A kill switch the run cannot argue with

Budgets and detectors are judgements made inside the run. A kill switch is a decision made outside it, by an operator or an alert, and the loop's only relationship to it is to read it.

@dataclass class KillSwitch: """Set from outside the run (an operator, an alert). The loop only ever reads it.""" everything: bool = False tenants: set[str] = field(default_factory=set) runs: set[str] = field(default_factory=set) def tripped(self, run_id: str, tenant: str) -> str | None: if self.everything: return "kill:global" if tenant in self.tenants: return "kill:tenant" return "kill:run" if run_id in self.runs else None

It has three scopes because incidents have three sizes: one run, one tenant, everything. The loop consults it before each model call and, more importantly, before each tool call within a turn. A model may request several tools at once, and "stop" should mean that the next side effect does not happen. Calls that are skipped receive an observation saying they were not executed, so the transcript remains well-formed for whoever investigates.

A killed run gets no wind-down, and wind_down reads the switch again before it does anything, so a stop that lands during the tools of the very step that convicts the run still ends it without another model call. The reason for pulling the switch may be the model, the provider or a compromised conversation, and in each case one more model call is the wrong thing to do. For the same reason the switch must not be a tool, a prompt instruction or anything else the model can see: like the permission layer from the previous article, it has to be enforced by code the model cannot talk to.

In a real deployment the flags live in a shared store that every worker reads, and two decisions follow. One is how stale a cached read may be, which sets how long a "stopped" agent keeps acting. The other is what to do when the store is unreachable. Failing closed stops every agent during an outage of the flag store; failing open means the switch is absent during exactly the kind of incident it exists for. Neither is free, and the choice should be made deliberately per tool class, in the spirit of circuit breakers in a distributed system.

What the switch cannot do is interrupt a call already in flight. A tool that hangs holds the run until its own timeout fires, and a side effect that was already sent is sent. That is one more reason for writes to carry idempotency keys, as the tool execution layer in this series does: after an emergency stop, someone has to work out what was and was not done.

What the simulation shows

Each loop shape is scripted as a model that never finishes on its own, and run twice: once with a 50-step cap and nothing else, once with the layered defences.

SHAPES = { "repeat": lambda i: ("search", {"query": "refund policy"}), "oscillate": lambda i: ("set_config", {"value": "timeout=30" if i % 2 else "timeout=60"}), "drift": lambda i: ("search", {"query": f"refund policy {2000 + i}"}), } def simulate(shape: str, layered: bool, max_steps: int = 50) -> dict: workspace, model = Workspace(), Shape(SHAPES[shape]) budget = Budget("run", {"steps": max_steps}) never = Progress(max_period=0, patience=10**9) # detection switched off: the step cap is all there is outcome = run(model, workspace.tools(), "Find the refund policy.", budget, PRICES, reserve={"steps": 1} if layered else None, progress=Progress() if layered else never, state_fn=lambda: workspace.config) return {"shape": shape, "defence": "layered" if layered else f"step cap {max_steps}", "status": outcome.status, "reason": outcome.reason, "model_calls": outcome.steps, "tokens": outcome.tokens, "cost_units": round(outcome.cost, 4)}

Token counts here are simulated, not measured: each model call is charged the size of the transcript it receives, at four characters per token, plus a fixed 60 output tokens. They show how the cost of a loop scales, not what any real run costs.

Loop shapeStep cap 50 onlyLayered defencesStopped by
Repeat50 calls, 360,575 tokens5 calls, 3,423 tokensrepeat
Oscillate50 calls, 78,200 tokens8 calls, 2,432 tokensoscillation:2
Drift50 calls, 82,798 tokens7 calls, 2,012 tokensno_progress

In this scripted simulation the step cap alone spent between 32 and 105 times the tokens of the layered run. The repeat loop is the most expensive of the three because its tool returns a full page each time, and every later call re-reads all of those pages.

Bar chart from the simulation: tokens spent per loop shape under a 50-step cap alone and under layered detection, and for drift under caps of 25, 50 and 100Figure 3. Simulated tokens until each run stopped. Doubling the step cap roughly quadruples the cost of a loop.

The lower half of the figure is the argument against tuning the cap. Under a step cap alone, the drift loop spent 21,176 simulated tokens at 25 steps, 82,798 at 50 and 327,448 at 100: each doubling multiplied the cost by about 3.9. The reason is arithmetic. If every step adds roughly the same amount to the transcript and every call re-reads the transcript, the total is the sum of 1 to n, which grows with the square of n. Raising a cap from 25 to 100 "to give hard tasks more room" raises the price of every stuck run about sixteenfold. Provider-side prompt caching can change the price of re-read tokens, not their number, and it was not modelled.

Tests, and what was verified

Every exit is a unit test against a scripted model. Two are worth reading because they test properties that are easy to assume and hard to notice when they break. The first is an oscillation that no fingerprint can see:

def test_a_write_that_returns_to_an_earlier_state_is_not_progress_whatever_it_prints(): state, tick = {"value": "a"}, [0] def write(value, note): tick[0] += 1 state["value"] = value return f"written at tick {tick[0]}" # a different result every time turns = [call("write", value="ab"[i % 2], note=f"attempt {i}") for i in range(20)] outcome = run(Scripted(turns + [FINAL]), {"write": Tool(write, mutates=True)}, "t", Budget("run", {"steps": 50}), PRICES, reserve={"steps": 1}, state_fn=lambda: state["value"]) assert (outcome.status, outcome.reason, outcome.steps) == ("wound_down", "no_progress", 8)

The write tool returns a different string on every call and receives a different note argument on every call, so neither fingerprint ever repeats and tail_period finds nothing. Only the state hash sees that the system is alternating between two values, and the run is wound down after eight model calls. The second is a stop that arrives in the middle of a turn:

def test_a_kill_between_two_tool_calls_stops_the_second_side_effect_and_spends_nothing_more(): switch, sent = KillSwitch(), [] def send_email(to): sent.append(to) switch.runs.add("run-1") # an operator pulls the switch while this call runs return "sent" both = ModelTurn("tool_calls", tool_calls=(ToolCall("a", "send_email", {"to": "x@example.com"}), ToolCall("b", "send_email", {"to": "y@example.com"}))) model = Scripted([both, FINAL]) outcome = run(model, {"send_email": Tool(send_email, mutates=True)}, "t", Budget("run", {"steps": 5}), PRICES, kill=switch) assert sent == ["x@example.com"] and (outcome.status, outcome.reason, outcome.steps) == ("stopped", "kill:run", 1) assert outcome.transcript[-1]["content"][1]["content"] == "Not executed: the run was stopped." and paired(outcome)

The operator's stop lands while the first of two emails is being sent. The assertion is on the side effect: one email, not two, and no further model call.

Verification. All 33 tests pass on Python 3.13.18 with pytest 9.2.0 and anthropic 2.8.0 (November 2026); simulate.py produced the figures in the table and make_chart.py generated Figure 3 from the same functions. One test drives the real Anthropic SDK through a local httpx2 mock transport with no network and no API key. No live model was called: the loops are scripted, the token counts are simulated at four characters per token, and nothing here measures how often any real model loops or whether it heeds a warning. The OpenAI Agents SDK is described below from its documentation and was not installed or run. A shared, concurrent budget store and a distributed kill-switch store were not built.

What a framework's turn limit gives you

Agent frameworks ship the backstop. The OpenAI Agents SDK documentation describes a max_turns parameter on its runner, a MaxTurnsExceeded exception when it is passed, and an error_handlers option whose max_turns handler can return a fallback final output instead of raising. That is a step cap with a hook for a wind-down. The same SDK's guardrails are a different mechanism, checks on input, output and tool calls that halt a run when a tripwire fires: they decide whether content is acceptable, not whether a run is going anywhere.

So a framework's limit covers the last row of the table below and leaves the others to the application. OWASP's entry on unbounded consumption, LLM10 in the 2025 list, treats uncontrolled inference as a security risk in its own right and names "denial of wallet" among its examples; its mitigations include rate limiting, timeouts and graceful degradation. Loop defences are how those translate to agents.

DefenceCatchesMisses
Call and result fingerprint, period 1RepeatAnything that varies an argument
Tail period 2 to 4Short oscillationCycles longer than the window
Masked-result stalenessDrift with echoed argumentsUseless but distinct results
State hash on writesOscillation of any periodTasks with no state function
Layered budgetsEverything, lateNothing, but at full price

Common mistakes

Raising the cap when good runs hit it. The cap is the price of the worst run, and that price grows with its square. If legitimate tasks need eighty steps, the answer is detection plus a higher cap, not a higher cap.

Fingerprinting the call without the result. It flags polling as a loop and teaches the team to turn the detector off.

One budget per run and none above it. Two hundred well-behaved runs can do what one runaway cannot. In a product with several tenants on shared infrastructure, the tenant level is the one that protects everyone else.

Engineering verdict

Add all three layers to any agent that runs unattended or spends shared money: budgets in tokens, cost and time at run and tenant level; progress detection with one warning; a kill switch read before every side effect. The code is small and none of it depends on the model behaving.

Keep only budgets and the kill switch when the agent is short and interactive, with a person watching each step. A user who can see the agent repeating itself is a better detector than a hash.

Do not expect these defences to say why an agent loops. They report the shape and the step, and that is the starting point for the real fix, which is usually in a tool: a search that returns an unhelpful page instead of saying it found nothing, an error message that does not say what to change, a write that reports success without saying what state it left. Record the termination reason of every run as a metric: a rising share of no_progress exits on one tool is a bug report for that tool.

References

Related Articles

AI & Machine Learning14 min read

The Agent Loop Is Forty Lines. The Guards Around It Are the Engineering

A framework-free agent loop in Python, written as a state machine with five explicit exits: validated tool calls, errors returned as observations, step, token and time budgets, and stall detection, all tested with a scripted model and the real SDK.

AI & Machine Learning16 min read

Bounded Autonomy: A Permission Model for Agents That Touch Real Systems

A deterministic policy layer between a model and its tools: capabilities derived from the calling user and the task, allow, deny or ask decisions, argument constraints, one-call credentials and an audit record, tested against privilege-escalation attempts.