An agent harness is all the code around a language model that turns it into an agent. It runs the loop that calls the model, executes the tools it asks for and feeds the results back. It decides which tools exist and which calls need approval. It manages what goes into the context window, retries failures, persists state, isolates side effects and records what happened. The model supplies judgement. The harness decides what that judgement can see, touch and get away with. On public benchmarks the same model swings by double-digit points depending on the harness wrapped around it.
This post defines the harness component by component, builds a minimal one in about 200 lines of Python, shows the evidence that harness choice moves results, and ends with a spec template and review scorecard you can run against your own agents.
01What is an agent harness?
Strip an agent down and you find two things: a model that maps a context window to a next action, and a program that does everything else. That program is the harness.
The word has settled in over the last year. Anthropic used it in Effective harnesses for long-running agents (November 2025). Benchmark leaderboards list "agent" and "model" as separate columns because the pair, not the model, is what gets measured. Claude Code, Codex CLI, Cursor's agent and the coding agents in most IDEs are harnesses. So is the 40-line while loop in your prototype.
A precise definition:
An agent harness is the deterministic runtime that owns the control loop, the tool surface, the permission model, the context window, error handling, durable state, the execution environment and telemetry for an LLM-driven agent.
The key word is deterministic. Everything in the harness is ordinary software. You can test it, version it, review it and reason about its failure modes. That is why most of the improvement you can make lives there.
Harness vs framework vs agent
These get conflated, so it's worth separating them.
| Term | What it is | Examples |
|---|---|---|
| Model | Weights behind an API. Stateless: context in, tokens out. | Claude Opus 5.5, GPT-class models, open-weight models |
| Framework / SDK | A library of parts for building harnesses. | LangGraph, OpenAI Agents SDK, the Anthropic SDK's tool runner |
| Harness | A specific, configured runtime: chosen tools, prompts, policies, context strategy and loop for one job. | Claude Code, Codex CLI, your support-triage agent |
| Agent | A running instance of a harness plus a model working on a task. | "The session fixing ticket #4812" |
A framework can make a harness quicker to write. It cannot make one good. The decisions that matter (what the tools return, what needs approval, what gets dropped from context) are yours either way.
02The anatomy of an agent harness
Here is the loop every harness implements, with the components that hang off it.
Eight components. Each one is a design decision with a measurable effect.
1. The control loop
The loop calls the model, inspects why it stopped, acts, and repeats. With the Anthropic Messages API the branch is on stop_reason: tool_use means run the requested tools and send back tool_result blocks; end_turn means the model thinks it's finished; max_tokens means output was cut off; refusal means the request was declined. A loop that only checks for tool_use will treat a truncated or refused turn as success. That bug is common, and it hides well.
The loop also owns termination: a turn cap, a token or cost budget and a wall-clock limit. Without them, an agent stuck in a retry spiral burns money until someone notices.
2. Tool definitions
Tools are the agent's interface to the world, and the model sees only the name, description and schema. The SWE-agent paper (Yang et al., 2024) called this the agent–computer interface and showed that designing it for the model, not for humans, materially changes results. Anthropic's Writing effective tools for agents (September 2025) makes the same case in practice. Namespace related tools. Return human-readable fields rather than UUIDs. Offer a concise/detailed response mode. Paginate and truncate with sensible defaults; Claude Code caps tool responses at 25,000 tokens by default.
What we'd actually do: start with fewer, coarser tools than you think. Every tool you add is another option the model can pick wrongly. A file reader, a file writer and a shell inside a sandbox cover a surprising share of engineering tasks.
3. The permission and approval model
The harness decides, per call, whether to allow, deny or ask a human. This is the main control you have over a model that might be wrong or might have been prompt-injected. The Claude Agent SDK's permission flow is a good reference design. Hooks run first. Then deny rules, then ask rules, then the permission mode (default, dontAsk, acceptEdits, bypass, plan, auto), then allow rules, and only then a canUseTool callback. Deny always beats allow. Anything that must be checked on every call belongs in a pre-tool hook, because allow rules and permissive modes skip the callback entirely.
Two rules we hold:
- Classify tools by blast radius, not by name.
read,write,exec,external(sends data out or spends money). Policy attaches to the class. - A declined call returns an error result, not silence. The model needs to know the action didn't happen, and that it shouldn't simply retry.
The threat model behind this is in our post Securing AI agents: prompt injection, tool permissions and least privilege for MCP.
4. Context management
The model only knows what's in the window, and every turn re-sends the whole window. The harness chooses what goes in: system prompt, tool schemas, history, retrieved files, memory. It also chooses what comes out: truncating tool output, clearing old tool results, summarising or compacting history. This is the subject of its own post in this series, on context engineering for long-running agents, so here is only the harness-level point. Context policy is code. Put it in one place, make it observable, and test it.
One constraint that has become stricter: newer Anthropic models tie thinking blocks to the conversation that produced them. If your harness edits earlier turns, for example by deleting stale tool results by hand, the model loses that reasoning. Prefer append-only history, and use the provider's own context-editing or compaction features rather than rewriting messages yourself.
5. Errors, retries and budgets
There are three kinds of failure, and each needs different handling:
| Failure | Example | Who handles it |
|---|---|---|
| Transport / provider | 429, 5xx, timeouts, overloaded | Harness, silently: exponential backoff with jitter (the official SDKs do this; tune max_retries) |
| Tool, model-recoverable | File not found, test failed, bad argument | Model: return is_ with a message that says what to try instead |
| Tool, harness bug | Exception inside your tool code | Harness: log it with a stack trace, give the model a short generic error, alert if it repeats |
The middle row is where harness quality shows. "ENOENT" teaches the model nothing. "No file at src/app.ts. Use run_command with find to locate it" usually gets you a correct next step.
6. State and durability
An agent run is a long, stateful process built on a stateless API. The transcript is the state. Persist each message as it's produced, before acting on it, and resuming after a crash becomes trivial. One case needs explicit handling: a crash between the model asking for a tool call and the result being recorded. The side effect may or may not have happened. The safe recovery is to tell the model exactly that, and have it check before retrying.
For multi-session work the harness needs memory outside the window. Anthropic's long-running harness uses a progress file, a machine-readable feature list, an init.sh and disciplined git commits as the memory that survives a context reset. That is a pattern worth copying.
7. Sandboxing hooks
Tools with side effects should run somewhere that limits the damage when the model is wrong: a container, a gVisor sandbox or a microVM, with egress restricted and secrets kept outside. The harness's job is to route every exec and write through that boundary and never around it. We cover the options in Sandboxing AI agents that run code: containers vs gVisor vs Firecracker, and locking down egress. The harness-level rule: the sandbox is the security boundary; the permission policy is a usability layer on top. String-matching rm -rf in a deny list is not a control.
8. Observability
You cannot improve a harness you can't see into, and tracing agent runs with OpenTelemetry is the cheapest place to start. At minimum, record one span per model call and per tool call, with token usage, latency, the permission decision and the error flag. The OpenTelemetry GenAI semantic conventions define operation names such as invoke_, chat and execute_ and attributes such as gen_. They're still marked Development, so expect renames, but using them now beats inventing your own. Keep full transcripts too. Most harness bugs are diagnosed by reading what the model saw.
03A minimal agent harness in Python
Below is a complete, small harness. It is deliberately boring. It uses the Anthropic Python SDK directly, without a framework, so every component above appears as code you can see. It assumes a running container called agent-sandbox with your repository mounted at /workspace (see the sandboxing post for how to build one properly), plus pip install anthropic opentelemetry-api.
# harness.py: a minimal agent harness. Python 3.11+, anthropic SDK.
import json, subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Literal
import anthropic
from opentelemetry import trace # no-op unless you configure an OTel SDK
MODEL = "claude-opus-5-5"
MAX_TURNS = 40
MAX_RESULT_CHARS = 20_000
WORKDIR = Path("/workspace") # same path inside and outside the sandbox (bind mount)
SANDBOX = "agent-sandbox" # a running, network-restricted container
client = anthropic.Anthropic(max_retries=4) # SDK backs off on 408/409/429/5xx
tracer = trace.get_tracer("harness")
Risk = Literal["read", "write", "exec"]
class ToolError(Exception):
"""An error the model caused and can recover from. Its message is shown to the model."""
@dataclass(frozen=True)
class Tool:
name: str
description: str
input_schema: dict
risk: Risk
fn: Callable[..., str]
def spec(self) -> dict:
return {"name": self.name, "description": self.description,
"input_schema": self.input_schema, "strict": True}
# ---------- tools ----------
def _safe_path(p: str) -> Path:
full = (WORKDIR / p).resolve()
if not full.is_relative_to(WORKDIR):
raise ToolError(f"{p} is outside the workspace. Use a path relative to {WORKDIR}.")
return full
def read_file(path: str, offset: int, limit: int) -> str:
f = _safe_path(path)
if not f.is_file():
raise ToolError(f"No file at {path}. Use run_command with 'find' to locate it.")
lines = f.read_text(errors="replace").splitlines()
body = "\n".join(f"{offset + i + 1}\t{line}"
for i, line in enumerate(lines[offset:offset + limit]))
remaining = len(lines) - (offset + limit)
if remaining > 0:
body += f"\n[{remaining} more lines. Call again with offset={offset + limit}.]"
return body
def write_file(path: str, content: str) -> str:
f = _safe_path(path)
f.parent.mkdir(parents=True, exist_ok=True)
f.write_text(content)
return f"Wrote {len(content)} characters to {path}."
def run_command(command: str, timeout_s: int) -> str:
timeout_s = max(1, min(timeout_s, 300))
try:
r = subprocess.run(
["docker", "exec", "-w", str(WORKDIR), SANDBOX, "sh", "-lc", command],
capture_output=True, text=True, timeout=timeout_s)
except subprocess.TimeoutExpired:
raise ToolError(f"Timed out after {timeout_s}s. Narrow the command.")
return f"exit={r.returncode}\n--- stdout ---\n{r.stdout}\n--- stderr ---\n{r.stderr}"
def _schema(**props: dict) -> dict:
return {"type": "object", "properties": props,
"required": list(props), "additionalProperties": False}
TOOLS = {t.name: t for t in [
Tool("read_file", "Read lines from a UTF-8 text file in the workspace. "
"Returns numbered lines. Use offset/limit to page through large files.",
_schema(path={"type": "string"}, offset={"type": "integer"},
limit={"type": "integer"}), "read", read_file),
Tool("write_file", "Create or overwrite a file in the workspace with the full new content.",
_schema(path={"type": "string"}, content={"type": "string"}), "write", write_file),
Tool("run_command", "Run a shell command in the project sandbox (no network). "
"Use for ls, find, grep, tests and builds. Returns exit code, stdout and stderr.",
_schema(command={"type": "string"}, timeout_s={"type": "integer"}), "exec", run_command),
]}
# ---------- permissions ----------
AUTO_ALLOW: set[Risk] = {"read"}
def decide(tool: Tool, args: dict) -> Literal["allow", "ask", "deny"]:
if tool.name == "run_command" and "git push" in args["command"]:
return "deny" # policy, not security: the sandbox has no credentials anyway
return "allow" if tool.risk in AUTO_ALLOW else "ask"
def approve(tool: Tool, args: dict) -> bool:
print(f"\n[approval needed] {tool.name}: {json.dumps(args)[:800]}")
return input("allow? [y/N] ").strip().lower() == "y"
# ---------- execution ----------
def _result(tool_use_id: str, text: str, error: bool = False) -> dict:
if len(text) > MAX_RESULT_CHARS:
half = MAX_RESULT_CHARS // 2
text = (f"{text[:half]}\n[... {len(text) - MAX_RESULT_CHARS} characters truncated. "
f"Narrow the query or page through the output ...]\n{text[-half:]}")
return {"type": "tool_result", "tool_use_id": tool_use_id,
"content": text, "is_error": error}
def execute(block) -> dict:
with tracer.start_as_current_span(f"execute_tool {block.name}", attributes={
"gen_ai.operation.name": "execute_tool",
"gen_ai.tool.name": block.name,
"gen_ai.tool.call.id": block.id,
}) as span:
tool = TOOLS.get(block.name)
if tool is None:
return _result(block.id, f"Unknown tool {block.name}.", error=True)
verdict = decide(tool, block.input)
span.set_attribute("harness.permission", verdict)
if verdict == "deny":
return _result(block.id, "Blocked by policy. Do not retry; choose another approach.", True)
if verdict == "ask" and not approve(tool, block.input):
return _result(block.id, "The user declined this action. Do not retry it; "
"explain what you wanted to do and propose an alternative.", True)
try:
return _result(block.id, tool.fn(**block.input))
except ToolError as e:
return _result(block.id, str(e), error=True)
except Exception as e: # a bug in our tool, not the model's fault
span.record_exception(e)
return _result(block.id, f"Internal tool failure ({type(e).__name__}).", error=True)
# ---------- durable state ----------
class Transcript:
"""Append-only JSONL. The transcript is the agent's state."""
def __init__(self, path: Path):
self.path = path
path.parent.mkdir(parents=True, exist_ok=True)
self.messages = ([json.loads(l) for l in path.read_text().splitlines()]
if path.exists() else [])
def append(self, msg: dict) -> None:
self.messages.append(msg)
with self.path.open("a") as f:
f.write(json.dumps(msg) + "\n")
def recover(t: Transcript) -> None:
"""If we crashed after the model asked for tools but before results were saved,
say so explicitly rather than pretending nothing happened."""
last = t.messages[-1]
if last["role"] == "assistant":
pending = [b for b in last["content"] if b.get("type") == "tool_use"]
t.append({"role": "user", "content": [
_result(b["id"], "The harness restarted before this call returned. Its effects "
"are unknown. Check current state before retrying.", error=True)
for b in pending] or [{"type": "text", "text": "Continue."}]})
# ---------- the loop ----------
SYSTEM = ("You are a careful software engineer working in a sandboxed repository at "
f"{WORKDIR}. Read before you write. Run the tests after every change. "
"When the task is done, summarise what you changed and how you verified it.")
def run(task: str, session_id: str) -> str:
t = Transcript(Path("sessions") / f"{session_id}.jsonl")
if t.messages:
recover(t)
else:
t.append({"role": "user", "content": task})
for _ in range(MAX_TURNS):
with tracer.start_as_current_span(f"chat {MODEL}", attributes={
"gen_ai.operation.name": "chat", "gen_ai.request.model": MODEL,
}) as span:
resp = client.beta.messages.create(
model=MODEL,
max_tokens=16_000,
system=SYSTEM,
tools=[tool.spec() for tool in TOOLS.values()],
messages=t.messages,
output_config={"effort": "high"},
betas=["server-side-fallback-2026-07-01"],
fallbacks="default", # re-run declined requests server-side
cache_control={"type": "ephemeral"}, # cache the growing prefix
)
span.set_attribute("gen_ai.usage.input_tokens", resp.usage.input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", resp.usage.output_tokens)
# Append the assistant turn unmodified (thinking blocks included) before acting on it.
t.append({"role": "assistant",
"content": [b.model_dump(mode="json", exclude_none=True) for b in resp.content]})
tool_uses = [b for b in resp.content if b.type == "tool_use"]
match resp.stop_reason:
case "end_turn":
return "".join(b.text for b in resp.content if b.type == "text")
case "refusal":
raise RuntimeError(f"Request declined: {resp.stop_details}")
case "max_tokens":
t.append({"role": "user", "content": [
*(_result(b.id, "Output limit reached before this call was complete. "
"Re-issue it.", error=True) for b in tool_uses),
{"type": "text", "text": "You hit the output limit. Continue in smaller steps."}]})
case "tool_use":
# All results go back in ONE user message, even for parallel calls.
t.append({"role": "user", "content": [execute(b) for b in tool_uses]})
case other:
raise RuntimeError(f"Unhandled stop_reason: {other}")
raise RuntimeError(f"Turn budget of {MAX_TURNS} exhausted. Transcript: {t.path}")
if __name__ == "__main__":
import sys, uuid
print(run(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else uuid.uuid4().hex))What's worth noticing:
- Every branch of
stop_reasonis handled. Truncated tool calls get error results, so the transcript stays valid. The API requires everytool_useto be answered by a matchingtool_result. - Write before act. The assistant turn is persisted before any tool runs, which is what makes
recover()possible. - Errors are written for the reader that matters, which is the model. Each one says what to do next.
- Permission is by risk class, and a declined call is reported as declined.
- The
git pushdeny is labelled as policy. The real control is a sandbox with no credentials and no network. - Spans use the OTel GenAI names, so they land usefully in any OpenTelemetry backend.
- Two provider-specific options: the
fallbacksopt-in (Anthropic's server-side fallback when a request is refused, behind a beta header) and top-level prompt caching. Swap the model call for another provider and the rest of the harness doesn't change. That's the point.
What it deliberately leaves out: streaming, parallel tool execution, compaction, sub-agents, MCP. Each is a real feature with a real cost. Add them when a measured problem calls for them, not before.
04Same model, different harness: the evidence
The claim that the harness matters as much as the model is easy to make and easy to wave away. The evidence is public.
- Terminal-Bench. The leaderboard ranks model and agent pairs, not models alone: every entry names the harness next to the model, and the same model appears more than once at different reasoning settings with different scores. A Terminal-Bench number describes a model inside a particular harness, never the model on its own.
- Meta-Harness. Lee et al. (March 2026) automated harness search with the model held fixed. They report a 7.7-point gain over a state-of-the-art context-management system with 4× fewer context tokens on text classification, a 4.7-point average gain on 200 IMO-level problems across five held-out models, and harnesses that beat the best hand-engineered baselines on Terminal-Bench 2.0.
- mini-swe-agent. The SWE-agent team's minimal harness is roughly 100 lines for the agent class, uses only bash, runs every action as an independent
subprocess., and reports above 74% on SWE-bench Verified.run
Read the last two together and the lesson is sharper than "harnesses matter". A good harness is not the same as a big one. mini-swe-agent wins by removing things: no custom tools to misuse, no stateful shell to corrupt, trivially sandboxable. Meta-Harness wins by searching over what goes into context. Both are about deciding precisely what the model sees and can do.
A caution on reading leaderboards: a benchmark harness is tuned for that benchmark's tasks, time limits and scoring. A harness that tops Terminal-Bench can still be wrong for your support-ticket agent. Benchmarks prove the harness effect exists. Only your own evals can tell you which harness suits your workload.
05Why the harness shapes cost as much as accuracy
Harness decisions dominate the bill as well as the score. The model call re-sends the entire context every turn, so input tokens grow roughly quadratically with turn count. A worked example, with the assumptions stated:
Assumptions (illustrative, not measured): 30 turns; a stable prefix of 8,000 tokens (system prompt plus tool schemas); each turn adds 3,000 tokens of tool output and model text; Claude Opus 5.5 list prices at the time of writing: $4 per million input tokens, $0.20 per million cache-read tokens, and 1.25× base ($5 per million) for 5-minute cache writes. Output tokens are ignored because they're identical in both cases.
- No caching. Turn i sends 8,000 + 3,000·i tokens. Over 30 turns: 30 × 8,000 + 3,000 × (1 + 2 + … + 30) = 240,000 + 1,395,000 = 1,635,000 input tokens ≈ $6.54.
- Prefix caching. Each turn reads the previous prefix from cache and writes only the new 3,000 tokens. Cache reads: 30 × 8,000 + 3,000 × (0 + 1 + … + 29) = 240,000 + 1,305,000 = 1,545,000 tokens × $0.20/M ≈ $0.31. Cache writes: 8,000 + 30 × 3,000 = 98,000 tokens × $5/M ≈ $0.49. Total ≈ $0.80.
Same model, same task, roughly an eighth of the input cost. And one careless line can lose all of it: a timestamp in the system prompt, tool schemas serialised in a different order, a tool list that changes between turns. Each of those breaks the cached prefix on every call. Our post on LLM cost engineering with prompt caching and model routing covers the rest of the bill. Truncating tool output to 20,000 characters instead of letting a 400 KB log through is another harness decision with a direct line to the invoice.
06Build vs buy: which harness should you use?
| Option | You own | Good for | Watch out for |
|---|---|---|---|
| Hand-written loop (as above) | Everything | Narrow, high-volume agents where you need every decision visible; regulated environments | You will reimplement streaming, compaction and parallelism eventually |
| Provider SDK helper (e.g. Anthropic's tool runner) | Tools and policy hooks | Custom-tool agents without writing the loop | Beta surfaces; check behaviour on edge stop reasons |
| Batteries-included agent SDK (e.g. Claude Agent SDK, OpenAI Agents SDK) | Configuration, hooks, custom tools | Coding and file-system agents; teams that want a proven permission model and context management | Defaults tuned for coding agents; permission modes like bypass are easy to misuse |
| Graph framework (e.g. LangGraph) | Graph, nodes, state schema | Workflows with explicit branching, human checkpoints, long-lived state | Abstraction cost; easy to build a workflow and call it an agent |
| Managed agent platforms | Config and tool results | Hosted, long-running sessions where you don't want to run the sandbox | Data residency, vendor coupling, less control of context policy |
Our default: if the agent mostly reads and edits files and runs commands, start from a batteries-included agent SDK. Its permission and context machinery has been tested against more edge cases than yours will be. If the agent calls your own business APIs at volume, write the loop. It's under 300 lines, and you'll want to own every token. You probably don't need a graph framework until you have a real workflow with branches and human checkpoints, and you probably don't need multiple agents at all. That trade-off has its own post in this series, on when a multi-agent architecture helps and when it just multiplies cost.
07The harness spec: a template and review scorecard
Most agent projects never write down what their harness does. Then a regression arrives with a model upgrade and nobody can say what changed. This is the asset we use: a one-page harness spec you keep in the repository next to the code, and a scorecard to review it against. Treat the spec like an API contract. Changes go through review, and every change is evaluated with the model held fixed.
Harness spec template
# harness.spec.yaml: one per agent, versioned with the code
harness: support-triage-agent
version: 2025.12.1
owner: platform-ai@yourco.example
model:
id: claude-opus-5-5 # pin explicitly; never "latest"
effort: high
fallback: provider-default # what happens on refusal / outage
loop:
max_turns: 40
max_wall_clock_s: 900
max_cost_usd: 2.00 # hard stop, enforced by the harness, not the prompt
handled_stop_reasons: [end_turn, tool_use, max_tokens, refusal]
tools: # every tool, its blast radius and its output cap
- name: search_tickets
risk: read
output_cap_tokens: 4000
paginated: true
- name: update_ticket
risk: write
idempotency_key: required
- name: refund_order
risk: external # moves money
approval: human
permissions:
default: ask
auto_allow: [read]
deny: ["refund_order where amount > 500"]
hook: pre_tool_policy.py # runs on every call, before rules
context:
system_prompt: prompts/triage.v7.md
cacheable_prefix: [tools, system] # nothing volatile above the cache breakpoint
tool_result_truncation: head_tail
history_strategy: provider_compaction # append-only; never rewrite turns
memory: none
errors:
transport_retries: 4 # SDK exponential backoff
tool_errors: return_is_error_with_next_step
unknown_tool: return_error
state:
transcript: append_only_jsonl
crash_recovery: mark_pending_calls_unknown
retention_days: 30 # transcripts contain customer data
sandbox:
exec: none # this agent has no shell
egress: [api.internal.yourco.example]
secrets: brokered_per_tool # model never sees credentials
observability:
traces: otel_genai_semconv
metrics: [task_success, cost_per_success, tool_error_rate, approvals_requested, turns]
transcript_sampling: 100%
evals:
suite: evals/triage/ # run on every harness or model change
gate: "success >= baseline and cost_per_success <= 1.1 x baseline"Harness review scorecard
Score each line 0 (absent), 1 (partial) or 2 (done). Anything below 18 of 24 isn't ready for unattended use.
| # | Component | Question | Minimum bar for "2" |
|---|---|---|---|
| 1 | Loop | Is every stop reason handled explicitly? | end_turn, tool_use, max_tokens, refusal each have a branch; unknown values raise |
| 2 | Budgets | Can a run exceed a known cost or time? | Turn, wall-clock and cost caps enforced in code |
| 3 | Tools | Could a new engineer predict what each tool returns from its description alone? | Descriptions say when to use it, what it returns, and its limits |
| 4 | Tool output | Is every tool's output bounded? | Caps plus pagination; truncation tells the model how to get more |
| 5 | Permissions | Is policy attached to blast radius? | Every tool classed read/write/exec/external; deny beats allow |
| 6 | Approvals | Does a declined action come back to the model as declined? | Error result with "don't retry, propose an alternative" |
| 7 | Errors | Do tool errors tell the model what to do next? | No raw stack traces or bare error codes in tool_result |
| 8 | Context | Is the cacheable prefix stable byte for byte? | Cache-read tokens > 0 on turn 2+, checked in a test |
| 9 | State | Can a run resume after the process is killed mid-tool-call? | Write-before-act transcript; pending calls marked unknown |
| 10 | Sandbox | If the model ran the worst possible command, what breaks? | Isolated runtime, egress allowlist, no ambient credentials |
| 11 | Observability | Can you replay exactly what the model saw on a failed run? | Full transcripts plus spans per model and tool call |
| 12 | Evals | Is there a fixed-model eval run on every harness change? | Suite in CI, tracking success rate and cost per success |
Line 12 is the one most teams skip, and it's the one that makes the rest improvable. Hold the model constant, change one harness component, and measure four things: task success rate, cost per successful task, tool error rate and turns per task. For agents, grade the end state and the path, as in trajectory evals, not just the final answer. Most harness changes trade one of these against another. You want to see the trade before production does.
08How the harness crosses the rest of the stack
The harness is where an AI project stops being an AI project. The sandbox and credential broker are security engineering. Where the harness runs, how it handles provider rate limits, and how it deploys are cloud and DevOps. Transcripts are a dataset full of customer content, with retention, access control and lineage obligations. The approval queue is a product surface someone has to design. And whether the agent is worth running at all is a strategy question about cost per outcome. When agents fail in production, the cause is usually at one of these seams rather than in the model. Our post on agent failure modes in production catalogues the common ones.
09FAQ
Is an agent harness the same as an agent framework?
No. A framework is a library of parts. A harness is a specific configured runtime: these tools, this policy, this context strategy, this loop, for this job. You can build a harness with a framework, an SDK or plain code. Two teams using the same framework can ship harnesses that perform very differently.
Does a better model make the harness less important?
It shifts what matters rather than removing it. Stronger models need less hand-holding in prompts and recover from more tool errors on their own. They also get trusted with longer runs and more dangerous tools, which raises the stakes on permissions, budgets, sandboxing and state. Re-run your harness evals on every model upgrade. Prompts and tool descriptions tuned for an older model often over-constrain a newer one.
Should I use MCP for my harness's tools?
Use the Model Context Protocol when you want tools that are reusable across harnesses or supplied by third parties. Use native tool definitions when the tools are specific to one agent and you want full control over descriptions and output shaping. Either way, the harness still owns permissions and output caps. MCP standardises how tools are connected, not whether a call should be allowed. Our post on building MCP servers agents can actually use goes deeper.
How small can a useful agent harness be?
Very small. mini-swe-agent reports over 74% on SWE-bench Verified with about 100 lines for the agent class and bash as its only tool. Small isn't the goal, though. The goal is that every component is deliberate. The minimal harness above is around 200 lines because it adds permissions, crash recovery and tracing, which a benchmark doesn't need and production does.
How do I compare two harnesses fairly?
Fix the model, model settings and task set. Run each harness several times per task, because agent runs are non-deterministic. Compare success rate, cost per successful task, tool error rate and turn count. Change one component at a time, or you won't know which change helped.
Where should human approval sit in the loop?
Between the model's tool request and execution, applied by risk class: auto-allow reads, ask for writes and anything external or irreversible, and deny what should never happen. Keep the approval prompt short and show the exact arguments. If approvals become frequent and always "yes", narrow the policy with allow rules instead of training people to click through.