Fig. 1, step by step: every decision on this page sits on one turn of the loop
<tool_call> blocks, one per file it wants to read (§1).<|im_end|> is an end-of-sequence id, so sampling stops there and the result can only come from the harness. This action boundary is the step most easily got wrong without noticing: let past it, the local model wrote the user's next turn in 5 of 18 samples (§2).tool_calls; a malformed call can vanish inside the server and look like "done" (§1, §7).The run is careful_s1 from section 10, on the harness this page builds (src/harness/native.py); the column is its prompt, token by token, from the model's own template and tokenizer, coloured by kind: tool definitions, system prompt and markup, task, model replies, tool results. The loop itself, built from zero in seven recorded steps, is the parent page's Loop lab; this page takes each step apart.
You need: the agent loop (model call, tool call, result, repeat), as in section 1 of Topic: agentic-harnesses. Not here, each owned by its own page: what goes into the window, compaction and memory (Context engineering); permissions and prompt injection (Agent security); how Claude Code implements all this (Claude Code, taken apart); ready-made loops in libraries (Topic: agentic-frameworks); agent benchmarks (Agentic benchmarks).
MEASURED: runs recorded on 6 October 2026 (Claude through the Claude Code CLI 2.1.289; Qwen3 4B Instruct 2507 in 4-bit on mlx-lm 0.32.0, Apple M1 Pro) or the parent page's of 5 October. SOURCE: published, linked. The small local model and Claude are never compared as if they were the same kind of model.
| Decision | A default that works | What the recordings showed | § |
|---|---|---|---|
| How the model asks for an action | The provider's native tool calls (JSON schemas in, typed calls out) | Underneath, an open model writes the call as tokens between special tokens; a malformed call can vanish silently in the server | 1 |
| Where the model's turn ends | At its action: the API's tool-use stop, the end-of-turn token, or a stop sequence | Let past that point, a model writes the other side's turn: Haiku wrote fake tool results (parent page); the local model wrote a fake user turn, with tool calls inside, in 5 of 18 samples | 2 |
| Several calls at once | Read-only batches concurrently, anything else in order, results in call order in one message | Sonnet batched calls in 9 of 29 replies, Haiku in 7 of 91; the local model batched an edit with the test run 13 times | 3 |
| Streaming and interrupts | Parse arguments at the block's end; give every pending call a result when interrupted | Claude Code ran a first edit 0.78 s before the second had finished streaming; on interrupt it wrote a "tool use was rejected" result itself | 4 |
| Tool design and errors | Few tools, verdict first, errors that say what to change | Retrying failed edits: "Edit failed." fixed 1 of 13, the tools' own messages 3, a computed diagnosis 4 | 5 |
| Edit format | Exact string replacement as a tool call; lenient appliers for diffs | Haiku: exact replace 13 of 13 correct, unified diff through git apply 4 of 13 (12 with recounted headers), whole file 12 with one silent line-ending change | 6 |
| Recovering from errors | Every failure becomes an observation, except infrastructure failures, which are retried out of sight | A truncated reply, an empty reply and a dropped server connection all occurred in these runs | 7 |
| Planning | A todo tool for long tasks; a read-only plan phase when a person must approve | Not measured here; published designs only | 8 |
| Where tools run | A working directory, a timeout and output capture on every call; isolation that grows with autonomy | native.py: 60-second timeouts, paths resolved and refused outside the repository | 9 |
| When to stop | Model says done and a verifier agrees (one the agent did not write), or a hard cap; truncation is not done | 4 of 16 local runs stopped with a test failing, a 5th on a truncated reply; a verify rule rescued one and burned 36,177 tokens on another | 10 |
| Cost and latency | Fewer round trips, small edits, budgets checked before each call | Each call re-reads the whole prompt: 486 tokens on call 1, 1,531 on call 5 | 11 |
| Is the harness any good? | Fix the model, change one harness decision, repeat runs, report cost beside score | The edit-format ranking flips between Claude and a 4B model on the same harness | 12 |
Real tokens from turn 1 of a recorded run (local model, temperature 0.7, seed 1; the parent page's running example). Token ids come from the model's own tokenizer; blue tokens are special tokens (one id each), green ones are what the model generated. "Boundary ignored" replays a recorded continuation: the same prompt and reply sent as raw text with generation allowed to run past the end-of-turn token (section 2).
The parent page's Loop lab built a harness whose model could only return text: tools described in prose, an ACTION line parsed by the harness. This page moves the same loop onto native tool calling and opens the layer the APIs hide. A tool call has three layers. The contract: the request carries tool definitions (name, description, JSON Schema of the arguments) and the reply a typed call (name, arguments, an id). The rendering: the provider turns definitions, messages and earlier calls into the text the model reads; Anthropic says "the API constructs a special system prompt from the tool definitions", a prompt that tells the model "The output is not expected to be valid XML and is parsed with regular expressions" (Define tools, read 6 Oct 2026) SOURCE, and OpenAI's functions are "injected into the system message" (parent page). The generation: the model writes the call as tokens it was trained to write and ends its turn with an end-of-turn token. With a closed model you see only the contract; with an open model all three, because the rendering is a published chat template.
The experiment. src/harness/native.py is the Loop lab's loop on native calls (the same four tools, read_file, run_tests, edit_file with exact replacement and run_command, and the same permission gate), sent to mlx_lm.server, which renders the request with the model's own template (a Jinja file shipped with the weights), generates, and parses the reply back into tool_calls. The key fact the stepper shows: to the model, a tool result is something the user said, rendered as a user turn of <tool_response> blocks without the call ids, matched to its call by order alone. Rendering the recorded conversation with the model's own template and tokenizer gives exactly the prompt sizes the server reported on every call: 486, 865, 926, 1,252 and 1,531 tokens MEASURED. So the tokens below are the model's real input.
The animation, step by step
read_file, run_tests, edit_file, run_command. Nothing here is text the model reads yet.<tools></tools>, and the instruction to answer with <tool_call>{...}</tool_call>: 428 tokens, tools included. Blue tokens are special tokens (one id each).<|im_start|>assistant and a newline, inviting the model to speak. The prompt is 486 tokens, exactly what the server reported.<tool_call>, a JSON object naming read_file and its path, </tool_call>, and a second call for the test file; 46 generated tokens by the server's count.<|im_end|>: the boundary. Like <tool_call> (id 151657), </tool_call> (151658) and <tool_response> (151665), it is a single added token. Token 151645 is one of the model's end-of-sequence ids (generation_config.json), so sampling stops here and the server reports finish_reason: "tool_calls". Nothing after the call is generated: the result can only come from the harness.json.loads on it and returns OpenAI-style tool_calls, 2 of them, with an id each. The harness never sees the tags.tool messages. The template renders them inside one user turn, as <tool_response> blocks, without the ids; with the assistant turn and a new generation prompt, the next request is 865 tokens.<|im_end|>.<|im_end|>. The same prompt and reply, sent as raw text to /v1/completions so nothing stops at the end-of-turn token. The model goes straight on and opens the next turn itself with <|im_start|>user (red tokens are the continuation).tool_calls and returned finish_reason "tool_calls". A harness reading this reply would execute calls the model wrote while pretending to be the user. It did this in 5 of 5 samples after this first call.core.py) and then said the code "appears correct". The end-of-turn token, a stop sequence, or an API's stop_reason is what keeps observations honest (section 2).json.loads). If the text between the tags is not valid JSON, server.py logs "Failed to parse tool call ... tool text was likely truncated mid-generation" and drops the call. The client receives an empty reply with finish_reason: "stop", which a naive harness reads as "the model is done". The sibling page Harnesses for training and evaluation measured the cost: its loop ended an episode on any reply without a tool call, and 9 of its local rollouts ended on a dropped malformed call, none of them passing. Read your server's parser before trusting its finish reasons; native.py treats an empty reply as an error to report back (section 7).| Anthropic Messages API | OpenAI (Responses / Chat Completions) | Open model through its chat template (Qwen3) | |
|---|---|---|---|
| Definitions | tools: name, description, input_schema; rendered into a tool-use system prompt (496 tokens on Haiku 4.5, before the definitions) | tools: type function, name, description, parameters, strict | JSON lines inside <tools> in the system turn, plus a format instruction |
| The call | tool_use block: id, name, input object | function_call item (or tool_calls): call id, name, arguments as a JSON string | text between <tool_call> tokens; the server parses it |
| How generation stops | stop_reason: "tool_use" | finish_reason: "tool_calls" | end-of-turn token <|im_end|> (an EOS id) |
| The result | tool_result blocks with tool_use_id, first in the next user message, is_error optional | function_call_output / role tool with the call id | role tool, rendered as a user turn of <tool_response> blocks; the ids are not rendered at all |
| Schema guarantee | strict: true (constrained decoding) | strict: needs additionalProperties: false and every field required | none in mlx-lm: whatever the model writes is parsed |
Sources, read 6 Oct 2026: Anthropic, Handle tool calls; OpenAI, Function calling; the Qwen3 4B Instruct 2507 chat template and generation_config.json (Hugging Face snapshot 50d4277 of mlx-community/Qwen3-4B-Instruct-2507-4bit); mlx-lm 0.32.0 server.py and tokenizer_utils.py. The 496-token figure is the parent page's (Anthropic tool-use pricing table).
Predict, then reveal. With two calls in one turn and no ids in the rendered results, how does this model know which result is which? By order only: the results are rendered in the order of the tool messages, which native.py keeps identical to the order of the calls. A harness that runs calls concurrently and appends results as they finish would silently swap them for this model. On the Anthropic API the tool_use_id does the matching, but the docs still require all results in one message, before any text.
Every token the local model read on the fifth and last call of the recorded run careful_s1, tokenised with the model's own tokenizer after rendering through its own chat template (Hugging Face snapshot 50d4277). Each earlier call read a prefix of this text, ending where the red marks are; the server reported the same token counts on all five calls MEASURED. Click a token for its id.
<|im_start|>assistant and a newline token. On call 2 the template rendered the model's reply after it (its text was a single newline, and the template puts another newline before a tool call), and the tokenizer merged the three newlines into one token, . So call 2's tokens are not call 1's tokens plus new ones: the 486th token changed. Any cache keyed on token prefixes (a local server's prompt cache, a provider's prompt cache) has to cope with that; keeping the rendered history byte-stable from call to call is the harness's job.A language model continues text. After it has written an action, the likeliest continuation of a transcript of actions and results is a result, so a model that is not stopped writes one. The harness must make the model's turn end exactly at its action and never read anything generated after it: the action boundary. Who enforces it depends on the protocol:
| Protocol | Who ends the turn at the action | What can go wrong |
|---|---|---|
| Provider API with tools (Anthropic, OpenAI) | The provider: stop_reason: "tool_use" / finish_reason: "tool_calls" | Nothing at the boundary; a reply cut by max_tokens can hold an incomplete call (section 7) |
| Open model through its chat template | The model, by writing its end-of-turn token, and the server, by stopping there | A raw-text endpoint, a misconfigured stop list, or a template whose end token is not in the server's EOS list |
Your own text protocol (the Loop lab's ACTION {json} line) | You: a stop sequence such as the result header your harness writes, or cutting the reply at the first action line | Everything, if you forget |
Without it, recorded. In the parent page's Loop lab, Claude Haiku 4.5 driven through claude -p (which cannot take a stop sequence) wrote fake tool results after its own action and once kept going for 95,162 characters until the 32,000-token output cap; mini-SWE-agent's text mode through the same route invented command output in 7 of 11 replies in the parent page's aborted run (closed block below), and in Other coding harnesses' own recorded run (its section 1) the parser refused 5 of 10 calls, and a client-side cut still paid for the invented text: 8,932 output tokens for 5 calls MEASURED. The two runs are different recordings, both on Haiku 4.5. The local model behaved differently:
<tool_response>). It wrote a user turn: 5 of 18 continuations opened with <|im_start|>user, all of them after its first call, usually restating the task, and 4 of them then asked for tool calls inside that user turn, which the server parsed as real tool_calls. The section 1 animation replays one ("Boundary ignored").Red: samples in which the model kept writing after its action MEASURED. In the chat endpoint the local model ended its turn right after the ACTION line in 20 of 20 samples, with or without a stop sequence: its own end-of-turn token did the work. Let past that token, it wrote the next turn itself in 5 of 18 samples: all 5 after its first call, none of the 13 after its later calls, where it ended at once with an end-of-text or an empty turn.
textstats/core.py), with and without stop: ["--- turn"]. Native past the boundary: the recorded conversation of run careful_s1 (section 10), rendered through the template up to and including each of the model's four tool-calling turns and its <|im_end|>, sent as raw text to /v1/completions with token ids returned, so every generated token, special ones included, is visible. Two of the planned 20 samples were lost when the shared server crashed. Code: src/harness/boundary.py.mini-SWE-agent 2.4.6, its stock text-based prompts unchanged, commands run in a python:3.13-slim container, each step sent to claude -p with every Claude Code tool switched off and the transcript flattened into one text prompt (the subscription has no API key), Claude Haiku 4.5, the running example, 5 October 2026. Stopped by hand after 11 model calls under a shared budget, code unchanged, tests still 2 failed, 1 passed MEASURED.
In 7 of 11 replies Haiku wrote its command and then kept going, inventing the command's output and its own next moves; mini-SWE-agent correctly rejected 6 of them for containing more than one action (format errors), and one call ran for 323 seconds writing 39,638 tokens of imagined session. In all: 75,041 output tokens in 612 seconds of model time, for no change to the code.
| Call | Input | Output | Seconds | Actions in reply | Ran |
|---|---|---|---|---|---|
| 1 | 1,264 | 196 | 16.6 | 1 | ls -la |
| 2 | 1,504 | 5,487 | 34.6 | 18, invented output | (rejected) |
| 3 | 1,663 | 308 | 15.1 | 1 | cat README.md && echo "---" && find . -type f -name "*.py" | head -20 |
| 4 | 1,858 | 2,040 | 16.3 | 11, invented output | (rejected) |
| 5 | 2,017 | 204 | 4.5 | 1 | python3 tests/test_core.py |
| 6 | 36,182 | 39,638 | 323.3 | 17, invented output | (rejected) |
| 7 | 2,312 | 9,907 | 82.5 | 1, invented output | python3 tests/test_core.py && echo "All tests passed successfully!" |
| 8 | 2,773 | 9,962 | 65.2 | 4, invented output | (rejected) |
| 9 | 2,932 | 183 | 4.3 | 1 | cat tests/test_core.py |
| 10 | 3,287 | 5,638 | 35.5 | 14, invented output | (rejected) |
| 11 | 3,446 | 1,478 | 14.1 | 2, invented output | (rejected) |
Why. A tool-calling API ends the model's turn at the tool call (stop_reason: "tool_use"); a text protocol needs a stop sequence at the end of the action block, and claude -p exposes none, so the adapter had nothing to stop on. That is why mini-SWE-agent 2.x recommends tool calls over its text mode (its models/utils/actions_text.py), and why the published mini-SWE-agent numbers (run through APIs) are not in question. A second trap appeared before any model call: the stock prompt fills in the host's operating system, so on a Mac host it tells the model to use BSD sed -i '' inside a Linux container; the adapter passed the container's own uname instead. Data: the parent page's src/atlas/inputs/mswe_attempt_2026-10-05.json.
A model may ask for more than one tool in a reply. Anthropic: "By default, Claude may call multiple tools in a single response"; disable_parallel_tool_use: true inside tool_choice limits it to one, and OpenAI has parallel_tool_calls: false (Parallel tool use; Function calling, both read 6 Oct 2026) SOURCE. "Parallel" describes the request, not the execution: the API "doesn't prescribe an execution order". Running them is the harness's decision, and how often it arises depends on the model:
Two kinds of batch show up. Independent calls, such as two or three reads, are safe to run at the same time. Dependent calls are not: the local model asked for edit_file and run_tests together in 13 of its 29 multi-call replies, and Sonnet in Claude Code sent Edit, Edit, Bash (two edits, then the tests) three times. Run those concurrently and the tests may run on the old code; the model then reads a failure caused by the harness.
read_file, run_tests), run them on a thread pool; otherwise one by one, in the order the model wrote them. Either way, return one result per call, in call order, in the next request. Anthropic adds two details: put all results in one user message, because splitting them "teaches" Claude to stop making parallel calls; and if you skip a call (say an earlier write failed), still return a result for it, marked is_error, such as "Not executed: the preceding write_file call failed." Its suggested system-prompt line for agents that batch too eagerly: "Only batch tool calls that are independent of each other." It also notes that Claude Fable 5.1 "may issue fewer parallel tool calls than earlier models" in long agent loops. Batches cut round trips, and every round trip re-reads the whole context (section 11).Replies that contained at least one tool call, split by how many MEASURED. Claude: the parent page's 22 recorded Claude Code sessions (Trace and context lab), counted per model message: Sonnet 5.5 put several calls in 9 of its 29 tool-calling replies and Haiku 4.5 in 7 of 91. Local model: the 16 runs of section 10.
is_error flag and an instructive message (section 5); and for the tests either their real output (which shows the unfixed code failing) or "Not executed: the preceding Edit failed." The second is clearer: it saves a test run and stops the model from reading a failure that says nothing new.Without streaming, nobody sees anything until the reply exists, and the harness cannot act on the first tool call while the model writes the second. Without interrupts, stopping a wrong turn means killing the process and losing the session. Both are harness features: the model does not know it is being streamed or stopped.
How a stream is shaped. A tool call streams its arguments as fragments of JSON that the harness concatenates and parses only when the block closes; errors can arrive inside a stream that has already started (details below).
One Claude Code run on the running example, each streamed line timestamped as it reached our process MEASURED. Bars: a model call from message_start to message_delta; darker segments: tool-call blocks streaming their arguments (blue, then purple when one reply holds two); green dots: the tool's result coming back. In row 4 the first Edit's arguments closed at 15.01 s and its result was back at 15.14 s, while the second Edit streamed until 15.93 s: the first call ran 0.78 s before the reply was complete. Claude Sonnet 5.5 in Claude Code 2.1.289 with --include-partial-messages; the whole run took 7 turns, 20.7 s and $0.0426 at list prices.
On the Anthropic API a reply is a sequence of server-sent events: message_start; per content block a content_block_start, deltas and content_block_stop; then message_delta (with stop_reason and usage) and message_stop. A tool call streams its arguments as input_json_delta strings that you concatenate and parse at the block's stop. Errors such as overloaded_error can arrive inside a stream that has already started (Streaming messages, read 6 Oct 2026) SOURCE.
Anthropic: ping events can appear anywhere, and "current models only support emitting one complete key and value property from input at a time", so a tool call's stream pauses while each value is being produced. OpenAI's Responses API streams arguments as response.function_call_arguments.delta events, closed by .done. mlx-lm's server does not stream tool arguments at all: it buffers everything between <tool_call> and </tool_call> and sends the call whole when the closing tag arrives (server.py, 0.32.0). How the providers' APIs differ as designs (where the conversation lives, what a tool call is, how its result is paired back) is Service APIs, section 7.
Interrupts mean three things: stop generation (close the stream), stop any running tool (kill its process, which is why a harness keeps child process handles), and leave a transcript the API will accept. The last is the subtle part: on the Anthropic API every tool_use must be followed immediately by its tool_result, or the next request fails with "tool_use ids were found without tool_result blocks immediately after" (Handle tool calls). So an interrupted call still needs a result, written by the harness. Claude Code writes one:
is_error: true with "Not executed: ..."), then let the person's next message steer. Never execute a half-streamed tool call: a call cut off by max_tokens must be retried with a larger limit (Handling stop reasons).Our script called client.interrupt() the instant the first tool call arrived MEASURED. Claude Code wrote the missing result itself ("The tool use was rejected", is_error: true), so a follow-up in the same session worked: asked what it last ran, Haiku said it had tried ls -la but "the tool use was rejected and I didn't get the result". Claude Agent SDK 0.2.163 (bundled Claude Code 2.1.286), Claude Haiku 4.5; the CLI's one em-dash is shown as ", ".
A tool is an interface whose user is a model that reads every word literally, cannot ask a colleague and sees the world only through what the tool returns. The SWE-agent paper (Yang et al., May 2024) called this the agent-computer interface (ACI) and measured it by changing one interface choice at a time on a SWE-bench Lite subset, same model SOURCE (Table 3, arXiv 2405.15793):
Resolved share of the SWE-bench Lite subset, default SWE-agent (a 100-line file viewer, summarised search, an edit command with a linter) against one change each. Read two lessons off it: more information is not better (the whole file, 12.7%, did worse than 100 lines, 18.0%), and a guardrail, a check inside the tool that refuses a bad action and says why, pays for itself (without the linter, 15.0%; with no edit command at all, shell only, 10.3%).
| Interface choice | Resolved | Change against the default |
|---|---|---|
| Default SWE-agent: file viewer of 100 lines, summarised search, edit command with a linter | 18.0% | |
| Edit command without the linter (syntax errors are accepted) | 15.0% | -3.0 points |
| No edit command at all (shell only) | 10.3% | -7.7 |
| Viewer shows 30 lines | 14.3% | -3.7 |
| Viewer shows the whole file | 12.7% | -5.3 |
| Iterative search (one result at a time) | 12.0% | -6.0 |
| No search command | 15.7% | -2.3 |
Anthropic's account of its SWE-bench agent (Erik Schluntz; dated 6 Jan 2025) adds poka-yoke, making mistakes impossible: "Sometimes models could mess up relative file paths after the agent had moved out of the root directory. To prevent this, we simply made the tool always require an absolute path." Of the edit strategies it tried, string replacement (old_str to new_str, failing when the old text occurs zero or several times) had "the highest reliability" (Raising the bar on SWE-bench Verified) SOURCE.
strict: true, OpenAI strict) guarantee arguments that parse; they cannot guarantee arguments that make sense.Every edit in the Edit format bench whose first attempt could not be applied was retried three times from the same first reply, each with a different error: terse ("Edit failed."), native (the applier's own words, such as git apply's "corrupt patch at line 8"), and instructive (a diagnosis our harness computes, such as "the hunk header says 4 old lines but the body has 5").
git apply's "corrupt patch at line 8", Codex's "Failed to find expected lines", Aider's SearchReplaceNoExactMatch report. Instructive: the hunk header says 4 old lines but the body has 5, the old lines start at line 12 not 13; the @@ line is itself one of the removed lines; the closest lines in the file with numbers; the file uses CRLF line endings.git apply's "corrupt patch at line 8" is written for a person who will open the patch in an editor; the model, given only that, resent the same broken patch. Some failures no wording fixes: a model that cannot see the carriage returns of a CRLF file cannot type them either, so the fix belongs in the tool (match lines without their line endings, as Codex's patch tool does) rather than in the message.Failed edits repaired by one retry, of 13, by wording: terse 1, native 3, instructive 4. Claude Haiku 4.5 with thinking off, through claude -p MEASURED. Small numbers: read them as a direction, not a rate.
A coding agent spends most of its effort deciding what to change; the edit format is how it writes that change so a program, the applier, can apply it. The format fails mechanically: an edit can be right in intent and still refused because a line number is off by one, or applied in the wrong place because the text it searched for appears twice.
The bench. Thirteen fixed edits on six small files, each requested in all five formats, one model call per (edit, format), applied by the format's own applier and checked by a test that also fails if anything else in the file changed; an applier error is sent back once for a retry. Every reply and verdict: the Edit format bench tab.
Fig. 2, step by step MEASURED (Claude Haiku 4.5, thinking off, unless named)
edit_file work this way. Correct at the first attempt: Haiku 13 of 13, Sonnet 12 of 13.git apply as "corrupt patch": the hunk headers announced 4 old lines where the body had 5, or started a line too early. The changes themselves were right: git apply --recount and Aider's applier (which ignores line numbers) applied 12 of the 13. Sent git's message back, the model mostly resent the same header.limit=10 to limit=20 at the end of the 141-line report module took 1,409 output tokens as a whole file and 51 to 155 in the other formats (first attempts). On a long file every rewrite is a chance to drop a line; on the CRLF file the whole-file reply applied, changed the constant and silently converted every line ending to LF.git apply refused almost all of them. Leniency turns refusals into silent mistakes when the model is weak, which is why the check after the edit matters more than the applier.The five formats the bench compares, as each tool documents them:
edit_file. Fails loudly on a typo or an ambiguous match; cannot land in the wrong place.<<<<<<< SEARCH, =======, >>>>>>> REPLACE. No JSON escaping of code; Aider's applier forgives some whitespace and uses the first match.diff -u and git diff write: hunks with line numbers and counts in @@ -a,b +c,d @@ headers. Familiar from training data; the numbers are where models slip.*** Begin Patch, *** Update File:, hunks anchored by an optional @@ line and context, no line numbers. Forgiving matcher (exact, then ignoring trailing or all surrounding whitespace); the first match wins.Across models MEASURED:
git apply instead of 4 and spent 76,771 output tokens on them, thinking included, against 2,634 without thinking: it counted lines at length and still got most headers wrong.git apply took in 11 of 13 cases, against Haiku's 4, which is why a harness that serves several models (Aider does) chooses the format per model.*** End Patch line, unprefixed lines inside a hunk).@@ line (@@ def export_rows(sales, limit=10):, then -def export_rows(sales, limit=10):). Codex searches for the hunk only after the @@ line, so the line to remove can never be found.INCH_TO_CM = 2.5 plus its newline did not match 2.5\r\n; the unified diff failed the same way; the whole-file reply applied, changed the constant and silently converted every line ending to LF (the check caught it). Exact replace succeeded because Haiku's old string had no newline; Sonnet's included one ("INCH_TO_CM = 2.5\n") and was refused until the retry. Only apply_patch, which compares lines without their endings and writes the file's own ending, passed at the first attempt in all three Claude runs.Aider reported that switching GPT-4 Turbo from SEARCH/REPLACE to its own line-number-free unified diffs raised its "laziness" benchmark score from 20% to 61%, and that disabling its flexible patching gave "a 9X increase in editing errors" (Unified diffs make GPT-4 Turbo 3X less lazy, 21 Dec 2023) SOURCE. Both point the same way as the bench's appliers table: the applier's tolerance matters as much as the format. Aider's edit formats page lists six formats and its leaderboards record which one each model is run with.
Which harness ships which format, and its applier read from source (Codex's apply_patch, Aider's edit coders, opencode's nine edit matchers), is on Other coding harnesses.
A harness never crashes on a bad turn and never hides one. Each failure is either turned into an observation the model can act on, or, if it is the infrastructure's fault rather than the model's, retried quietly and kept out of both the transcript and the score. The difficulty is telling the two apart, and noticing some failures at all.
| What went wrong | How the harness notices | What it should do | Seen on this page |
|---|---|---|---|
| The call is not valid JSON, or names no tool | parse error; on mlx-lm the call simply vanishes (empty reply) | say so as the next message; count it toward a malformed-reply cap | section 1; local model in the Edit format bench ("no edit_file tool call") |
| Unknown tool, missing or wrong-typed argument | validation before running | an error result that lists the valid tools or the schema; strict schemas remove most of these | native.py run_one() |
| The tool ran and failed | exit code, exception | a result with the exit code and the relevant lines first, is_error: true | parent page: command not found: python, fixed on the next call |
| The edit did not apply | the applier refuses | an instructive error and one retry; never a silent partial apply | section 5 and the bench |
| The edit applied but is wrong | only a verifier (tests) can tell | run the verifier after edits and before accepting "done" | bench (amber cells), section 10 |
The reply was cut at max_tokens | finish_reason: "length" / stop_reason: "max_tokens" | not a stop: retry with a higher limit, or ask for a shorter reply; never execute a half-written call | section 10, run naive_t0 |
| An empty reply | no text, no call | a new user message asking it to continue (Anthropic's advice for empty end_turn replies after tool results) | native.py careful rule |
| Permission denied | the gate | an observation saying why, so the model can choose another way | parent page, Loop lab step 3 |
| The server failed (dropped connection, overload such as a 529, out of memory) | HTTP error, a stream error event | retry with back-off outside the loop; do not show it to the model; do not score it | the shared local server ran out of GPU memory ("[METAL] ... Insufficient Memory") three times while several clients used it and had to be restarted; our runners retried the dropped requests and scored nothing from them |
Retry budgets. Every retry needs a ceiling: errors in a row (the Loop lab ended a run after three malformed replies), retries per edit (one in our bench), and the run's overall caps (section 10). Anthropic's docs describe Claude's own behaviour with invalid tool calls: it "will retry 2-3 times with corrections before apologizing to the user" (Handle tool calls). Retrying the infrastructure belongs in the client or a gateway; the frameworks root's Production stack tab measures LiteLLM's retry and fallback rules.
Edits refused by the applier at the first attempt that were correct after the applier's own error was sent back once, all formats together MEASURED: Haiku 4.5 3 of 13 (thinking off) and 6 of 11 (thinking on), Sonnet 5.5 3 of 6, Qwen3 4B 2 of 24.
On a task of five or seven turns, like the running example, the loop needs no plan: native.py has none, and nothing on this page measures one. On long tasks two failures grow: steps drift out of view as the transcript grows, and the model declares victory early. Harnesses answer with two patterns, both built from parts this page already has (a tool, a gate, a verifier), not from a special model ability.
todo_write(items) that changes nothing outside the transcript: the harness stores the list and returns it as the result, so the plan stays in recent context and the person watching has something to supervise. The model ticks items off by calling it again. After compaction (Context engineering), the harness re-inserts the current list.How Claude Code implements plan mode and its todo list, with recorded runs: Claude Code, taken apart.
Illustrative. Left: a plan phase whose tool set is read-only, ending at a person's approval, then the act phase with every tool. Right: a todo tool whose only effect is its result, the current checklist, which therefore sits near the end of the transcript on every later turn.
Every tool call runs somewhere, with somebody's rights. Whatever the isolation, the harness owns five things on every call, and native.py shows each in a line or two:
cwd set to the repository.inside() resolves a path to its real location and refuses anything outside the repository, so ../ and symlinks cannot escape (the poka-yoke of section 5, also a safety line).PYTHONDONTWRITEBYTECODE=1 keeps __pycache__ out of what the model sees; for evaluation every run must start from the same repository state, or runs stop being comparable (section 12).At the far end, the host runs nothing at all. In Qwenputer a compiler writes a RISC-V CPU into 11 extra layers in front of Qwen3.5-4B; Qwen writes an ordinary tool call, and the response tokens are predicted by those compiled layers, so the host executes no tool (it still needs a custom decoding driver to boot the CPU and route its trace tokens). A demonstration, not a design to copy.
The security analysis of each layer (what the sandbox lets through, egress control, prompt injection) is Agent security's; how namespaces and seccomp work is Containers and isolation's. For training and evaluation the environment is part of the measurement: Harnesses for training and evaluation runs its hidden verifier in a fresh container with no network.
Where a bad command is contained, from none to a machine you can throw away. A permission gate decides what may start; it does not contain what runs. An OS sandbox wraps each command (Claude Code's optional sandbox uses Seatbelt on macOS and bubblewrap on Linux); a container or virtual machine contains the whole session, and a cloud agent returns a branch or pull request for review instead of edits you watch. The trade, not measured here: each step out costs start-up time and copies of files and credentials, and tools the model expects may be missing inside.
The textbook loop stops when the model replies without a tool call. That means "the model thinks it is done", which is not "the task is done", and it is not even always the model's signal: a reply cut off by the output limit or emptied by a parser failure also has no tool call. The opposite failure, never stopping, needs limits the model cannot argue with.
end_turn / no tool calls. Necessary, not sufficient. Check the finish reason first: length, max_tokens, model_context_window_exceeded ("treat the response as truncated"), refusal and pause_turn ("send the response back as-is") are not completions (Handling stop reasons).The experiment. Sixteen runs of native.py on the running example with the local model, under three stop rules: naive (any reply without a tool call ends the run: the parent page's loop and most tutorials), careful (a reply cut at the output limit, finish_reason: "length", or an empty reply is not a stop: the harness says so and calls again) and verify (careful, and before accepting a stop the harness runs the tests itself; if they fail it shows the output and continues, at most three times). Five seeds at temperature 0.7 per rule, plus one run at temperature 0; each logged after every turn whether the tests passed, so any rule can be replayed MEASURED.
Fig. 3, step by step
The same seed was sent with each rule so the runs would be identical until the rule mattered. Pick a pair and step through it yourself: each box is a turn, with its tool calls or the reply that ended the run, a green edge when the tests passed after that turn and red when they failed. "Seed 4" shows the verifier rescue a run, "Seed 2" shows it spend three nudges and still fail, and "Temperature 0" shows the naive rule stopping on a truncated reply.
Fig. 3 replayed one rule, a cap of 5 turns. Try the others: a token budget for the whole run, or a detector that stops a run when the same call (same tool, same arguments) is asked for a third time. A stricter rule can only cut a run earlier, so its outcome is read from the record at the cut; rules that would let a run go on longer cannot be replayed. Each box on the right is one run and each cell one turn: green when the tests passed after that turn, red when they failed, dashed where the replayed rule cut the run.
finished, max_turns, budget, stuck), and keep the transcript so a capped run can be resumed rather than restarted. Replay your own logs under candidate rules, as above, before choosing the numbers.A product reports why it stopped. Claude Code ended a --max-budget-usd 0.01 run at $0.0118, because the budget is checked after a call has been paid for (details below).
Claude Code with --max-turns 3 ended with subtype: "error_max_turns" after running three tool calls whose last result the model never saw; with --max-budget-usd 0.01 it ended with "error_max_budget_usd" at $0.0118, because the budget is checked after a call has been paid for, and the tool call that call asked for was never run (claude -p 2.1.289, Haiku 4.5, recorded 6 Oct 2026 MEASURED). Claude Code, taken apart recorded the same limits on 2.1.290 (its section 9: the budget stop overshot by one call, and result.usage then missed that call).
| Run | Rule | Turns | Why it stopped | Tests at the end | Tokens |
|---|
Click a run for every turn, its calls and results.
Per-rule counts are fragile. With five seeds each, one run moves a rule by a fifth, and careful's seed 4 failed for a reason unrelated to its rule: it diverged from the naive run at turn 3, before any rule acted, because the shared server batched our requests with other clients' and batched arithmetic is not bit-identical. Compare tokens, not seconds: the machine was swapping under other work.
The same seed was sent with each rule so the runs would be identical until the rule mattered; seed 4 shows they were not always. Local model: Qwen3 4B Instruct 2507, 4-bit, mlx-lm 0.32.0 on an Apple M1 Pro; output limit 1,024 tokens per reply.
A model call reads its whole prompt again every turn: the system prompt, every tool definition, the task, every earlier reply and every result. So the cost of a run grows faster than its length, and most levers either cut round trips, cut what each one carries, or stop paying for turns that teach nothing.
Prompt tokens of the five calls of run careful_s1, by kind, from the model's own template and tokenizer MEASURED: 486, 865, 926, 1,252 and 1,531, so the run read 5,060 prompt tokens to do five turns of work derived. The four tool definitions are 299 tokens on every call, 1,495 of the 5,060 (about 30%). These are a 4B model's prompts with four tools; the parent page's Trace and context lab shows Claude Code's first call reading 13,000 tokens before any file.
| Lever | What it saves | Measured on this page | § |
|---|---|---|---|
| Batch independent calls | round trips, each a full re-read | Sonnet batched in 9 of 29 replies, Haiku in 7 of 91 | 3 |
| Execute a call when its block closes | latency | the first Edit ran 0.78 s before the reply was complete | 4 |
| Small edits, not whole files | output tokens | 1,409 tokens as a whole file against 51 to 155 | 6 |
| Thinking off for mechanical steps | output tokens | 76,771 against 2,634 tokens for 6 against 4 diffs applied | 6 |
| Cap verifier nudges and turns | whole turns | 36,177 against 9,544 tokens, same seed, still failing | 10 |
| Check the budget before each call | the overshoot | Claude Code stopped at $0.0118 on a $0.01 cap | 10 |
| Keep the prompt prefix byte-stable | prompt-cache hits | re-rendering changed token 486 between calls 1 and 2 | 1 |
What prompt caching saves, and how window budgets and compaction keep the prompt small: Context engineering (its section 2). Wall-clock latency of the local runs is not reported: the shared server was batching other agents' requests, so seconds were not comparable; tokens are.
A harness is a program, and its decisions can be tested like one: hold the model fixed and change one decision at a time. Every comparison on this page has that shape, and the same decision can rank differently on another model:
How big is the harness effect? On ordinary tasks, mostly the bill: Arena's HarnessTax study (16 Sep 2026) ran seven models in three harnesses (Claude Code, Codex CLI and Pi, a minimal four-tool harness) on 30 tasks each; the harness moved success by about ±2 points on SWE-bench Lite and ±5 on Terminal-Bench 2.0, while Claude Code cost about 2.0× Pi on SWE-bench Lite (HarnessTax, as checked on Agentic benchmarks) SOURCE. On a small model, much more: Harnesses for training and evaluation found the harness moved a 4B model's success a lot and Claude Haiku's little, while Haiku's input tokens per rollout varied several-fold across harnesses (its Scaffold experiment tab). Scores published for a model are scores for a model in a harness: the parent page's section 7 and Coding benchmarks cover reading them.
Share of edits correct at the first attempt, per format, for each model on the same bench and appliers MEASURED: Haiku 4.5 (thinking off) 13, 12, 4, 12 and 10 of 13 for exact replace, SEARCH/REPLACE, unified diff, whole file and apply_patch; Sonnet 5.5 12, 12, 11, 12 and 11 of 13; Qwen3 4B 4, 5, 1, 7 and 1 of 10. A harness tuned on one model is not tuned for another.
src/harness/native.py is 205 lines of standard-library Python (166 without comments and blank lines) and contains most decisions on this page. Read top to bottom, it is the checklist:
| Part of native.py | Decision | § |
|---|---|---|
TOOLS: four JSON-schema definitions | few tools, descriptions that say what the result looks like ("The first line is the exit code"), exact replacement for edits | 1, 5, 6 |
post() with urllib | the request is plain JSON you can log and replay; the provider renders it | 1 |
| the finish-reason checks | a reply without a tool call is a stop only if it is not truncated and not empty | 2, 7, 10 |
run_one() | parse, validate, gate, execute; every failure becomes an observation | 5, 7 |
| the batch rule | read-only batches run concurrently; anything else in order; one result per call, in call order | 3 |
RULES and check() | the Loop lab's permission gate; nobody to ask means deny | parent page, step 3; Agent security |
inside(), cwd, timeout=60 | the execution environment's fences | 9 |
--stop-rule verify | the harness runs the tests before accepting "done", at most three times | 10 |
--max-turns, the token count in every log line | hard caps, and the data to choose them | 10, 11 |
log(): one JSON line per turn | the trajectory, which every number on this page was computed from | 12 |
What it leaves out, on purpose. Context management (clipping, masking and compaction for longer tasks: Context engineering, its section 4), a sandbox (the gate decides what may start; it does not contain what runs: section 9), planning tools (section 8), streaming and interrupts (section 4), retries for a flaky server (section 7), and prompt caching (the parent page's Loop lab shows what one growing text block costs; a native-call harness keeps the system prompt and tools byte-identical at the front of every request). For libraries that give you the loop ready-made (LangGraph, Pydantic AI, the OpenAI Agents SDK, the Claude Agent SDK and others), see Topic: agentic-frameworks.
Answer aloud first, then open.
<tool_call>, a JSON object with name and arguments, </tool_call>, then the end-of-turn token. The server stops at that token, parses the JSON and returns a structured call. Results go back as text (a user turn of <tool_response> blocks for Qwen3).Sources are linked where each fact is used. Recordings: Claude Code CLI 2.1.289 (and the Claude Agent SDK 0.2.163 with its bundled 2.1.286) on a Claude subscription, and a local model served by mlx-lm 0.32.0, all run on 6 October 2026; the parent page's recordings are from 5 October. Redacted copies are in this page's source (src/recordings/), with the harness and bench code that made them.
An agent changes code by writing an edit in some format that the harness then applies. This bench fixes everything except the format: thirteen edit requests on six small files (the running example's two bugs, a 69-line inventory module, a 141-line report module, a Makefile, a JSON config and a file with Windows line endings), each asked for in five formats, one request per (edit, format), applied by that format's own applier and checked by a test that also fails if anything else in the file changed MEASURED. When the applier reports an error, the harness sends it back once and asks again, as a real loop would. A reply that applies but is wrong gets no retry: the applier cannot know. The local model ran the ten edits outside the 141-line report module: the shared server was producing a few tokens a second under other jobs' load, and a whole-file reply of that module would have taken many minutes.
Green: applied and correct. Amber: applied, but the check failed (wrong edit, or something else in the file changed). Red: the applier refused it. Dashed green: refused at first, correct after the error was sent back. Click a cell for the request, the reply and every applier's verdict. The controls replay the run cell by cell; it opens on the full matrix and moves only when you move it.
Bar: share of the 13 edits correct at the first attempt (solid) and after one retry (light). Right: correct first and after retry, out of 13. Below each model, the median number of output tokens per reply.
A format is a contract between the model and an applier, and appliers differ in how forgiving they are. Every unified-diff reply was applied three ways (git apply, git apply --recount, which ignores the line counts in hunk headers, and Aider's udiff applier, which ignores line numbers and treats each hunk as a search and replace), and every SEARCH/REPLACE reply two ways (exact match, and Aider 0.86.2's own do_replace with its whitespace-tolerant fallbacks).
edit_file tool; Claude got the same JSON schema through claude -p --json-schema, which turns it into a tool named StructuredOutput), Aider's SEARCH/REPLACE blocks, a standard unified diff, the whole file in a fence, and Codex's apply_patch envelope. Appliers: our exact replace (each old string must occur once), Aider 0.86.2's own parser and appliers (from its PyPI wheel), git apply, and a Python port of Codex's apply_patch (openai/codex at commit 8b6bb1c, 6 Oct 2026: exact, then trailing-whitespace, then whitespace-insensitive matching, first match wins). The harness reads and writes files as raw bytes, so CRLF endings survive unless a reply drops them; note that Aider itself reads files in text mode and writes them with the platform's line ending by default (--line-endings platform), which would turn the CRLF file into LF on macOS. Code: src/editbench/.Links checked on 6 October 2026; the HarnessTax and long-running-harness links were added on 24 October 2026 from the pages that cite them. Times are estimates for a careful read.
Thirteen edits in five formats, for Claude Haiku (with and without thinking), Claude Sonnet and a 4B local model, with every reply and verdict. About 25 min.
The root: the agent loop from zero. Tabs: Loop lab (a harness in seven recorded steps, the text-protocol loop this page starts from), Trace and context lab, Harness atlas. Reading 21 min, plus 3 in closed details.
How the reference harness implements the loop, tools, permissions, hooks, memory, subagents and headless runs, in 23 recordings. Tab: Recordings; the permission grid is in Reading section 3. Reading 37 min, plus 24 in closed details.
Window budgets, caching, tool-output policies, compaction, memory files, subagents. Its former labs now sit beside the claims they prove: cache placement in section 2, real compactions in section 4, the needle grid in section 9. Reading 35 min, plus 25 in closed details.
Permission gates, OS sandboxes, defences against prompt injection, egress control. The trifecta design tool is in section 1, every gate decision in section 4. Reading 28 min, plus 3 in closed details.
Six harnesses read from source, including their edit formats and appliers, and run on one task. Tab: Same task, every harness; Aider's repository map is in section 5. Reading 26 min, plus 22 in closed details.
Resident, message-driven agents: queues, heartbeats, memory and the trust boundary. Tab: A day, replayed; the gate designer is in section 6. Reading 32 min, plus 29 in closed details.
Scaffold sensitivity, harnesses as RL environments, trajectories as data. Tabs: Scaffold experiment, Environment lab; rollouts to a dataset and self-improving harnesses are Reading sections 6 and 7. Reading 33 min, plus 16 in closed details.
Libraries that give you the loop: the same agent built six ways, orchestration, gateways (retries and fallbacks), tracing. About 28 min.
Namespaces, cgroups, seccomp: what a sandbox or container actually contains (section 9). About 51 min.
How tools from outside the harness are discovered and called on the wire. About 37 min.
Terminal-Bench, tau2, OSWorld and the harness-tax evidence, with what each score includes. About 40 min.
SWE-bench and why a score needs its scaffold column. About 34 min.
Grading trajectories like the logs this page is built from. About 30 min.
The paper the agent loop descends from. About 21 min.
How models are post-trained (supervised fine-tuning, preference tuning, RL): the stage where formats such as tool calls are learned. Reading 26 min, plus 22 in closed details.
Yang et al., May 2024: the ACI and its ablations (viewer size, search, linting). 45 min.
Anthropic: a minimal scaffold, the edit tool, poka-yoke tools. 15 min.
Anthropic, 11 Sep 2025: tool design and evaluating tools with agents. 20 min.
Anthropic, 26 Nov 2025: initializer agent, progress log and feature list across sessions (section 8). 25 min.
16 Sep 2026: seven models in three harnesses; the harness moves the bill more than the score (section 12). 12 min.
Dan Luu, 7 Sep 2026, our article page: what an agent's self-written tests miss, the case for a held-out verifier (section 10). Reading 23 min, plus 5 in closed details.
Our article page: a RISC-V CPU compiled into extra layers of Qwen3.5-4B answers Qwen's own tool calls, with a driver in the loop (section 9). Reading 21 min, plus 3 in closed details.
Defining tools, handling calls and errors, parallel tool use, streaming, stop reasons. 40 min.
Tool definitions, strict mode, parallel calls, streaming events. 25 min.
Six formats and when Aider uses each; with Unified diffs make GPT-4 Turbo 3X less lazy. 25 min.
The patch grammar, its lenient parser and the fuzzy line matcher this page ported. 30 min.
The local server: server.py and tool_parsers/ show how a template's tool calls are parsed. 30 min.
The model card and the chat template with its tool-call format. 10 min.