Building a harness: the loop, tool calling, edit formats, stop conditions

How to write the program around a model: how a tool call travels, where the model's turn must end, tool and error design, edit formats, recovery, planning, the execution environment, when to stop, what it costs, and how to measure a harness rather than the model. Every number is from runs recorded on 6 October 2026 or a dated source. Reading: 41 min, plus 20 in closed details. Data as of October 2026.
The idea in one sentenceA harness is a loop that sends the model a request, lets its turn end exactly at the action it asks for, runs that action somewhere safe, hands back a result the model can act on, and stops only when the work is verified or a limit is hit; every engineering decision is one of those steps, and each fails in a way you can measure.

Fig. 1, step by step: every decision on this page sits on one turn of the loop

  1. Send the request. The harness sends the system prompt, the tool definitions and the whole history, and the model reads all of it on every call: 486 tokens on call 1 of the recorded run, of which 299 are the four tool definitions (§1, §11).
  2. The model writes a tool call. To the model a call is just tokens: 46 generated tokens holding two <tool_call> blocks, one per file it wants to read (§1).
  3. The turn ends at the action. <|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).
  4. Parse and validate the calls. The server cuts out the text between the tags and parses it into typed tool_calls; a malformed call can vanish inside the server and look like "done" (§1, §7).
  5. Gate, then run the calls. Both calls are read-only, so they run side by side; anything else runs in order. Every call runs in the repository with paths fenced and a 60-second timeout (§3, §4, §9).
  6. Return results it can act on. The two results go back as one user turn, in call order, and the next prompt is 865 tokens. How a result is worded matters: "Edit failed." repaired 1 of 13 failed edits, a computed diagnosis 4 (§5, §6, §7).
  7. Go round again, then stop. Calls 3 to 5 read 926, 1,252 and 1,531 tokens, the tool definitions again each time; the fifth reply has no tool call. Stop only when a verifier agrees or a cap is hit: stopping on the model's word left a test failing in 4 of 16 runs (§10, §11).

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).

Native tool calling: tools sent as JSON Schema in the request, calls returned as typed data, not parsed from prose.
Action boundary: the point where the model's turn must end, right after it asks for an action.
Agent-computer interface (ACI): tools, their results and errors, designed for a model as the user.
Edit format and applier: how the model writes a code change, and the program that applies it.
Verifier: a check the harness runs itself (tests, a build) before it accepts "done".
Stop rule: what ends the loop: the model's own stop, a verifier, a cap or a loop detector.

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.

DecisionA default that worksWhat the recordings showed§
How the model asks for an actionThe 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 server1
Where the model's turn endsAt its action: the API's tool-use stop, the end-of-turn token, or a stop sequenceLet 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 samples2
Several calls at onceRead-only batches concurrently, anything else in order, results in call order in one messageSonnet batched calls in 9 of 29 replies, Haiku in 7 of 91; the local model batched an edit with the test run 13 times3
Streaming and interruptsParse arguments at the block's end; give every pending call a result when interruptedClaude Code ran a first edit 0.78 s before the second had finished streaming; on interrupt it wrote a "tool use was rejected" result itself4
Tool design and errorsFew tools, verdict first, errors that say what to changeRetrying failed edits: "Edit failed." fixed 1 of 13, the tools' own messages 3, a computed diagnosis 45
Edit formatExact string replacement as a tool call; lenient appliers for diffsHaiku: 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 change6
Recovering from errorsEvery failure becomes an observation, except infrastructure failures, which are retried out of sightA truncated reply, an empty reply and a dropped server connection all occurred in these runs7
PlanningA todo tool for long tasks; a read-only plan phase when a person must approveNot measured here; published designs only8
Where tools runA working directory, a timeout and output capture on every call; isolation that grows with autonomynative.py: 60-second timeouts, paths resolved and refused outside the repository9
When to stopModel says done and a verifier agrees (one the agent did not write), or a hard cap; truncation is not done4 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 another10
Cost and latencyFewer round trips, small edits, budgets checked before each callEach call re-reads the whole prompt: 486 tokens on call 1, 1,531 on call 511
Is the harness any good?Fix the model, change one harness decision, repeat runs, report cost beside scoreThe edit-format ranking flips between Claude and a 4B model on the same harness12

One tool call, end to end, in tokens

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).

1. A tool call on the wire

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

  1. The harness sends JSON. Two messages (system, task) and four tool definitions, each a name, a description and a JSON Schema: read_file, run_tests, edit_file, run_command. Nothing here is text the model reads yet.
  2. The server renders the system turn. The chat template writes the system prompt, then "# Tools", the four definitions as JSON lines inside <tools></tools>, and the instruction to answer with <tool_call>{...}</tool_call>: 428 tokens, tools included. Blue tokens are special tokens (one id each).
  3. Then the task, and an open assistant turn. The user turn holds the task and the file list; the prompt ends with <|im_start|>assistant and a newline, inviting the model to speak. The prompt is 486 tokens, exactly what the server reported.
  4. The model generates two tool calls. Token by token: a newline, <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.
  5. <|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.
  6. The server parses the calls. mlx-lm cuts the text between the tags, runs json.loads on it and returns OpenAI-style tool_calls, 2 of them, with an id each. The harness never sees the tags.
  7. Results come back as a user turn. The harness runs both reads and appends two role 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.
A failure the client cannot see
mlx-lm 0.32.0 picks its tool parser from the template (here a plain 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).
The same call in three protocols: Anthropic, OpenAI, an open model's template
Anthropic Messages APIOpenAI (Responses / Chat Completions)Open model through its chat template (Qwen3)
Definitionstools: 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, strictJSON lines inside <tools> in the system turn, plus a format instruction
The calltool_use block: id, name, input objectfunction_call item (or tool_calls): call id, name, arguments as a JSON stringtext between <tool_call> tokens; the server parses it
How generation stopsstop_reason: "tool_use"finish_reason: "tool_calls"end-of-turn token <|im_end|> (an EOS id)
The resulttool_result blocks with tool_use_id, first in the next user message, is_error optionalfunction_call_output / role tool with the call idrole tool, rendered as a user turn of <tool_response> blocks; the ids are not rendered at all
Schema guaranteestrict: true (constrained decoding)strict: needs additionalProperties: false and every field requirednone 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 of five consecutive requests, by kind

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.

Re-rendering history is not always token-identical
Call 1 ended with <|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.

2. The action boundary: the turn must end at the call

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:

ProtocolWho ends the turn at the actionWhat 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 templateThe model, by writing its end-of-turn token, and the server, by stopping thereA 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 lineEverything, 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:

The surprise past the end-of-turn token
It did not invent a tool result (none of the 18 continuations contained a <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").
The rule
Enforce the boundary yourself whatever the model usually does (the provider's tool calls, the server's end-of-turn stop, or a stop sequence plus a cut at the first action) and never parse past it. A model that behaves on one route (the local model in a chat API) can misbehave on another (the same model on a raw endpoint, Haiku through a CLI without stop sequences): a model writing the other side's turn is a harness bug.

The local model stopped at its action in every chat sample, and wrote the user's next turn when let past its end token

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.

How the boundary experiment was run
Local model: Qwen3 4B Instruct 2507 (4-bit) on mlx-lm 0.32.0, temperature 0.7, seeds 1 to 5 per condition. Text protocol: the Loop lab's step-1 system prompt verbatim, sent through the chat endpoint, at turn 1 and at turn 2 (after a real read of 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.
The parent page's aborted mini-SWE-agent run, call by call (moved from its Harness atlas)

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.

CallInputOutputSecondsActions in replyRan
11,26419616.61ls -la
21,5045,48734.618, invented output(rejected)
31,66330815.11cat README.md && echo "---" && find . -type f -name "*.py" | head -20
41,8582,04016.311, invented output(rejected)
52,0172044.51python3 tests/test_core.py
636,18239,638323.317, invented output(rejected)
72,3129,90782.51, invented outputpython3 tests/test_core.py && echo "All tests passed successfully!"
82,7739,96265.24, invented output(rejected)
92,9321834.31cat tests/test_core.py
103,2875,63835.514, invented output(rejected)
113,4461,47814.12, 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.

3. Several tool calls in one reply

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.

The rule native.py uses
If every call in the batch is read-only (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).

The same harness sees very different batch sizes depending on the model

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.

Predict, then reveal: a batch of Read a.py, Edit a.py, Bash pytest where the Edit fails
Three results, in order: the Read's output; the Edit's error with an 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.

4. Streaming and interrupts

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).

Claude Code runs the first edit while the second is still streaming

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.

Stream details per provider

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:

Design rules that follow
Parse tool arguments only at the block's end (or with a partial-JSON parser for display). Execute a call when its block closes, not when the whole message does, if you want the latency win Claude Code gets, and keep the result order equal to the call order. On interrupt, give every pending call a result that says plainly it was not run (Anthropic's parallel-tool docs suggest 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).

What Claude Code writes when you interrupt it

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 ", ".

5. Designing tools for a model: the agent-computer interface

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):

Every interface choice SWE-agent removed or changed lowered the resolve rate

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%).

The ablation table
Interface choiceResolvedChange against the default
Default SWE-agent: file viewer of 100 lines, summarised search, edit command with a linter18.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 lines14.3%-3.7
Viewer shows the whole file12.7%-5.3
Iterative search (one result at a time)12.0%-6.0
No search command15.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.

Names and descriptionsThe model chooses a tool from its name and description alone. Anthropic's tool docs call detailed descriptions "by far the most important factor in tool performance" and suggest "at least 3-4 sentences" per tool; OpenAI's suggest keeping fewer than 20 functions available at once ("a soft suggestion"). Overlapping tools invite wrong choices and cost tokens on every call.
Arguments that cannot be wrongAbsolute paths; enums instead of free strings; one required field rather than three optional ones that conflict. Strict schemas (Anthropic strict: true, OpenAI strict) guarantee arguments that parse; they cannot guarantee arguments that make sense.
Results that lead with the verdictExit code and pass or fail on the first line, the informative lines next, a note of what was cut. The parent page's Loop lab measured what happens otherwise: the test results sat at lines 92 to 95 of about 240 and a head-and-tail clip removed them.
Errors that say what to doAnthropic: "Instead of generic errors like "failed", include what went wrong and what Claude should try next." Measured below.

Does the wording of an error change the outcome?

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").

The three wordings in full
Native: 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.
What to take from it
An error is the model's only view of what went wrong. 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.

A message that names the wrong number and the right one repaired the most failures

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.

6. Edit formats, measured

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)

  1. Exact replace. A tool call with an old string and a new one; the applier finds the old string, which must occur exactly once, and swaps it. Claude Code's Edit, Anthropic's text-editor tool and our edit_file work this way. Correct at the first attempt: Haiku 13 of 13, Sonnet 12 of 13.
  2. It fails loudly. If the old string occurs twice, or not at all, the applier refuses and says so: an error the model can act on, never an edit in the wrong place (the duplicate here is illustrative).
  3. Unified diff: the line numbers are where models slip. 9 of 13 diffs were refused by 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.
  4. Whole file: it cannot fail to apply, and pays in tokens. Changing 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.
  5. Lenient appliers apply wrong edits; only the check catches them. On the 4B model's diffs, Aider's forgiving udiff applier applied 8 of 10, but 6 of those 8 failed the check (wrong place, or other lines changed); 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:

Exact replaceA tool call with an old string and a new one; the old string must occur exactly once. Claude Code's Edit, Anthropic's text-editor tool, our edit_file. Fails loudly on a typo or an ambiguous match; cannot land in the wrong place.
SEARCH/REPLACE blocksAider's main format: the same idea as text between <<<<<<< SEARCH, =======, >>>>>>> REPLACE. No JSON escaping of code; Aider's applier forgives some whitespace and uses the first match.
Unified diffWhat 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.
Whole fileWrite the entire new file. Cannot fail to apply; costs output tokens in proportion to the file, and quietly loses whatever the model forgets or normalises.
apply_patchCodex's envelope: *** 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:

  • Thinking does not fix the counts. With thinking on (Claude Code's default), Haiku got 6 of the 13 diffs through 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.
  • The model matters as much as the format. Sonnet 5.5 (thinking off) wrote unified diffs that 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.
  • A small model ranks them the other way. Qwen3 4B (local, temperature 0, the ten edits on the short files) was correct at the first attempt in 7 of 10 whole-file replies, 5 of 10 SEARCH/REPLACE, 4 of 10 exact replacements, and 1 of 10 for both unified diffs and apply_patch: it broke the formats themselves (no filename line before a SEARCH block, a patch without its *** End Patch line, unprefixed lines inside a hunk).

Exact replace was the safest for Claude; the 4B model did best where it could not break the format

Two more failures: the patch anchor, Windows line endings
  • apply_patch, by the anchor. Twice the model put the line it was changing on the @@ 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.
  • Windows line endings. On the CRLF file, the SEARCH block 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.
What this suggests for your harness
Prefer exact replacement as a tool call for frontier models: the fewest failures for Claude here (Haiku 13 of 13; Sonnet 12 of 13, the miss being the CRLF file, fixed on the retry), and it fails safely (an error, never a wrong place). If you accept diffs, apply them the forgiving way (recount, or match hunks by content as Aider does) and never trust model-written line numbers. Match lines without their line endings and write back the file's own ending. Keep whole-file writes for new or very small files, or for a small model that cannot hold a format, with a check after every write. And measure on your own model (section 12).
Published context and which harness ships which format

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.

7. Error recovery: every way a turn can go wrong

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 wrongHow the harness noticesWhat it should doSeen on this page
The call is not valid JSON, or names no toolparse error; on mlx-lm the call simply vanishes (empty reply)say so as the next message; count it toward a malformed-reply capsection 1; local model in the Edit format bench ("no edit_file tool call")
Unknown tool, missing or wrong-typed argumentvalidation before runningan error result that lists the valid tools or the schema; strict schemas remove most of thesenative.py run_one()
The tool ran and failedexit code, exceptiona result with the exit code and the relevant lines first, is_error: trueparent page: command not found: python, fixed on the next call
The edit did not applythe applier refusesan instructive error and one retry; never a silent partial applysection 5 and the bench
The edit applied but is wrongonly a verifier (tests) can tellrun the verifier after edits and before accepting "done"bench (amber cells), section 10
The reply was cut at max_tokensfinish_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 callsection 10, run naive_t0
An empty replyno text, no calla new user message asking it to continue (Anthropic's advice for empty end_turn replies after tool results)native.py careful rule
Permission deniedthe gatean observation saying why, so the model can choose another wayparent page, Loop lab step 3
The server failed (dropped connection, overload such as a 529, out of memory)HTTP error, a stream error eventretry with back-off outside the loop; do not show it to the model; do not score itthe 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.

One retry with the applier's own error repaired a share of refusals for Claude and almost none for the 4B model

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.

8. Planning: a todo tool and a plan phase

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.

  • A todo tool. A tool such as 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.
  • Plan, then act. A phase in which the harness offers only read-only tools (read, search, run the tests) and ends when a person approves the plan; then all tools. Implement it as a switch of the tool list and a gate rule, not as a request in the prompt, so the model cannot edit during planning even if it wants to.
  • Across sessions. Past one context window the plan must live outside it. Anthropic's long-running harness (26 Nov 2025) has an initializer agent set up the environment, a progress log and a feature list with every feature initially marked failing; each later session reads them, implements one feature, tests it, commits and updates the log. It was built against premature completion and marking features done without proper testing (Effective harnesses for long-running agents) SOURCE. The feature list is a todo list the verifier, not the model, ticks.

How Claude Code implements plan mode and its todo list, with recorded runs: Claude Code, taken apart.

Planning is a tool set and a tool result, not a prompt

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.

9. The execution environment: where tools run

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:

  • A working directory: every command runs with cwd set to the repository.
  • Paths resolved and fenced: 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).
  • A timeout: 60 seconds per command or test run, so a hung process becomes an error result instead of a hung agent; an interrupt must also be able to kill it (section 4).
  • Captured output: standard output and error together, the exit code on the first line (the verdict first, section 5).
  • Hygiene: 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.

Isolation rises with autonomy: the more the agent may do unasked, the further out the boundary

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.

10. Stop conditions and budgets

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.

The model's own stopend_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).
A verifierBefore accepting "done", run the check yourself (the tests, a linter, a build) and, if it fails, show the output and continue. In Claude Code this is a Stop hook (Claude Code, taken apart, section 4); in native.py the "verify" rule. It must be a check the agent did not write: in Dan Luu's runs of a coding agent writing a Zstd decoder at xhigh effort, agents nearly always got their own tests to pass, while 14% to 31% of runs, depending on the prompt, still failed the hidden tests (How well do agents use test/verification techniques?). Hold the tests out, or have a person specify them.
Hard capsTurns, tokens, dollars, wall-clock time. Checked by the harness on every iteration, with the reason reported in a typed result, never by asking the model.
Loop detectorsThe same call with the same arguments asked for again and again; the same error several times in a row. Cheap to compute from the log; a hint that the model is stuck, not proof.

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

  1. Sixteen runs, turn by turn. One row per run, grouped by rule, one block per turn. A block's height is the prompt the model read on that turn (486 tokens on turn 1, up to 4,471 on the longest run's last), green when the tests passed after that turn, red when they failed. 11 of the 16 runs end with the tests passing.
  2. The naive rule ends runs that are not done. The model said it was done with a test still failing in 4 runs; in a 5th (temperature 0) its reply hit the 1,024-token output limit before any tool call, and the naive rule read the truncation as completion. The careful rule treats that truncation, and an empty reply, as an error to report back, not a stop.
  3. A verifier rescues some runs. Under the verify rule the harness runs the tests itself before accepting a stop; each glow is a nudge, the failing output shown to the model, after which the run goes on. Seed 4 was told the tests still failed and fixed the remaining bug by turn 7; seed 2 used all three nudges and still failed after 13 turns.
  4. ... and costs on others. Seed 2 under the verify rule ran 13 turns, spending 36,177 tokens against 9,544 for the same seed under the naive rule, and still failed. A cap on nudges is what ended it.
  5. A turn cap of 5, replayed on the record. Cut every run after turn 5 and read the tests at the cut: 10 of the 16 still pass, against 11 with no cap. The passing runs had fixed both bugs by turn 4 or 5, so the cap loses only the run that needed the verifier's extra turns. Caps lose exactly the runs still making progress, which is why a cap should be generous and the verifier strict, not the other way round.

Two runs of the same seed, side by side

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.

Replay a stricter rule on the record

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.

A stop policy that holds up
Stop when the model says it is done and the verifier agrees, or when a hard cap is reached, whichever comes first. Treat truncated and empty replies as errors, not stops. Check budgets before each model call (so a cap is never overshot by a whole call) and cap the number of verifier nudges. Return the reason as data (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).

Every run, turn by turn, and Claude Code's limit records

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).

RunRuleTurnsWhy it stoppedTests at the endTokens

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.

11. Cost and latency

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.

Each call re-reads everything before it; the tool definitions are paid on every call

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.

LeverWhat it savesMeasured on this page§
Batch independent callsround trips, each a full re-readSonnet batched in 9 of 29 replies, Haiku in 7 of 913
Execute a call when its block closeslatencythe first Edit ran 0.78 s before the reply was complete4
Small edits, not whole filesoutput tokens1,409 tokens as a whole file against 51 to 1556
Thinking off for mechanical stepsoutput tokens76,771 against 2,634 tokens for 6 against 4 diffs applied6
Cap verifier nudges and turnswhole turns36,177 against 9,544 tokens, same seed, still failing10
Check the budget before each callthe overshootClaude Code stopped at $0.0118 on a $0.01 cap10
Keep the prompt prefix byte-stableprompt-cache hitsre-rendering changed token 486 between calls 1 and 21

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.

12. Measuring a harness, not the model

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 to test a harness change
(1) Fix the model and its settings, change one decision (SWE-agent's Table 3 in section 5 is the template: removing the edit command took 18.0% to 10.3%). (2) Use fixed tasks with checks that also catch an edit that applied but is wrong. (3) Run each cell more than once: same-seed runs diverged here (section 10). (4) Report cost beside success, in tokens and dollars. (5) Keep tasks no prompt or tool change was tuned on. (6) Read the trajectories, not only the score: the per-turn log is what every number on this page was computed from (Agent and trajectory evaluation grades them).

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.

Same harness decision, opposite ranking: Claude did worst with diffs, the 4B model best with whole files

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.

Depth

The harness, assembled: native.py part by part

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.pyDecision§
TOOLS: four JSON-schema definitionsfew tools, descriptions that say what the result looks like ("The first line is the exit code"), exact replacement for edits1, 5, 6
post() with urllibthe request is plain JSON you can log and replay; the provider renders it1
the finish-reason checksa reply without a tool call is a stop only if it is not truncated and not empty2, 7, 10
run_one()parse, validate, gate, execute; every failure becomes an observation5, 7
the batch ruleread-only batches run concurrently; anything else in order; one result per call, in call order3
RULES and check()the Loop lab's permission gate; nobody to ask means denyparent page, step 3; Agent security
inside(), cwd, timeout=60the execution environment's fences9
--stop-rule verifythe harness runs the tests before accepting "done", at most three times10
--max-turns, the token count in every log linehard caps, and the data to choose them10, 11
log(): one JSON line per turnthe trajectory, which every number on this page was computed from12

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.

Interview rehearsal: eight questions

Answer aloud first, then open.

What does an open model actually generate when it "calls a tool"?
Ordinary tokens in a format it was trained on, bracketed by special tokens: for Qwen3, <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).
Why must the harness enforce the action boundary, and how?
Because a language model continues text: after an action, the likeliest continuation is an observation, so without a stop it writes one. Enforce it with the API's tool-use stop, the end-of-turn token for open models, or a stop sequence plus a cut at the first action for text protocols.
The model returns three tool calls. How do you execute them?
Classify them: independent read-only calls concurrently, writes and anything after a write sequentially in the given order; on a failure, mark later dependent calls "not executed"; return one result per call, in order, in a single message.
How would you implement an interrupt?
Cancel the stream, kill running tool processes, write a result for every pending call saying it was not run (Claude Code writes that the user rejected the tool use), append the user's new message, and continue the same session.
Which edit format would you choose, and how would you decide?
Exact string replacement as a tool call for strong models (fails safely, cheap), with lenient diff application if a model prefers diffs; then measure on a fixed set of edits with checks, including traps such as duplicated text, CRLF files and long files, and count refusals, wrong applies and tokens.
What makes a good tool error message?
It names what was wrong in the input the model wrote, gives the fact needed to fix it (the actual line number, the closest matching lines, the valid values), and says what to do next. It leads with that, and is short.
Design the stop conditions for a coding agent.
Model says done and the verifier passes; hard caps on turns, tokens, dollars and time checked before each call; truncation and empty replies treated as errors; a loop detector; a cap on verifier nudges; the reason returned as data; the transcript kept for resumption.
Your agent's success rate dropped after you switched to a cheaper model. Where do you look first?
The trajectories: edit refusals per format, malformed calls, truncations and early stops. A smaller model often fails mechanically before it fails at reasoning: here the 4B model broke the diff and patch formats that Claude handled, and did best rewriting whole files. The fix may be a different format per model plus a check after every edit, not a bigger model.

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.