Harness engineering: everything around the model
An agent is a model plus a harness. The model produces text. The harness supplies state, tools, a place to run code, memory, limits and a way to survive a crash. Most of the reliability you get from an agent comes from this layer.
Harness engineering in 60 seconds
- What: the harness is everything in an agent that is not the model: prompts, tools, a workspace, a sandbox, memory, limits, hooks and the runtime that drives the loop.
- How to design it: start from a behaviour you want, then ask which harness feature produces it. A model alone cannot keep state, run code or see fresh facts.
- Core primitives: a filesystem, general-purpose execution, an isolated sandbox, memory files and context controls.
- Long tasks: treat each session as a shift change. Leave a plan, a progress file and clean commits for the next one.
- Production: make every model call and tool call a persisted, retryable step, with idempotency keys and spend limits.
The problem it solves
A model takes text in and puts text out. On its own it cannot remember yesterday, run a test, read a file that was not pasted in, or find out what happened this morning. It also cannot decide that it has been working for too long. Every one of those gaps is closed by code that sits around the model.
A useful habit is to work backwards. Write down the behaviour you want, such as "finishes a two-day refactor without losing track", and then name the harness feature that makes it possible. If you cannot name one, the behaviour will depend on luck.
Anatomy of a harness
Most harnesses contain the same five parts, whatever the domain. Instructions and tool descriptions shape what the model attempts. Infrastructure gives it a place to work. Orchestration decides who runs next and on which model. Hooks add deterministic behaviour at fixed moments. A runtime keeps the whole thing alive.
- Instructions and tools: the system prompt, tool schemas and their descriptions, and short skill summaries.
- Infrastructure: a filesystem, a sandbox for running commands, and sometimes a browser.
- Orchestration: sub-agents, hand-offs and routing of easy steps to a cheaper model.
- Hooks and middleware: code that runs at set points, for example to compact history, force a continuation or run a linter.
- Runtime: the part that triggers runs, persists steps, retries failures and records traces.
The primitives that earn their place
The filesystem is the most useful base primitive. It gives the agent a workspace, a place to put output that does not fit in context, and a way to keep work between sessions. People and agents can also share it. Put it under version control and you gain history, rollback and branches for free, which makes bold changes safer to try.
General-purpose execution comes next. A shell and a code interpreter let the agent do things you never wrote a tool for, and even build its own small tools on the fly. This beats a hand-made tool for every action, which grows into an unmanageable list. Keep the dedicated tools for operations that need strict control, and let everything else go through code. The design of those dedicated tools has its own page: tool design.
Execution needs a sandbox. A good one is isolated from the network by default, allows only listed commands, is created when a task starts and is destroyed when it ends. Because it is cheap to create, you can fan out one per task. Give it sensible defaults, such as language runtimes, a test runner and a headless browser, so the agent can check its own work by running tests, reading logs and looking at screenshots.
Memory comes in two forms. One is an instruction file that is loaded at the start of every session and that the agent may update when it learns something durable. The other is search, which supplies facts newer than the model's training. See working memory and procedural memory for the underlying ideas.
Controlling the context window
Quality drops as the window fills with stale tool output and old reasoning. People call this context rot. The harness is the only place that can fight it, because the model cannot see what it has forgotten.
- Tool-output offloading: keep the first and last lines of a large result in context and write the full text to a file the agent can search.
- Progressive disclosure: load only a short description of each skill, and fetch the full instructions when the agent picks one.
- Within-run pruning: clear or trim old tool results, but keep the last few iterations intact so the agent does not lose its thread.
- Across-run compaction: when session history passes a token threshold, summarise it and start the next run from the summary.
- Budget warnings: tell the agent when few iterations remain, so it wraps up and does not stop mid-edit.
- Overflow recovery: if a call fails for length, compact by force and retry the same step. The retry should not use up an iteration.
Order matters for cost as well. Keep the system prompt, tool schemas and stable instructions at the front, in the same order on every call, and append the changing material at the end. That keeps the prefix identical, which is what a prefix cache needs to work. Moving a timestamp to the top of the prompt can quietly double your bill.
Long-horizon work
An agent that works for hours starts every session knowing nothing, like an engineer arriving at the start of a shift. The fix is the same as for people: a handover. The first session does set-up only. It writes a plan or feature list, creates a progress file and makes a first commit. Every later session reads those, does one increment of work, runs the checks, commits and updates the progress file.
Two hooks make this robust. A continuation hook catches the moment the agent says it has finished and, if the goal is not met, restarts it in a fresh context with the goal restated. A verification hook runs the tests after each increment and sends failures straight back. One rule matters more than the rest: do not let the worker decide that the whole goal is done. A separate check, ideally a deterministic one, should make that call. See long-running agent and coding agent.
Harness versus framework
Retries, persistence, queues, routing, concurrency and traces are infrastructure problems, and they were solved long before agents. A durable, event-driven runtime handles them well. Every model call and every tool call becomes a persisted step that can be retried alone. A worker that crashes halfway through a long task picks up from the last saved step, so earlier model calls are never paid for twice.
Split the system into small functions. One acknowledges a message at once, so the user sees a response. One runs the loop. One delivers the reply. One handles failures. One runs scheduled maintenance, such as compaction. Use a session key for singleton concurrency, so there is only ever one run per conversation. When a new message arrives, cancel the running loop and restart with the full history. Steering an agent in the middle of a run is still hard, and cancel-and-restart is the honest, simple answer.
Sub-agents run as separate invoked functions with their own context window. Give them the same tools minus the ability to delegate, which prevents recursive spawning, and have them return a short summary and not their whole transcript. For human approval, use a wait-for-event step. The run sleeps at no cost until an approval event arrives or a timeout fires. See the human checkpoint pattern.
A worked example
Acme Logistics runs an agent that migrates customer integrations to a new API. A typical job touches 40 files and needs about 120 model calls and 90 tool calls. The first version ran as one long process on a single machine.
- Crash cost: the process failed on call 87 in roughly 1 job in 12. Each failure replayed all 87 calls, which cost about 2.60 pounds and 14 minutes.
- Durable steps: after moving to persisted steps, a crash on call 87 resumes at call 87. The retry costs one call, roughly 3 pence.
- Double actions: 1 in 30 retried jobs had created a duplicate ticket, because the ticket tool had run twice. An idempotency key built from the run ID and step number removed the duplicates.
- Context: compaction at 70 percent of the window cut the average prompt from 58,000 to 31,000 tokens, with the success rate unchanged at 91 percent.
- Spend limit: a cap of 400 calls per run stopped one looping job at 5 pounds, where before it ran to 40 pounds.
Building it
import hashlib
MAX_STEPS_PER_RUN = 400 # hard cap on model and tool calls per run
MAX_SPEND_PENCE = 500 # spend limit per run, in pence
MAX_STEP_PAYLOAD_BYTES = 64_000 # larger outputs go to a file, not the log
DESTRUCTIVE = {"delete_record", "send_email"} # tools that need approval
def run_step(run, step_no, action):
# Stop before doing anything if a budget is spent.
if step_no > MAX_STEPS_PER_RUN or run.spend_pence > MAX_SPEND_PENCE:
return run.finish(status="budget_exhausted")
# A stable key means a retried step never repeats a side effect.
key = hashlib.sha256(f"{run.id}:{step_no}:{action.name}".encode()).hexdigest()
saved = store.get(key)
if saved is not None:
return saved # replay: reuse the recorded result
# Destructive tools wait for a person. Placeholder for a wait-for-event step.
if action.name in DESTRUCTIVE and not run.approved(action):
return run.wait_for_approval(action, timeout_hours=24)
result = tools.call(action, idempotency_key=key, timeout_s=30)
# Keep big outputs out of the persisted step.
if len(result.body) > MAX_STEP_PAYLOAD_BYTES:
result = workspace.offload(result, keep_head=40, keep_tail=40)
run.spend_pence += result.cost_pence
store.put(key, result) # persist before the next model call
return result
store, tools, workspace and the run object are placeholders. The points to copy are the order of operations: check budgets, look for a recorded result, gate destructive actions, call with a key, persist, then move on.
Design decisions
- Checkpoint granularity: persisting every call gives the finest resume point and the highest storage and latency cost. Persisting per group of calls is cheaper, but a crash repeats more work. Choose by the cost of a replayed call.
- Deterministic replay: record model outputs as well as tool results, so a replay follows the same path. Without that, a resumed run can diverge from the one that crashed.
- Payload cap: limit what a step may store, and push large outputs to files with a reference.
- Permission tiers: split tools into read-only, reversible and destructive. Allow the first freely, log the second and gate the third behind approval.
- Spend breakers: apply a circuit breaker per run and per tenant, so one stuck loop cannot drain a shared budget.
- Prompt ordering: fix the order of the stable prefix and treat any change to it as a cost event.
- Versioned configuration: store prompts, tool schemas and limits as one versioned bundle, and stamp each trace with its version. See idempotency for the retry rules.
Measuring it
- Harness A/B tests: hold the model fixed and change one harness setting, such as the compaction threshold, then compare task success on the same labelled set.
- Trace mining: group failed traces by cause, and turn the top three causes into harness fixes before touching a prompt.
- Resume rate and replay cost: how often runs resume after a fault, and the extra calls each resume costs.
- Context health: mean prompt size, share of runs that compact, and success rate before and after compaction.
- Cache hit rate: the share of prompt tokens served from a prefix cache.
- Duplicate action rate: side effects that happened twice. The target is zero.
- Budget stops: runs ended by a limit, split into genuine long tasks and loops.
When to use it, and when not to
| Situation | Harness approach | Why |
|---|---|---|
| Single question, one or two tool calls | Thin loop, no durable runtime | A restart costs seconds. The extra machinery is not worth it. |
| Tasks of many minutes with side effects | Durable steps and idempotency keys | A crash should resume, and a retry should never act twice. |
| Work that spans hours or days | Plan files, progress notes and continuation hooks | Each session starts blank, so the handover carries the state. See long-running agent. |
| Code that must be run or checked | Sandbox with defaults and test hooks | The agent can verify its own work. See coding agent. |
| Destructive or costly actions | Approval gates and spend breakers | A person or a limit should stand between the model and the damage. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Reliability | Durable steps, limits and gates turn crashes and loops into small, bounded events. | Fund the runtime early for any task that takes more than a few minutes. |
| Latency | Persisting steps and waiting for approval add delay to each action. | Persist at sensible granularity, and gate only the actions that are costly to undo. |
| Cost | Harness work needs engineering time, storage and sandbox capacity, but it cuts replay and runaway spend. | Track cost per completed task, not per call. |
| Portability | A model tuned inside one harness may do worse in another, and the reverse can also happen. | Test harness changes on your own tasks before adopting them. |
Compared with related ideas
Context engineering decides what the model sees on one call. Harness engineering decides what happens across calls, crashes, sessions and tenants. The harness evolution page covers the control flow a harness uses, from chains to graphs to code. This page covers the supporting parts that every one of those designs needs.
An ordinary application framework gives you routing and structure. A harness also has to deal with an unpredictable caller in the middle of the loop, which is why limits, gates and verification are first-class parts of it.
What this means for your role
Common mistakes
Further reading
- Harness evolution: how control flow moved from chains to graphs to code.
- Context engineering: what goes into the window and why.
- Long-running agent: the pattern for work that spans many sessions.
- Coding agent: a harness built around running and testing code.
- Idempotency: the retry rules behind safe tool calls.
- Circuit breaker: the pattern behind spend limits.
- Prefix cache: why prompt order affects cost.
The model gets the attention, but the harness decides whether an agent is dependable. Build it from the behaviour you want, keep each part small and replaceable, and let traces tell you what to fix next.