Skip to main content

The agentic loop

A basic chat completion is strictly reactive: it accepts an input prompt, generates a continuation, and immediately terminates. In that single interaction, the model cannot run a build, inspect a filesystem, or verify whether its code compiles.

Transforming an LLM into an autonomous coding assistant requires an orchestration layer: a program that interprets model output, executes requested commands (such as running a test suite or writing a file), feeds the execution output back to the model, and repeats the cycle until the objective is satisfied. That orchestration program is the . The majority of what practitioners describe as an "AI agent" actually resides within the logic of this harness.

Consider a practical development workflow. You prompt the system: "The parser test is failing, fix it." The harness packages your request alongside its internal system prompt, project-level instructions, and the current workspace configuration. The model evaluates the prompt and requests a shell command to execute the test suite. The harness executes the command and feeds forty lines of pytest failure traces back to the model. Analyzing the stack trace, the model issues two tool calls requesting parser.py and parser_test.py. The harness reads both files and returns nine hundred lines of code. The model then proposes modifying three lines in parser.py. Recognizing a state-modifying action, the harness pauses execution and prompts you for confirmation. Upon your approval, the edit is applied. The model requests one final test run, observes that the suite passes, and returns a concise completion summary with no further tool calls. What felt like a single command involved five model round-trips, four tool executions, and an interactive confirmation checkpoint—all triggered by seven words of user input.

The execution loop

Each iteration through this cycle constitutes a : a single model invocation paired with the harness operations that handle its response. The overarching recursive process is the .

  1. Context assembly: The harness gathers the system prompt, user intent, recent conversation history, and accumulated tool outputs.
  2. Model inference: The assembled context is dispatched to the model API.
  3. Action parsing: The model responds with natural language prose, structured , or a combination of both.
  4. Policy evaluation and execution: The harness evaluates requested tool calls against its security policies. Some run automatically, others require interactive confirmation, and disallowed operations are rejected.
  5. Observation ingestion: Execution results—including standard output, standard error, exit codes, or refusal notices—are appended to the conversation context.
  6. Loop continuation: The cycle recurses back to step 1.

The loop concludes when the model produces a terminal textual response without requesting further actions, or when a configured stop condition halts execution.

Because LLMs are fundamentally stateless between API calls, models cannot remember what files they inspected in earlier turns unless the harness actively preserves those tool results within the context window.

Harness responsibilities beyond the model API

At the raw API level, an LLM simply transforms prompt tokens into completion tokens. Everything required to turn those token predictions into reliable software automation is handled by the harness:

  • Context assembly and pruning: Raw user input represents only a fraction of the outgoing payload. The harness injects runtime system prompts, repository rules, conversation history, tool definitions, and dynamic workspace content. For detailed token budgeting, see what fills a context window.
  • Tool execution and protocol adapters: When a model requests read_file, the harness handles the physical disk read. For external integrations, such as MCP, the harness acts as the client maintaining subprocess lifecycles or network sockets and projecting tool schemas into the model's format.
  • Security and authorization: A robust establishes clear boundaries around tool execution. It dictates which operations run automatically, which require interactive human approval, and which are blocked outright. Reading local files is generally permitted silently, while modifying code, running arbitrary shell commands, or accessing external networks typically requires elevated privileges.
  • Token management and compaction: As conversation logs expand with lengthy tool outputs, the harness monitors available context limits. When thresholds are breached, it triggers automated compaction, pruning intermediate tool outputs or summarizing early turns to preserve room for new work.
  • Resilience and error handling: Upstream API timeouts, rate limits, malformed JSON arguments, and non-zero process exits all require distinct recovery strategies. The harness manages retries, formats error diagnostics, and presents actionable feedback to the model.
  • Subagent orchestration: When tackling broad investigations, a harness can instantiate a —an isolated agentic loop with its own dedicated context window. Rather than polluting the primary conversation with tens of thousands of tokens of search results, the subagent performs the exploration independently and returns only a concise synthesis to the parent loop.
  • Execution sandboxing: A enforces strict operating system-level constraints around running processes. By restricting filesystem writes to designated project directories and isolating network interfaces, sandboxes prevent accidental damage or prompt injection attacks regardless of what commands the model attempts to run.
  • Audit transcripts: Maintaining comprehensive on-disk audit logs of every prompt, tool invocation, and shell output ensures that complex automated changes remain inspectable and reproducible.
What the harness adds to the model API A tall stack of eight boxes sits above one short band. The eight boxes are the work the harness does: assembling the context from instructions, files, history and tool results; holding the tool implementations and the MCP client connections; the permission model deciding what runs without asking; the sandbox limiting which files and hosts a tool can reach; watching the token budget and compacting; retries, timeouts and error handling; subagents that each get their own context window; and the transcript and checkpoints. A thick dashed line labelled "the boundary" runs under them. Below the line is a single short band, drawn with a heavier stroke and marked "the whole API", holding one request and one response: tokens and tool definitions in, tokens and tool calls out. The stack above the line is roughly seven times the height of the band below it. What the harness gives you Eight decisions. Every one of them is somebody's code, not the model's. Context assembly Tool implementations and MCP client connections Permission model Sandbox Token budget and compaction Retries, timeouts, error handling Subagents Transcript and checkpoints instructions, repository files, history, tool results the harness opens the file the model asked for run silently, stop and ask, or refuse which paths are writable, which hosts are reachable summarise or drop old results before the window fills a rate limit, a timeout and a failing tool need three answers a nested loop with its own context window every message, every call, every result, on disk the boundary below this line: what the provider ships Model API · the whole API one request: tokens and tool definitions in · one response: tokens and tool calls out Eight rows above the line, one below it, drawn to scale.
The model API handles inference in isolation; the harness provides the surrounding architecture—context management, permissions, and execution boundaries—that determines agent behavior.

Stop conditions and safeguards

An agentic loop operating without guardrails can enter runaway cycles—repeatedly executing failing commands with minor variations while burning tokens and incurring API costs. A provides a deterministic boundary that halts execution regardless of model state.

Production harnesses commonly enforce multiple complementary limits:

  • Turn caps: Enforcing a maximum count of model round-trips prevents infinite loops when an agent gets stuck in circular troubleshooting.
  • Token budgets: Capping total token consumption ensures that complex runs cannot exceed predefined cost thresholds.
  • Wall-clock timeouts: Setting hard elapsed time limits terminates operations that hang on long-running compilation or test commands.
  • Repeated failure thresholds: Halting after consecutive failed invocations of the same tool prevents repetitive trial-and-error spirals.
  • Interactive interrupts: Giving developers keyboard interrupts (such as pressing escape) provides immediate manual control over runaway execution.
Stop conditions for an unattended run

Set every limit before you start the run.

  1. Set a maximum number of turns.
  2. Set a maximum token budget for the run.
  3. Set a wall clock timeout.
  4. Stop the run after three consecutive failures of the same tool.
  5. Write the transcript to a file.
  6. Run the harness in a sandbox. Give write access to one directory only.

Failure modes in extended agent runs

Prolonged autonomous runs introduce specific failure modes that do not appear in single-turn interactions:

Compounding errors: If a model introduces a subtle flaw—such as hallucinating a method name or misinterpreting a test fixture—subsequent turns will read that code back from the filesystem as ground truth. Lacking out-of-band awareness, the model treats its own earlier mistakes as established architectural patterns, spreading the error across other files. Grounding the agent in external, deterministic verification—such as running linters, compilers, and test suites whose outputs cannot be hallucinated—is the primary safeguard against compounding mistakes.

Context drift and goal loss: As an agent explores a large codebase, thousands of tokens of intermediate command output can push the original user prompt out of the model's immediate attention window. An agent tasked with fixing a minor bug may drift into refactoring unrelated utilities. Mitigation strategies include periodic task re-anchoring, preserving the user goal in protected system prompt regions that bypass compaction, or decomposing expansive tasks into discrete, modular subagent runs.

Selecting the right harness involves evaluating how well each system balances autonomous execution with safety controls. Comparing harnesses analyzes the trade-offs across current tools.

Terms introduced

  • Harness: the program between you and the model API that assembles context, runs tools, enforces permissions, and keeps the loop going.
  • Agentic loop: the cycle of calling the model, running the tools it asks for, appending the results, and calling again until it stops asking.
  • Turn: one pass through that cycle. One model call plus whatever the harness does with the answer.
  • Permission model: the rules deciding which tool calls run silently, which need your confirmation, and which are refused.
  • Subagent: a nested loop with its own context window, given one task and returning only its result.
  • Stop condition: a limit that ends a run whether or not the job is finished, such as a turn cap, a token budget, or a timeout.
  • Sandbox: an enforced boundary around tool execution, covering the files a tool may read or write and the hosts it may reach.

How providers do it

Both APIs stop when the model asks for a tool and hand the work back to the caller. The names differ and the stop conditions differ a lot.

The loopAnthropicOpenAI
Model asks for a toolstop_reason: "tool_use" plus tool_use blocksoutput item "type": "function_call"
Result goes back astool_result with tool_use_id"type": "function_call_output" with "call_id"
Next call carries history byresending the messagesprevious_response_id
Prebuilt harnessClaude Agent SDK, Claude CodeCodex
Headless invocationclaude -p, or the Agent SDKcodex exec
Turn limitmax_turns / maxTurnsnot found in the docs read
Spend limitmax_budget_usd / maxBudgetUsdnot found in the docs read
Permission modelpermission mode, plus allow and deny rulesapproval_policy
SandboxOS isolation for Bash commandssandbox_mode, defaulting to workspace-write
Automatic compactionyes, marked by a compact_boundary messageyes, at model_auto_compact_token_limit

Every cell above is confirmed against the vendor's own documentation, except the two "not found" rows, which are open questions rather than a claim that the feature is absent.

The row that changes how a run is designed is the turn limit. Anthropic's harness will stop itself at a number you set; on OpenAI's, the cap read on the pages above is the sandbox rather than a count, so a run that keeps retrying a failing tool has to be stopped by whatever launched it.

What this maps to: the Messages API does not run the loop. It returns a tool_use block and stops, and the caller runs the tool and calls again. Anthropic also ships the loop twice over: as the Claude Agent SDK, a library for Python and TypeScript, and as Claude Code, the harness built on it.

QuestionAnswerStatus
How does the model ask for a tool?The response carries stop_reason: "tool_use" and one or more tool_use content blocksconfirmed
How does the result go back?A tool_result block quoting the matching tool_use_id, in the next requestconfirmed
Does the API ever run the tool?Client tools, no. Server tools such as web_search, web_fetch and code_execution run on Anthropic's infrastructure and return results in the same responseconfirmed
Is there a loop written for you?Tool Runner in the SDKs executes the tools and sends the results back automaticallyconfirmed
What is a turn called?A turn: model output with tool calls, SDK executes them, results feed back. The loop ends when Claude produces output with no tool callsconfirmed
Turn limitmax_turns / maxTurns. Counts tool-use turns only. No limit by defaultconfirmed
Spend limitmax_budget_usd / maxBudgetUsd. Subagent spend counts toward itconfirmed
Wall clock limitNo wall clock option appears in the agent loop reference read. Open questionunconfirmed
How does a run report why it stopped?ResultMessage.subtype: success, error_max_turns, error_max_budget_usd, error_during_executionconfirmed
Permission modelpermission_mode / permissionMode, one of default, acceptEdits, plan, dontAsk, auto, bypassPermissions, evaluated together with allowed_tools and disallowed_toolsconfirmed
What happens on a denial?Claude receives a rejection message as the tool result and usually tries another approachconfirmed
SubagentsSupported. A subagent starts with a fresh conversation, does not see the parent's turns, and returns only its final response as a tool resultconfirmed
CompactionAutomatic as the window approaches its limit. A system message with subtype: "compact_boundary" marks itconfirmed
SandboxOperating system level filesystem and network isolation for Bash commands, configured separately from the permission rulesconfirmed
TranscriptSessions are written to disk and can be resumed or forked by session IDconfirmed

Their vocabulary

Standard termTheir term
Agentic loopAgent loop
TurnTurn, counted as tool-use round trips
Stop conditionMax turns, max budget, reported as a result subtype
Permission modelPermission mode, plus allow and deny rules
SubagentSubagent

Where to look

The ResultMessage at the end of an SDK run carries subtype, num_turns, total_cost_usd and session_id, which answers what stopped the run and what it cost. In Claude Code, /context shows what is in the window and /usage shows the session's token and cost totals.

Last verified: 2026-09-09 against https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview and https://code.claude.com/docs/en/agent-sdk/agent-loop and https://code.claude.com/docs/en/permissions.


Check your understanding

0 of 4 answered

  1. A model "calls a tool". Which program actually opens the file?
  2. What ends a normal pass through the agentic loop?
  3. Why does a harness run a large repository search in a subagent rather than in the main conversation?
  4. What does a sandbox give you that a permission allowlist does not?