Agent harness: model + harness = agent
A model reads text and writes text; on its own it can't open a file or run a test. The agent you use is that model inside a harness: a loop that gives it tools, runs what it asks for under rules, and keeps its context. Watch one fix a small bug, then change the rules and the window and see what changes.
What you'll take away
- Explain the loop that makes a model an agent: call a tool, add the result, ask again
- Set allow, ask or deny per tool, and know a rule isn't a security wall
- Know what compaction keeps and drops when the context window fills up
- Spot why the same model does better in one harness than another
The 1-minute version
Tap a point and the picture below plays that step.
Youtest_add fails. Find out why and fix it.
The model is the same every time; only the harness changes. Watch how often it asks you, and whether your folder changes
An agent asks for the tests to be run, and the result comes back. Who actually ran them?
The picture: the model hall stands in the middle and the harness is the ring road round it. Each lap the context leaves the glass warehouse for the hall, the model writes a call (tiles on its roof), the harness reads it where the drive meets the ring, and the rule gate lights green (allow), amber (ask) or red (deny). The shell shop runs the tests (two lamps on its roof), the files shop holds your project, and the result rides back as a light into the warehouse, whose slabs are the context; the dashed line is three quarters of the window, and compaction squeezes old slabs into one gold summary. Your terminal, or a plain chat when there is no harness, is on the left (under the picture on a phone). The model is a stand-in written as rules, not a real model; the tools really run on the two-file project in harness.py below. The counts are words standing in for tokens, teaching numbers: real models count tokens, with far larger windows.
Compare them all: Agent harness
The same model and the same task (test_add fails, fix it) in four common kinds of harness. See which tools each gives, how often it asks you, and where the work ends up.
Use it when Questions, explanations, a second look at code you paste in
Skip it when Work that needs your files or a test run: you become the harness, copying back and forth each round
The model is a stand-in written as rules, not a real model; the tools really run on harness.py's toy project. The four are general shapes, not any one product; the allow / ask / deny rules and the sandbox follow the docs of coding agents such as Claude Code and Codex. Press any tile to see it large above, with when it fits.
Four harnesses, one model
| Harness | Tools it gives | Asks you before | Where it works | Ends with |
|---|---|---|---|---|
| Chat, no tools | none | nothing | nothing runs | advice; you make the fix |
| Editor assistant that asks | run_tests, read_file, edit_file | run_tests, edit_file | in your folder | the fix, made in your folder |
| Terminal agent with rules | run_tests, read_file, edit_file | edit_file | in your folder | the fix, made in your folder |
| Background agent in a sandbox | run_tests, read_file, edit_file, open_pr | nothing | in a copy (sandbox) | a pull request for you to review |
The loop
Given a list of tools, a model can reply with a request to call one, with the arguments, and stop; it never runs anything itself. The harness does the rest: it builds the context (a system prompt, the tools and their descriptions, your task), sends it, runs the tool the model asked for, adds the call and its result to the context, and sends it again, until the model replies without a call. Anthropic's Building effective agents describes agents as models using tools based on feedback from their environment, in a loop, and both Anthropic's tool use docs and OpenAI's function calling guide leave running the tool to your code. Some tools come with the harness (read a file, run a command); others come from outside through MCP, an open standard for connecting AI applications to other systems.
Context and compaction
Everything the model knows about the job is in the context: the system prompt, the tools, your task, every call and every result. The window has a fixed size, and Anthropic's Effective context engineering notes that a model recalls what is in it less accurately as it grows. Near the limit, a harness compacts: the model summarises the work so far, keeping decisions, unresolved bugs and details it still needs, and the harness starts a fresh context from that summary. In the picture the harness compacts at three quarters of the window.
Rules: allow, ask, deny
Before it runs a call, the harness checks the tool's rule: allow runs it, ask stops and asks you, deny refuses and tells the model. Claude Code, for example, reads without asking, asks before commands and edits by default, and checks deny rules first, then ask, then allow; Codex has read-only, workspace-write and full-access modes, with the network off by default when it writes to the workspace. A rule matches a command's text, so it is a convenience more than a wall: Claude Code's docs say a command rule isn't a security boundary. For an agent left to act alone, the wall is a sandbox, a container or a VM.
Same model, other harness
Put one model in the four harnesses above and four different things happen: advice you act on yourself, a fix you approve step by step, a fix with one question, a pull request made in a copy. What changed is what the harness gives the model, what it lets run, and what it keeps in the context. Anthropic found the same building its SWE-bench agent: it spent more time on the tools than on the prompt, and once a file tool required absolute paths, the model stopped making path mistakes. When an agent does well or badly, look at the harness as well as the model.
In real code
# A toy agent harness. The "model" is a stand-in written as plain rules (no real model, no network, no key): it reads
# the context and either calls a tool or answers. Everything else is the harness: the loop, real tools on a project in
# a temporary folder, a permission rule per tool (allow / ask / deny), a context window counted in words, and
# compaction when the window is three quarters full. The same stand-in behaves differently in each setup below.
# Run: python3 harness.py
import difflib
import shutil
import sys
import tempfile
import traceback
import types
from pathlib import Path
SYSTEM = "You are a coding agent working in a project folder. Look before you change anything, run the tests after a change, keep answers short."
TOOLS = {
"run_tests": "run_tests(): run the project's tests and say which pass and which fail.",
"read_file": "read_file(path): return the text of one file in the project.",
"edit_file": "edit_file(path, old, new): replace the text old with new in one file.",
"open_pr": "open_pr(title): put the change on a new branch and open a pull request for review.",
}
TASK = "test_add fails. Find out why and fix it."
PROJECT = {
"calc.py": '"""Small helpers for the checkout page."""\n\n\ndef add(a, b):\n """Return the sum of a and b."""\n return a - b\n\n\ndef mul(a, b):\n """Return a times b."""\n return a * b\n',
"test_calc.py": "from calc import add, mul\n\n\ndef test_add():\n assert add(2, 3) == 5\n\n\ndef test_mul():\n assert mul(2, 3) == 6\n",
}
def words(text: str) -> int:
return len(text.split())
def size(context: list[str]) -> int:
return words("\n".join(context))
def run_tests(folder: Path) -> str:
calc = types.ModuleType("calc")
exec(compile((folder / "calc.py").read_text(), str(folder / "calc.py"), "exec"), calc.__dict__)
sys.modules["calc"] = calc # so the test file's "from calc import ..." finds this copy
tests: dict = {}
exec(compile((folder / "test_calc.py").read_text(), str(folder / "test_calc.py"), "exec"), tests)
del sys.modules["calc"]
failed = []
for name in ("test_add", "test_mul"):
try:
tests[name]()
except AssertionError as e:
failed.append(f"{name} FAILED ({traceback.extract_tb(e.__traceback__)[-1].line})")
return f"tests: {2 - len(failed)} passed" + "".join(f", {f}" for f in failed)
def stand_in_model(context: list[str], tools: list[str]) -> tuple[str, str]:
"""Rules in place of a model: ("call", tool + arguments) or ("answer", text)."""
seen = "\n".join(context).__contains__
if not tools:
return "answer", "I can't open your files or run the tests from here. Paste calc.py and the test output and I'll point at the bug."
refused = seen("denied: edit_file") or seen("you said no to edit_file")
if not seen("tests:"):
return "call", "run_tests()"
if not seen("read test_calc.py"):
return "call", 'read_file("test_calc.py")'
if not seen("read calc.py"):
return "call", 'read_file("calc.py")'
if not seen("edited calc.py") and not refused:
return "call", 'edit_file("calc.py", "return a - b", "return a + b")'
if seen("edited calc.py") and not seen("tests: 2 passed"):
return "call", "run_tests()"
if "open_pr" in tools and not seen("pull request #"):
return "call", 'open_pr("Fix add(): it subtracted")'
if seen("pull request #"):
return "answer", "Opened pull request #1: add() subtracted, it now adds. Both tests pass."
if seen("edited calc.py"):
return "answer", "Fixed: add() returned a - b, it now returns a + b. Both tests pass."
return "answer", "I didn't change anything. The bug: in calc.py, add() returns a - b; it should return a + b."
def summarise(context: list[str]) -> str:
"""Compaction: a real harness asks the model for this summary; the stand-in keeps each result's first line and the bug it found."""
keep = [m.split("\n", 1)[0] for m in context[3:] if not m.startswith("calls ")]
if any("return a - b" in m and m.startswith("read calc.py") for m in context):
keep.append("calc.py line 6: return a - b (should be a + b)")
return "Summary of earlier work: " + "; ".join(keep)
def harness(rules: dict, window: int, say: str = "yes", sandbox: bool = False) -> list[str]:
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp) / "project" # your folder
home.mkdir()
for name, text in PROJECT.items():
(home / name).write_text(text)
work = Path(shutil.copytree(home, Path(tmp) / "sandbox")) if sandbox else home
log = loop(rules, window, say, work)
fixed = "return a + b" in (home / "calc.py").read_text()
return log + [f"your folder: add() {'returns a + b' if fixed else 'still returns a - b'}"]
def loop(rules: dict, window: int, say: str, work: Path) -> list[str]:
"""The harness itself: context in, the model's reply out, the tool run (or not), its result back in, again."""
tools = list(rules)
context = [SYSTEM, "\n".join(TOOLS[t] for t in tools), TASK]
log, turn = [], 0
while True:
if size(context) > window * 3 // 4:
before = size(context)
context = context[:3] + [summarise(context)]
log.append(f"compacted: {before} -> {size(context)} words")
turn += 1
kind, text = stand_in_model(context, tools)
if kind == "answer":
context.append(text)
log.append(f"turn {turn}: answer: {text} | context {size(context)}/{window}")
break
name = text.split("(")[0]
rule = rules[name]
if rule == "ask":
rule = say if name == "edit_file" else "yes"
decision = f"asked you: {rule}"
else:
decision = "allowed" if rule == "allow" else "denied"
if rule in ("allow", "yes"):
if name == "run_tests":
result = run_tests(work)
elif name == "read_file":
path = text.split('"')[1]
body = (work / path).read_text()
result = f"read {path} ({len(body.splitlines())} lines):\n{body}"
elif name == "edit_file":
body = (work / "calc.py").read_text()
assert body.count("return a - b") == 1
(work / "calc.py").write_text(body.replace("return a - b", "return a + b"))
result = "edited calc.py: line 6 is now return a + b"
else:
diff = difflib.unified_diff(PROJECT["calc.py"].splitlines(), (work / "calc.py").read_text().splitlines(), lineterm="", n=0)
changed = [d for d in diff if d[:1] in "+-" and d[:3] not in ("+++", "---")]
result = f"pull request #1 opened: {' | '.join(changed)}"
elif rule == "no":
result = f"you said no to {name}"
else:
result = f"denied: {name} is not allowed here"
context += [f"calls {text}", result]
first_line = result.splitlines()[0]
log.append(f"turn {turn}: {text} -> {decision} -> {first_line} | context {size(context)}/{window}")
return log
SETUPS = {
"allow everything, window 1000": dict(rules={"run_tests": "allow", "read_file": "allow", "edit_file": "allow"}, window=1000),
"ask before edits": dict(rules={"run_tests": "allow", "read_file": "allow", "edit_file": "ask"}, window=1000),
"ask before edits, you say no": dict(rules={"run_tests": "allow", "read_file": "allow", "edit_file": "ask"}, window=1000, say="no"),
"ask before every tool": dict(rules={"run_tests": "ask", "read_file": "ask", "edit_file": "ask"}, window=1000),
"read-only": dict(rules={"run_tests": "allow", "read_file": "allow", "edit_file": "deny"}, window=1000),
"allow everything, window 180": dict(rules={"run_tests": "allow", "read_file": "allow", "edit_file": "allow"}, window=180),
"chat, no tools": dict(rules={}, window=1000),
"editor that asks": dict(rules={"run_tests": "ask", "read_file": "allow", "edit_file": "ask"}, window=1000),
"background, in a sandbox": dict(rules={"run_tests": "allow", "read_file": "allow", "edit_file": "allow", "open_pr": "allow"}, window=1000, sandbox=True),
}
for title, setup in SETUPS.items():
log = harness(**setup)
print(f"== {title}")
print("\n".join(log))
assert harness(**SETUPS["read-only"])[-1] == "your folder: add() still returns a - b"
assert harness(**SETUPS["background, in a sandbox"])[-1] == "your folder: add() still returns a - b"
assert sum(line.startswith("compacted") for line in harness(**SETUPS["allow everything, window 180"])) == 1
python3 harness.pyIt printed:== allow everything, window 1000
turn 1: run_tests() -> allowed -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 78/1000
turn 2: read_file("test_calc.py") -> allowed -> read test_calc.py (9 lines): | context 103/1000
turn 3: read_file("calc.py") -> allowed -> read calc.py (11 lines): | context 140/1000
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> allowed -> edited calc.py: line 6 is now return a + b | context 160/1000
turn 5: run_tests() -> allowed -> tests: 2 passed | context 165/1000
turn 6: answer: Fixed: add() returned a - b, it now returns a + b. Both tests pass. | context 180/1000
your folder: add() returns a + b
== ask before edits
turn 1: run_tests() -> allowed -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 78/1000
turn 2: read_file("test_calc.py") -> allowed -> read test_calc.py (9 lines): | context 103/1000
turn 3: read_file("calc.py") -> allowed -> read calc.py (11 lines): | context 140/1000
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> asked you: yes -> edited calc.py: line 6 is now return a + b | context 160/1000
turn 5: run_tests() -> allowed -> tests: 2 passed | context 165/1000
turn 6: answer: Fixed: add() returned a - b, it now returns a + b. Both tests pass. | context 180/1000
your folder: add() returns a + b
== ask before edits, you say no
turn 1: run_tests() -> allowed -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 78/1000
turn 2: read_file("test_calc.py") -> allowed -> read test_calc.py (9 lines): | context 103/1000
turn 3: read_file("calc.py") -> allowed -> read calc.py (11 lines): | context 140/1000
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> asked you: no -> you said no to edit_file | context 155/1000
turn 5: answer: I didn't change anything. The bug: in calc.py, add() returns a - b; it should return a + b. | context 174/1000
your folder: add() still returns a - b
== ask before every tool
turn 1: run_tests() -> asked you: yes -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 78/1000
turn 2: read_file("test_calc.py") -> asked you: yes -> read test_calc.py (9 lines): | context 103/1000
turn 3: read_file("calc.py") -> asked you: yes -> read calc.py (11 lines): | context 140/1000
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> asked you: yes -> edited calc.py: line 6 is now return a + b | context 160/1000
turn 5: run_tests() -> asked you: yes -> tests: 2 passed | context 165/1000
turn 6: answer: Fixed: add() returned a - b, it now returns a + b. Both tests pass. | context 180/1000
your folder: add() returns a + b
== read-only
turn 1: run_tests() -> allowed -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 78/1000
turn 2: read_file("test_calc.py") -> allowed -> read test_calc.py (9 lines): | context 103/1000
turn 3: read_file("calc.py") -> allowed -> read calc.py (11 lines): | context 140/1000
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> denied -> denied: edit_file is not allowed here | context 156/1000
turn 5: answer: I didn't change anything. The bug: in calc.py, add() returns a - b; it should return a + b. | context 175/1000
your folder: add() still returns a - b
== allow everything, window 180
turn 1: run_tests() -> allowed -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 78/180
turn 2: read_file("test_calc.py") -> allowed -> read test_calc.py (9 lines): | context 103/180
turn 3: read_file("calc.py") -> allowed -> read calc.py (11 lines): | context 140/180
compacted: 140 -> 100 words
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> allowed -> edited calc.py: line 6 is now return a + b | context 120/180
turn 5: run_tests() -> allowed -> tests: 2 passed | context 125/180
turn 6: answer: Fixed: add() returned a - b, it now returns a + b. Both tests pass. | context 140/180
your folder: add() returns a + b
== chat, no tools
turn 1: answer: I can't open your files or run the tests from here. Paste calc.py and the test output and I'll point at the bug. | context 55/1000
your folder: add() still returns a - b
== editor that asks
turn 1: run_tests() -> asked you: yes -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 78/1000
turn 2: read_file("test_calc.py") -> allowed -> read test_calc.py (9 lines): | context 103/1000
turn 3: read_file("calc.py") -> allowed -> read calc.py (11 lines): | context 140/1000
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> asked you: yes -> edited calc.py: line 6 is now return a + b | context 160/1000
turn 5: run_tests() -> asked you: yes -> tests: 2 passed | context 165/1000
turn 6: answer: Fixed: add() returned a - b, it now returns a + b. Both tests pass. | context 180/1000
your folder: add() returns a + b
== background, in a sandbox
turn 1: run_tests() -> allowed -> tests: 1 passed, test_add FAILED (assert add(2, 3) == 5) | context 93/1000
turn 2: read_file("test_calc.py") -> allowed -> read test_calc.py (9 lines): | context 118/1000
turn 3: read_file("calc.py") -> allowed -> read calc.py (11 lines): | context 155/1000
turn 4: edit_file("calc.py", "return a - b", "return a + b") -> allowed -> edited calc.py: line 6 is now return a + b | context 175/1000
turn 5: run_tests() -> allowed -> tests: 2 passed | context 180/1000
turn 6: open_pr("Fix add(): it subtracted") -> allowed -> pull request #1 opened: - return a - b | + return a + b | context 200/1000
turn 7: answer: Opened pull request #1: add() subtracted, it now adds. Both tests pass. | context 212/1000
your folder: add() still returns a - bThe loop round a stand-in model written as plain rules (no real model, no key, no network): real tools on a two-file project in a temporary folder, a rule per tool, a context window counted in words, and compaction at three quarters. Nine setups, the same stand-in in each. Really run.
Common questions
What is an agent harness?
The program round a model that makes it an agent: it builds the context (system prompt, the list of tools, the task, results so far), sends it to the model, runs the tools the model asks for under its rules, and loops. The model only writes text; the harness is what acts.
Does the model run the tools itself?
No. The model replies with a request to call a tool, with the arguments, and stops; your code or the harness actually runs it and sends the result back. Anthropic's tool use docs and OpenAI's function calling guide both describe it this way.
What happens when the context fills up?
The context window has a fixed size, and models use a long context less well as it grows. So the harness compacts: it has the model summarise the work so far, keeping what matters, like an unfixed bug, dropping raw tool output, and starts a fresh context from that summary.
Is it safe to let an agent do everything?
Not on a machine with real work on it. An allow or deny rule matches a command's text, and the same program called another way can slip past; Claude Code's docs say such rules aren't a security boundary. To let it act alone, run it in a sandbox, a container or a VM.
Why does the same model do better in one tool than another?
Because the harness differs: the tools given and how they are described, the rules, what goes into the context. Building their SWE-bench agent, Anthropic spent more time on the tools than on the prompt, for example requiring absolute file paths, after which those mistakes stopped.
Where do an agent's tools come from?
Some come with the harness, like reading and editing files or running commands; others come from outside through MCP (Model Context Protocol), an open standard for connecting AI applications to other systems. Each reaches the model as a name and description in the context, and passes the same rules.
What is a read-only mode for?
To let an agent explore and plan without touching files: it reads, runs the tests, finds the cause and proposes a fix, and you decide after reading it. Here it finds the same bug but your folder doesn't change. Claude Code's plan mode and Codex's read-only mode work this way.
How is an agent different from a workflow?
A workflow follows paths written in code ahead of time, such as calling a model three times in order. An agent lets the model choose which tool to call next and when to stop, inside the harness's loop. Anthropic's advice is to start with the simplest approach that works.
Next lesson
AI attacksLevel: Intermediate
A harness's tools and its allow, ask and deny are where an AI attack is stopped or let through; next, the attacks themselves.