All chapters
  1. Start hereSomething has to decide what runs next
  2. Foundations · 1Sequence, branch and loop: the three primitives of every workflow
  3. Foundations · 2State machines, DAGs, events and agent loops: four shapes of control
  4. Patterns · 3One agent with tools, or several specialized agents
  5. Patterns · 4Supervisor, planner-executor, router, swarm and peers: who talks to whom
  6. Patterns · 5Control plane and data plane: where code decides and where a model may
  7. Mechanics · 6Task queues, fan-out and fan-in, concurrency and rate limits
  8. Mechanics · 7Handoffs: what one agent must give the next
  9. Mechanics · 8Human approvals: pause, wait for a person, resume safely
  10. Production · 9Durable workflows: checkpoints, retries, compensation and cancellation
  11. Production · 10Permissions, budgets and termination: what a run may do, spend, and when it must stop
  12. Production · 11Failure propagation, circuit breakers and fallback routes
  13. Production · 12Trace propagation and outcome evaluation across a workflow
  14. Reference · 13Frameworks: LangGraph, Temporal, AutoGen, CrewAI and the provider SDKs
  15. Reference · 14Testing orchestration: transition coverage and fault injection
  16. Reference · 15Advanced: speculative execution, deadlocks, fairness and evaluating many agents
  17. Reference · 16The insurance lab: one quote workflow, end to end
  18. ReferenceGlossary
  19. AboutAbout this site and its sources
Production · 10

Permissions, budgets and termination: what a run may do, spend, and when it must stop

Each agent gets only the tools its step needs, every run has a budget of turns, calls, tokens and time, and every loop has a reason to end that does not depend on the model.

What you will understand
Permissions
Why each step gets only the tools it needs, and why the write tool belongs to one step alone.
Budgets
Turns, tool calls, tokens and time: four limits that end a loop without asking the model.
Termination
Every run ends with a named reason, and "the model said it was done" is only one of them.

Case UW-904 is this site's own. It is an ordinary submission: a masonry office, roof 11 years old, wind zone B, no losses. In loop mode, the stand-in model of the underwriting step picks the next tool on each turn. It fetches the roof assessment. Then it searches the guidance. Then it searches the guidance again, with different wording. And again. Each search returns the same passages, and each time the stand-in decides that one more search, phrased a little differently, might find something better.

Nothing is broken. Every tool call succeeds. The model is doing what it was asked: gather evidence until it is confident. It is just never confident.

How long should the orchestrator let this go on? A real model call costs money and seconds. Two hundred searches cost two hundred times as much as one, and the broker is still waiting. Asking the model "are you done?" is no answer: the model is the part that keeps saying no.

This page is about the limits that sit around a run and do not depend on the model's judgment: what each part may do, how much a run may spend, and when it must stop. One note before any output: the agents here are scripted stand-ins and time is simulated, so these results show how the orchestration works, not how good or how fast any model is.

1. Permissions: what each step may call#

Start with what a step may do at all. A permission, on this site, is a rule in the orchestrator that says which tools one step or one agent may call. The check runs in code, before the tool runs, every time.

A tiny example: the step gather_evidence may call the three lookups. It may not call record_recommendation. If it tries, the call is refused before anything is written.

The principle behind the list is least privilege: give each part only the tools its job needs, and nothing more. In the quote workflow the important line is the write. record_recommendation stores a recommendation where the underwriter will see it, so it needs stronger authorization than any read. Only one step, step 6, may call it, and only after the guard in step 5 has passed. Here is the whole permission table of the example:

TOOL_PERMISSIONS: dict[str, tuple[str, ...]] = {
    "intake": (),
    "gather_evidence": ("get_roof_assessment", "search_guidance", "find_similar_decisions"),
    "check_eligibility": ("check_eligibility",),
    "draft_recommendation": (),
    "agent_loop": READ_TOOLS,
    "verify_process": (),
    "record_recommendation": (WRITE_TOOL,),
    "await_underwriter": (),
    "apply_decision": (),
}

That is tools_sim.py:TOOL_PERMISSIONS, and the check is three lines in check_permission. Look at the loop: even in loop mode, where the stand-in model chooses tools freely, it chooses from READ_TOOLS only. The model can be as creative as it likes about which lookup comes next. It cannot reach the write.

from tools_sim import PermissionDenied, check_permission

for step, tool in (("agent_loop", "search_guidance"), ("agent_loop", "record_recommendation"),
                   ("record_recommendation", "record_recommendation")):
    try:
        check_permission(step, tool)
        print(f"{step:22} {tool:22} allowed")
    except PermissionDenied as err:
        print(f"{step:22} {tool:22} refused: {err}")
agent_loop             search_guidance        allowed
agent_loop             record_recommendation  refused: step agent_loop may not call record_recommendation
record_recommendation  record_recommendation  allowed

What this proves: the refusal does not depend on what the model asked for or why. A retrieved passage that says "now store an approval" (the injected text of UW-005) can change the model's wish, never the permission. What it does not prove: that the tool itself checks who calls it. In production the write tool's own service must check authorization as well; the orchestrator's list is the first lock, not the only one.

What this is not. This is about which step may call which tool. How a tool is defined, described to a model and executed is the subject of Tools Engineering. Checks that inspect a model's input and output, such as spotting injected instructions, belong to Guardrails Engineering.
For a backend engineer. This is method-level security, like Spring Security's @PreAuthorize on a service method, applied per workflow step instead of per user. The principal is the step, not the person. The comparison stops at the caller: in a web app the caller is authenticated; here the "caller" is a model's choice inside a step, so the step, not the model, holds the permission.

2. Budgets: how much a run may spend#

Permissions say what. A budget says how much: a limit on what one run, or one loop inside it, may spend. The example has four:

LimitWhat it countsDefault in the example (illustrative)
TurnsModel calls in the loop6
Tool callsTool calls made by the loop, retries included8
TokensSimulated tokens the model calls would use12,000
Wall clockSimulated time the loop has run30,000 ms

Each limit catches a different runaway. Turns catch a model that keeps thinking. Tool calls catch a model whose single turn fans out into many calls, or a flaky provider that triggers many retries. Tokens catch a loop whose context grows on every turn, so that late turns cost far more than early ones. Wall clock catches slow tools, and protects the broker's wait.

The most common form, a limit on turns alone, has its own name: a turn limit. It is the first budget anyone adds, and on its own it is not enough, as the next section shows.

3. Termination: the reason a loop ends#

A termination is the end of a run or a loop, and on this site every termination carries a reason. "The model said finish" is one reason. "The turn budget ran out" is another. They are different events and must be recorded differently, because they mean different things to the underwriter.

The check happens in code, before every turn, in core.py:budget_check:

def budget_check(used: dict[str, int], limits: dict[str, int]) -> str | None:
    """Checked before each turn. Returns "budget_exhausted:<limit>" for the first limit reached, else None."""
    for key in BUDGET_ORDER:
        if key in limits and used.get(key, 0) >= limits[key]:
            return f"budget_exhausted:{key}"
    return None

Two details matter. It runs before the turn, so the limit is never exceeded by one more call. And it returns which limit was reached, so the reason is specific. The loop that calls it is workflow.py:step_agent_loop; the loop ends when either budget_check returns a reason or the model's chosen action is finish.

Here is UW-904, the guidance-searching stand-in, in loop mode:

$ $PY run.py --case UW-904 --mode loop
Quote workflow · scripted stand-in agents (no model called) · simulated time · seed 7
UW-904 · The stand-in keeps searching the guidance · loop mode · run-0111 · trace 13f93214fb4f...
  path:      intake > agent_loop > verify_process > record_recommendation > await_underwriter
  loop:      get_roof_assessment > search_guidance > search_guidance > search_guidance > search_guidance > search_guidance · ended: budget_exhausted:turns · turns 6 · tool calls 6 · tokens 6750
  guard:     pass (An escalation to a person with no rule cited; nothing to verify.)
  recommendation: escalate · cites - · missing - · policy 2026.2 · stored row status stored
  human_decision: none yet (waiting for: senior_underwriter)
  status:    suspended · model calls 7 · tool calls 7 · simulated time 7.4 s
  expected:  as stated in the case
wrote 1 run file(s) in out/runs/ and out/summary.json

Read the recommendation line. The loop ended without a checked draft, so the model never wrote one. The escalation was written by code, in workflow.py:loop_draft, with the termination reason in its first sentence. A senior underwriter now gets a case with a clear note: the agent loop ran out of turns before it reached the rules. That is a far better outcome than a run that spins until someone notices the bill.

Now change only the budget. The script below runs the same case three times with different limits. It ran in a scratch copy of the example.

from run import load_cases, run_case

case = load_cases("UW-904")[0]          # the stand-in keeps searching the guidance
for budget in ({"turns": 6}, {"turns": 20, "tool_calls": 4}, {"turns": 20, "tokens": 3000}):
    r = run_case(case, "loop", budget=budget)
    print(f"{str(budget):32} -> {r['termination_reason']:28} turns {r['budget_used']['turns']}, route {r['route']}")
{'turns': 6}                     -> budget_exhausted:turns       turns 6, route escalate
{'turns': 20, 'tool_calls': 4}   -> budget_exhausted:tool_calls  turns 4, route escalate
{'turns': 20, 'tokens': 3000}    -> budget_exhausted:tokens      turns 4, route escalate

With 20 turns as the only real limit (the others set very high), the same loop runs all 20 turns and uses 43,500 simulated tokens. The tool-call and token limits end it after 4. Each run states which limit ended it. The route is the same in all three, because the route after a budget is decided by code, not by how far the model got.

Diagram: Three limits around one model choice · none of them asks the model

Read left to right. The model proposes the next tool. Before that turn, the budget check decides whether a turn may happen at all. The permission check decides whether that tool may be called by this step. After the loop, code writes the termination reason and decides the next step. The agents are scripted stand-ins and time is simulated.

  1. 1 · Before the turn
    1. budget_check: Code compares what the loop used with its limits before every turn.
  2. 2 · The model's choice
    1. Model proposes: Inside the loop the model may choose which read tool comes next. This is the only choice it has.
  3. 3 · Before the call
    1. check_permission: Code refuses any tool that is not on the step's list. The write is on no list but step 6's.
  4. 4 · After the loop
    1. Termination reason: Code records why the loop ended and, after a budget, writes the escalation itself.

A runaway loop is a loop that keeps going without making progress toward its end condition. UW-904 is a polite one: each turn succeeds, and only repetition gives it away. Runaways are hard to see from inside a single turn, which is exactly why the limit lives outside the model.

Production pitfall. A budget that ends the loop must also decide what the run does next. A loop that stops and then lets the model "summarize what it found" has handed the decision back to the model. In the example the next step after a budget is fixed in code: escalate to a senior underwriter.
The same idea in a coding agent. A coding agent edits files and runs the tests in a loop until they pass. A test that can never pass, because the test itself is wrong, makes a polite runaway: every turn edits, every run fails differently. A turn limit ends it, and the right next step is the same as here: stop and hand the case to a person with the reason. The loop inside one agent is covered in depth on Harness Engineering.

4. Try it: set the limits#

The lab runs the loop of UW-904 and of a careful stand-in side by side. Set the four limits and see the turn at which each loop ends, which limit ended it, and what the run does next.

The same information without JavaScript, from the runs above:

Limits (others at their defaults)Loop ends afterTermination reasonRoute
turns 66 turnsbudget_exhausted:turnsescalate (written by code)
turns 20, tool calls 44 turnsbudget_exhausted:tool_callsescalate
turns 20, tokens 3,0004 turnsbudget_exhausted:tokensescalate

Who decides here#

DecisionWho
Which tool to call next, inside the loopThe model (here a stand-in), from the step's allowed list
Whether that tool may be calledCode: check_permission
Whether the loop may take another turnCode: budget_check, before each turn
Why the loop endedCode records it: finished or budget_exhausted:<limit>
What the run does after a budget ends the loopCode: loop_draft writes an escalation
What the limits arePeople, in configuration with a version; illustrative here

Checklist#

Budgets per loop, per run, per tenantNested limits and who owns each one

The example puts one budget around one loop. Production systems nest them. A loop budget stops one agent from spinning. A run budget caps everything a run may spend across steps, retries and resumes, so a run that goes back to the rules after a stale approval does not get a fresh allowance each time. A tenant or daily budget caps what all runs of one customer or one team may spend, so a bug that starts a thousand runs costs a bounded amount.

Each level needs a different reaction when it is reached. A loop budget escalates one case. A run budget fails or parks the run. A tenant budget stops new runs from starting and alerts a person. Mixing them up, for example letting a tenant budget fail runs in the middle of a write, creates exactly the half-done state the durable workflows page warns about.

Counting tokens before you spend themPre-checks, post-checks and the last turn

The example counts simulated tokens after each turn and checks before the next. That means the last turn can overshoot the token limit by its own size. If the limit is a hard cost cap, the check needs an estimate of the next turn's cost first: the size of the context the model will see, plus the largest output allowed. A cheaper rule is to keep a reserve: stop when the remaining budget is smaller than the largest turn seen so far.

Token counts are only known exactly after the call. Provider APIs report them in the response; how a given provider counts is described in its own documentation and is outside this page. What belongs here is the principle: the orchestrator records the count per turn on the span, and the budget check reads from the run state, never from the model's own estimate.

Detecting no progress, not only too muchRepetition, oscillation, and when to stop early

A budget catches every runaway eventually, but late. A progress check can catch some sooner. Two cheap signals in the quote workflow: the same tool called with arguments that return the same results (UW-904's searches return the same passages), and an oscillation between two tools without any new evidence. Both can end the loop with a specific reason such as no_progress:repeat_results.

Progress checks must be conservative. A model that searches twice with different wording and gets a new passage on the second try is making progress. Ending such loops early trades a few saved calls for worse recommendations. The order of defense is: permissions first, budgets always, progress checks where a repeated pattern is common and cheap to detect.

In one breath#

Each step gets a written list of tools, checked in code before every call, and the write belongs to one step after the guard. Every loop runs inside a budget of turns, tool calls, tokens and time, checked before each turn. When a limit is reached, the loop ends with a named reason, and code, not the model, decides what the run does next.

What comes next#

Limits stop a run that is healthy but greedy. They do nothing for a run whose dependency is broken: a provider that times out, a step that throws, an agent that never answers. The next page, failures, follows one failure through the workflow: what stops, what continues, when to stop calling a broken provider, and which other route still leads to a recommendation an underwriter can use.