← notes Agents

A model in a loop: how frontier LLM agents are built

Every frontier agent calls a model in a loop. The products differ in the harness around it: tools, context and the prompt cache, subagents, sandboxes and evals. A snapshot of 2026-10.

21 min read 7 interactive

The loop is the agent

An LLM agent is a program that calls a model in a loop. The model never acts by itself. The harness turns each reply into an effect and feeds the effect back as text. Five steps recur in every system of the walkthrough: query the model with the message list, parse the action, execute it in the environment, append the output, and test whether to stop. The message list is the only state the model sees.

mini-SWE-agent shows how little this needs. Its agent class has 190 lines. It has one tool, bash, one linear message list that is both the model input and the saved trajectory, and a fresh subprocess for each command. It submits when a command prints COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT as its first output line and exits with code 0. Its authors report 74% on SWE-bench Verified with Gemini 3 Pro.

The products differ on four axes:

  • Loop owner. The agent process (mini, Claude Code), a server inside the sandbox (OpenHands V1), or the front end (Gemini CLI, where the UI calls a one-turn engine again after each batch of tool results). Aider has no inner loop; the human is the outer loop.
  • Action format. A native tool call, or a fenced text block that a regular expression extracts (SWE-agent in 2024, mini v1).
  • State. A message list; an event log (OpenHands stores immutable events and resumes by replay); or a stateless request (Codex sends store: false, so the client carries the history and replays the model’s encrypted reasoning).
  • Stop rule. A submit signal, a reply without a tool call (Codex, Claude Code), a limit, or a human.

animation

One task through the agent loop

Press Play, or Step one hop at a time. Then switch the stop rule to No call and run again: step 3 is a reply without a tool call.

Stop rule
Message list

    model calls
    input, this call
    input, all calls
    output, all calls
    input : output
    Every model call re-sends the whole list, so input grows much faster than output. Under the sentinel rule the empty reply becomes an error observation; under the no-call rule the same reply ends the run before the fix. Toy script and token counts.

    A good loop turns every failure that the model can fix into an observation: a format error, a timeout, a bad edit. mini kills the whole process group on a timeout and returns the timeout as text with return code −1. Loops count consecutive failures and stop after a small number; 3 is the common value. They also keep a fallback result for fatal errors. SWE-agent submits the current git diff when any limit fires; mini exits with an empty submission.

    Limits are not uniform. mini counts model calls (250 in its SWE-bench config, with a cost cap of 3 USD and a 30 s command timeout), OpenHands counts agent steps (500 by default), and Gemini CLI counts turns (100). Codex has no step cap in its turn loop. Cost caps stop after the call that crosses them, so that call is already paid.

    Tools and extensions: load only what you use

    Every major coding agent has a shell tool. They differ in what sits beside it. Codex has no dedicated read or search tool; its prompt tells the model to prefer rg. Claude Code adds Read, Edit, Write and others, and Gemini CLI keeps dedicated glob and grep_search tools. Bash alone works. In 2024 the SWE-agent paper lifted GPT-4 Turbo from 11.0% to 18.0% on SWE-bench Lite with a custom interface. One year later the same lab’s bash-only mini-SWE-agent was competitive with current models. Products keep dedicated tools where the harness needs control: a permission rule can match Edit(/src/**), but a shell string is hard to classify.

    Four edit formats are in production, and the choice follows the model’s training:

    FormatWhoTrade-off
    Exact str_replaceClaude Code, Gemini CLI, OpenHandsSimplest; fails on whitespace drift; no line numbers to shift
    Patch envelope under a grammarCodex apply_patchSeveral files per call; best with a model trained on it
    SEARCH/REPLACE text blocksAider (289 of 357 models in its registry)Works with any model; old text must match exactly
    Whole-file writeAll, for new or small filesMost reliable; output cost grows with file size

    Cursor gives OpenAI models a patch tool and Anthropic models string replacement, because an unfamiliar tool “costs extra reasoning tokens”. Every harness also caps tool output and says how to narrow the query: Codex keeps head and tail of 10,000 tokens, mini keeps the first and last 5,000 characters, and Claude Code’s Read stops at 25,000 tokens.

    Tool definitions are input tokens on every request. Anthropic’s example with five MCP servers had 58 tools and about 55K tokens of definitions. Three remedies exist. Deferred loading keeps a tool out of the prompt until a search tool finds it: about 77K tokens fell to 8.7K, and Opus 4 accuracy on an MCP eval rose from 49% to 74%. Programmatic tool calling lets the model call tools from code in a sandbox (−37% tokens). Code as interface shows each MCP server as files of TypeScript wrappers; the agent reads only what it needs, and intermediate data stays in the sandbox (150K tokens to about 2K in Anthropic’s example). Codex’s newest models see only two tools, exec and wait, and call every other tool from JavaScript in a V8 isolate.

    Extensions follow the same rule, called progressive disclosure. A skill is a directory with a SKILL.md file. Only its name and description (about 100 tokens) sit in the prompt; the body loads when a task matches, and bundled scripts run without entering the context. A hook is a command that the harness runs at a loop event. It is the only deterministic extension: a PreToolUse hook that exits with code 2 blocks the call, and its stderr becomes the reason the model sees. Instruction files such as CLAUDE.md are advice, not enforcement. MCP (Model Context Protocol, created by Anthropic in 2024-11 and donated to the Agentic AI Foundation in 2025-12) is the open standard for tool servers. Its 2026-07-28 revision is stateless: no handshake and no session id, so any replica can answer any call.

    Context is a budget, and the cache sets the price

    The window holds five blocks: the system prompt, the tool schemas, instruction and memory files, session context, and the conversation. The first four should stay fixed; the conversation grows with every tool output. Length itself hurts: Chroma ran 18 models over 194,480 calls and found that accuracy falls as input grows, even on simple tasks.

    Harnesses shrink the conversation in a fixed order, cheapest first. First, they cap each tool output at the source. Second, they mask old tool results: an old output becomes a short placeholder, and the model’s actions stay. A JetBrains study on SWE-agent found that masking about halves the cost and matches LLM summarisation in solve rate. Anthropic’s context editing clears old results at 100,000 input tokens by default and keeps the 3 latest. Third, they compact: a model writes a summary that replaces the old history. Triggers range from 50% of the window (Gemini CLI) to 90% (Codex). Gemini CLI adds a second “probe” turn that looks for what the summary lost, and Cursor and Manus keep paths and URLs so that a dropped detail can be fetched again.

    playground

    Fill, mask or compact a 200K window

    Press Play to replay the 60 steps, or drag across the chart to scrub. Switch the strategy and the tool-schema load, and move the trigger.

    Strategy
    Tool schemas
    system + memory tool schemas CLAUDE.md model actions tool outputs summary masked placeholders
    run
    peak context
    mask / compact events
    outputs no longer verbatim
    input sent, all calls
    With no strategy the window overflows, and in mini an overflow ends the run. Masking holds the window nearly flat with no model call. Compaction draws a sawtooth, and each tooth loses the verbatim outputs. Toy output sizes; the 77K and 8.7K schema loads are Anthropic's measurement.

    Each step re-sends the whole history, so agents are input-dominated. Manus measures about 100 input tokens per output token over about 50 tool calls per task. A prompt cache stores the attention keys and values that the provider computed for a request prefix. A later request that starts with the same bytes skips that work and pays less. On Anthropic’s 2026-10 price rows, a cache write costs 1.25× the input price (5-minute lifetime) and a read 0.1× (0.05× on Opus 5.5 and Sonnet 5.5). At 0.1×, ten requests over one prefix cost about 2.15× one request instead of 10×.

    Manus, the Claude Code team and Hermes reached the same rules:

    • Stable prefix. No per-second timestamp in the system prompt; a fixed tool order and JSON key order. Past Claude Code cache breaks came from a detailed timestamp and an unordered tool list.
    • Append-only history. Hermes states that “the ONLY context mutation is compression”.
    • Updates as messages. Time, file changes and mode changes go into the next message. Claude Code’s plan mode is two tools plus a message, not a new tool set.
    • Compaction as a fork. The summary request reuses the parent’s prefix and adds its instruction last, so it reads the history at the cache price.
    • No model switch mid-session. After about 100K tokens in an Opus session, an answer from Haiku costs more than staying on Opus. Route cheap work to a subagent instead.

    calculator

    One changed token breaks the cache

    Click a block to make it change on every request, as a timestamp would. Click Turn 1 to edit old history. Switch the model.

    Model
    read from cache written to cache (1.25× input) same request, no cache
    input cost, cached
    input cost, no cache
    cached / no cache
    tokens read from cache

    The cache matches a prefix byte for byte. A block that changes forces a re-write of everything after it at 1.25× the input price, so a broken cache can cost more than no cache. Prices: Anthropic, 2026-10; block sizes are toy numbers.

    Plans, long runs and subagents

    Coding agents plan interleaved by default: there is no planner stage, only a short checklist that the model edits as it works. Plan mode is opt-in, and the harness enforces it as a permission state, not a prompt. Gemini CLI adds a catch-all deny rule at priority 40 and allows read-only tools at priority 50, so the model cannot talk its way out. Todo tools help through recitation (Manus: rewriting todo.md puts the goal at the end of the context), but Claude Code turned them off for its newest models, which track multi-step work without a list.

    Models under-ask. In Ambig-SWE, talking to a simulated user raised the resolve rate on underspecified issues by up to 74%, yet Qwen3-Coder never asked. Products therefore force the question with a tool that has options and a default, and with a timeout path for unattended runs.

    Runs now outlast a context window. METR puts the 50% time horizon at about 50 minutes for Claude 3.7 Sonnet (2025-03) and about 17 hours on a 2026-04 chart (a secondary source; METR calls values above 16 hours unreliable). The Ralph loop (2025-07) is the plainest answer: while :; do cat PROMPT.md | claude-code ; done, a fresh context and the same prompt on every pass, with state in files.

    A subagent is a child loop with its own context window, system prompt and tool list. Only its final message returns to the parent. The gains: a child can read tens of thousands of tokens and return 1–2k; children run in parallel (Anthropic’s lead agent starts 3–5 of them and cut research time by up to 90%); and a child can run on a cheaper model. The costs: the child knows only what the brief says, two children can make conflicting implicit decisions, and tokens multiply. Anthropic measured single agents at about 4× the tokens of a chat and multi-agent systems at about 15×; Claude Code agent teams cost about 7×. Anthropic’s research system beat single-agent Opus 4 by 90.2% on an internal eval.

    animation

    One context against a fan-out

    Press Play in each mode. Then raise the tokens per file until one agent passes the window, and change the number of children.

    Show

    file content brief (parent → child) summary (child → parent) context used, of a 200K window
    One agentFan-out
    Limit of this toy: it bills fewer input tokens for the fan-out than for one agent, but real multi-agent systems use more (Anthropic measured about 15× chat tokens, against about 4× for one agent). What the toy does show: the fan-out keeps every window small and finishes in fewer steps, and it loads a little more in total because each child repeats its setup. Toy sizes.

    The rule that survived is single writer, many readers. Cognition’s “Don’t Build Multi-Agents” (2025-06) showed two subagents that built a Mario-style background and a bird that did not match. Its 2026-04 follow-up keeps writes single-threaded and adds agents that “contribute intelligence rather than actions”, such as a reviewer with a clean context that sees only the diff. Cursor ran hundreds of agents on one project: with a shared lock file, 20 agents worked at the speed of 2 or 3, and only a planner/worker hierarchy with a judge and fresh cycles worked. Git worktrees isolate files, not decisions. open_deep_research learned the same lesson: workers that researched and wrote sections gave disjoint reports, so it now researches in parallel and writes once.

    Safety lives below the model

    An agent turns text into side effects. Anthropic names the failure sources: overeager actions beyond what the user authorised, honest mistakes about the blast radius of a command, and prompt injection, which is hostile instructions inside data the model reads. Simon Willison’s lethal trifecta says when injection can steal data: private data, untrusted content and an outward channel in one session. Remove one leg and the attack fails. Meta’s Rule of Two turns this into a checklist. Fixed tests do not settle it: adaptive attacks broke 12 published defences, with success above 90% for most of them.

    Defence comes in five layers: the model, the harness (rules or a classifier), the OS sandbox, the network egress proxy, and credential handling. The model layer is probabilistic. The lower layers are enforced by the kernel or by a separate process, so a fooled model cannot argue past them. That matters because rule lists leak. Claude Code’s docs say a rule “isn’t a security boundary”: Bash(curl *) stops curl but not /usr/bin/curl or sh -c 'curl …'. Codex binds .git read-only last inside writable roots, because a writable .git/hooks lets a sandboxed command plant code that runs outside.

    playground

    Send a tool call through the layers

    Pick a call and a setup. When the harness asks, answer it. Compare the counters for the three setups.

    Setup
      prompts to you, all 7 calls
      harmful calls stopped, no human
      harmful calls left to your click
      Rules alone ask you about almost everything and stop only exact text matches. A sandbox runs harmless commands silently and stops the rest at the kernel, the proxy or the credential layer. A classifier answers the remaining escape requests. Toy calls and verdicts; each mechanism is from the walkthrough.

      Approval fatigue drove the 2026 design. Users approved 93% of prompts by habit, and Claude Code’s opt-in sandbox cut prompts by 84%. Codex and Cursor run sandbox-first and ask only when a command must leave the sandbox. Claude Code starts interactive sessions in auto mode: a classifier that sees user messages and tool calls but not tool outputs, so injected text cannot address it. Anthropic published its error rates: 0.4% false positives on 10,000 real actions, and 17% false negatives on 52 real overeager actions, which the post calls “the honest number”. The incidents of 2025 came from missing separation, “always allow” habits and bypass flags, not from exotic exploits.

      Products: one loop, many harnesses

      Coding agents moved through five overlapping eras in 30 months: IDE autocomplete, chat, local CLI agents, cloud background agents (2025-04 onward), and fleets that run for hours. All share the loop above. They differ in the surface (terminal, IDE, cloud), the substrate (OS sandbox, container, microVM, CI runner) and the review path (diff, plan, draft PR). Four themes recur by 2026: a fast read-only retrieval child, a verification step that the agent cannot skip, git as the unit of isolation, and cost counted per task. On Cognition’s FrontierCode benchmark (vendor-reported), a lead with a cheaper sidekick scored 63.1 at 1.35 USD per task, against 63.6 at 3.51 USD for Opus 5 alone.

      diagram

      Ten coding agents on six design axes

      Pick an axis to regroup the products. Click a product to see all its choices and its design signature.

      Group by
      The loop is shared; the harness is where products differ. n/d means the sources read do not document the item, not that it is absent. Product numbers elsewhere are vendor-reported.

      General agents run the same loop on other environments. Computer-use agents started with pure screenshots (Claude in 2024-10; OpenAI’s CUA in 2025-01 at 38.1% on OSWorld, press-reported). A Claude screenshot costs 1,000 to 1,800 input tokens, so a 200K window holds well under 100. The 2026 trend is hybrid: pixels plus indexed page elements plus code shortcuts. Agent S3 reached 72.6% on OSWorld with best-of-10 rollouts and a behaviour judge (humans: 72.36%). Deep research follows one shape: clarify once, write a brief, run parallel searches in isolated contexts, compress each result, and write the report in one call. Personal assistants such as OpenClaw and Hermes run as a background daemon fed by chat apps. A heartbeat turn every 30 minutes ends with “If nothing needs attention, reply NO_REPLY”, so the agent speaks only when needed.

      Measure the system, not the model

      The system under test is the model plus the harness; a change to either needs a new measurement. Infrastructure counts too. Anthropic ran Terminal-Bench 2.0 under six container resource settings and saw a 6-point spread (p<0.01p<0.01), larger than many leaderboard gaps; infra errors fell from 5.8% to 0.5% as limits loosened. Treat a gap under 3 points with suspicion.

      Grade the final state, not the path. Opus 4.5 scored 42% on CORE-Bench until a grader that demanded “96.12” for “96.124991…” was fixed; the score then reached 95%. Harbor tests every task set with two built-in agents: the oracle runs the reference solution and must score 1, and a do-nothing agent must score 0. Keep infra failures out of the score: a crashed sandbox is a missing data point, while an agent that runs out of time has failed.

      Report repeats, confidence intervals and paired differences. When questions share a context, cluster the standard errors; the clustered value was over 3× the naive one on some evals. For an agent that must work every time, report pass^k, the chance that all kk trials succeed, (ck)/(nk)\binom{c}{k}/\binom{n}{k} per task with cc successes in nn trials. pass@k, the chance that at least one succeeds, suits tasks where one success is enough. At k=1k=1 they are equal. A 75% per-trial rate gives pass3=0.753=42%\text{pass}^3 = 0.75^3 = 42\%.

      playground

      Same pass@1, different reliability

      Drag a task's bar up or down. Try All 75%, then Mixed: both have a mean of 75%.

      pass@k: at least one of k trials succeeds pass^k: all k trials succeed
      pass@1 (mean rate)
      pass@3
      pass^3
      pass^10
      With All 75%, pass@k climbs toward 100% and pass^k falls as 0.75^k toward 0. Tasks that always pass or always fail add the same to both curves at every k, so in Mixed pass^k levels off near 54%. Toy task rates; the curves use per-task rates, not the count estimators.