Chapter 01 · 12 min read · Updated
What Is an Agent Harness?
A coding agent harness is the ordinary software wrapped around a model: it feeds context, runs tool calls, and keeps output on the rails.
Prefer one idea per screen? Read it as 12 slides →
In this chapter12
- 01.1The one-sentence version
- 01.2Concept explanation
- 01.3Why it matters
- 01.4How it works: two mental maps
- 01.5Real code: Codex splits the harness into crates
- 01.6Real code: OpenClaw treats the harness as a plugin
- 01.7A tiny illustration
- 01.8Real code: the model answers, the environment acts
- 01.9Real code: pi plugs a coding harness into a generic loop
- 01.10Read the source yourself
- 01.11Connecting to the bigger picture
- 01.12Key takeaways
01.1
The one-sentence version
A coding agent is not a smarter language model. It is an ordinary language model wrapped in a thick layer of regular software that feeds it context, runs the tools it asks for, and keeps it on the rails. That wrapping layer is called the harness, and it is the real product.
01.2
Concept explanation
When you use Claude Code or OpenAI's Codex in your terminal, it feels like one thing: a clever program that understands your code. It is actually two very separate things glued together.
The first thing is the model. It runs on Anthropic's or OpenAI's servers. It takes in a big blob of text and produces more text. It cannot touch your files. It cannot run a command. It has no memory of yesterday. Left alone, it can only talk.
The second thing is the harness. It runs on your machine (or in a managed sandbox). It is the CLI you launched. Every turn, the harness gathers up your instructions, your project's files, the conversation so far, and the list of tools the model is allowed to use, then sends all of that to the model. When the model says "run npm test," the harness is what actually runs npm test, captures the output, and hands it back. The model reasons; the harness acts.
A good analogy: the model is a brilliant consultant on the phone who has never seen your office. The harness is the assistant in the room who reads documents aloud to the consultant, writes down what the consultant says to do, walks over and does it, and reports back what happened. The consultant is smart, but without the assistant, nothing in the room actually changes. And a careless assistant (one who reads the wrong documents, or does dangerous things without checking) makes even a brilliant consultant useless.
This split is why the Mervin Praison breakdown of Claude Code insists that "Claude Code is not a CLI that calls Claude. It is an agentic harness." The model reasons; the harness mediates every action. That separation is exactly what makes the system feel magical while staying debuggable, because once you can name the layers, you can reason about where things go wrong.
01.3
Why it matters
Here is the practical punchline, and it shows up in nearly every source in this collection: investing in the harness usually beats tweaking the prompt.
If your agent keeps doing the wrong thing, your instinct is to rewrite the system prompt. Sometimes that helps. But the engineers who build these systems consistently find that the bigger wins come from better tool descriptions, better permission rules, better memory files, and better context management. The Snyk team that studied Cursor's security agents found the prompt driving a system that catches hundreds of real vulnerabilities was a mere fifteen lines. The prompt was simple precisely because the infrastructure underneath it (state tracking, deduplication, deployment, orchestration) was not. The harness was carrying the weight.
So if you want to build a capable agent, most of your effort is not going to be prompt wording. It is going to be plumbing. This guide is mostly about that plumbing.
01.4
How it works: two mental maps
Different sources slice the harness in different ways. Two slicings are worth keeping in your head as a map for the rest of the guide.
Map A: the six layers (from the Claude Code architecture breakdown)
This view puts a simple loop in the middle and wraps six concentric layers around it.
| Layer | What it does | Where in this guide |
|---|---|---|
| 1. Input | Session boundary, trust, what the agent is allowed to do | Ch 7 |
| 2. Knowledge | Persistent instructions and context that survive long sessions | Ch 9 |
| 3. Execution | Dispatching tools and running the loop | Ch 2, 6 |
| 4. Integration | External systems and packaged extensions (MCP, plugins) | Ch 10 |
| 5. Multi-agent | Delegated work that does not blow up the main context | Ch 11 |
| 6. Observability | Deterministic control and audit points (hooks, checkpoints) | Ch 12 |
The key phrase from that breakdown is that the loop in the center is "the dumb part on purpose." The intelligence is not in some clever orchestration engine. It is in the model's reasoning plus the quality of the layers around it.
Map B: the seven pillars (from the "Agentic Harness Architecture" breakdown)
This view is more opinionated and more builder-focused. It lists seven things a production harness gets right, and for each one it separates what the platform gives you for free from what you have to architect yourself.
| Pillar | The core idea | Where in this guide |
|---|---|---|
| 1. Context engineering | Decide what enters the context window, and what stays out | Ch 3, 4, 5 |
| 2. Memory management | Knowledge that lives outside the model's weights | Ch 9 |
| 3. Skills as workflow encoding | Package a repeatable procedure the agent loads on demand | Ch 10 |
| 4. Agent contracts and orchestration | Give each subagent a clear input/output contract | Ch 11 |
| 5. Tiered execution | Answer cheaply when you can, escalate only when you must | Ch 5, 11 |
| 6. Deterministic computation | Push exact work into code, not the model's head | Ch 10 |
| 7. Portability and shareability | The whole setup lives in the repo, so a teammate can clone it | Ch 9, 16 |
The seven pillars breakdown adds one more idea that deserves a spot of its own: the anti-hallucination contract. The most important rule for any agent handling real data is that if a tool can fetch the truth, the agent must not be allowed to make the answer up. We will return to this in Chapters 10 and 13.
Do not memorize either table. The point is that "harness" is not one blob. It is a set of distinct problems (context, memory, tools, safety, delegation, observability) that you can attack one at a time. That is exactly how the rest of this guide is organized.
01.5
Real code: Codex splits the harness into crates
The six-layer table in "How it works: two mental maps" names the jobs around the model: input, knowledge, execution, integration, multi-agent, and observability. Codex, OpenAI's coding agent, puts each job in its own Rust crate, one library or program. codex-rs/Cargo.toml, at this commit, lists 157 of them. The request that reaches the model is codex-api, one dependency of core. Most of the other names are harness: permissions, hooks, sandboxing, memory, session files, telemetry, and tools.
"skills",
"core", # [1]
"core-api",
"core-plugin-common",
"core-plugins",
"diagnostics",
"guardian-context",
"hooks", # [2]
"history",
"http-client",
"secrets",
"exec",
"file-system",
"exec-server-protocol",
"exec-server",
"exec-server/tests/support",
"execpolicy", # [3]
"ext/agent",
Source: openai/codex, codex-rs/Cargo.toml (Apache-2.0)
"linux-sandbox", # [4]
"lmstudio",
"login",
"codex-mcp",
"memories/read",
"memories/write",
# ... (5 lines)
"ollama",
# ... (6 lines: process hardening, voice, the protocol crate, prompts)
"rollout",
"rollout-trace",
# ... (3 lines)
"sandboxing",
# ... (1 line)
"otel",
# ... (4 lines: a trace websocket, the TCP tunnel, the terminal UI, user verification)
"tools",
Source: openai/codex, codex-rs/Cargo.toml (Apache-2.0)
What to notice
- [1]
coreis the business logic the Codex UIs call, which its readme says in the first paragraph. In the six-layer table, this is the execution layer, the loop. The model call is the separatecodex-apiclient. - [2]
hooksruns your code at named moments, including before a tool runs. TheHarnessclass later in this chapter has no such pause: the model asks, and that class runs the tool.historyholds the types for model history and for persisted rollout records.rolloutstores the session files. - [3]
execpolicyis the permission check that class stores inpermissions. A rule matches the start of a command, written in Starlark, a small configuration language, and the decision isallow,prompt, orforbidden. That is the input layer.skillsloads skill folders, and it notices when a command reads a skill document or runs a skill script. - [4]
linux-sandboxconfines a command on Linux. Its readme says bubblewrap for filesystem and namespace isolation, and seccomp to filter system calls.sandboxingis the shared policy for Linux, macOS, and Windows.memories/readinjects saved notes into the prompt.otelexports logs, traces, and metrics.toolsbuilds the tools the model may call.
Read it yourself: Open codex-rs/core/Cargo.toml and find codex-api, codex-execpolicy, and codex-hooks. Then read the three decision values in codex-rs/execpolicy/README.md.
01.6
Real code: OpenClaw treats the harness as a plugin
OpenClaw is a personal assistant that runs on your computer and meets you in chat apps. Its readme says you can swap agent harnesses, the programs that call the model and run tools, without changing the rest of the setup. Sandbox and workspace rules do not automatically come along. Every harness fills one small type, a list of fields an object must have. Only four fields are required. supports answers whether this harness can serve this request. runAttempt runs one turn.
type AgentHarnessContract<
// ... (2 type parameters)
> = {
id: string;
label: string;
// ... (24 lines: provider lists, remote placement, and context management)
/** Core must reject containment this runtime cannot implement before invoking it. */
executionEnvironment?: "host-only"; // [1]
// ... (11 lines: which tool and model policies this harness promises to enforce exactly)
supports(ctx: AgentHarnessSupportContext): AgentHarnessSupport; // [2]
// ... (42 lines: setup checks, session ownership, credentials, per-turn tool limits)
runAttempt(params: TAttemptParams): Promise<AgentHarnessAttemptResult>; // [3]
Source: openclaw/openclaw, src/agents/harness/types.ts (MIT)
What to notice
- [1]
host-onlymeans this runtime runs on the Gateway host, the machine running OpenClaw. Core always rejects it when a sandbox is required, when execution is remote, or when this run requires a workspace boundary. Workspace-only files, a sandbox that is already on, a permission mode that is not full access, and tool restrictions are rejected too, unless this agent has already consented to this harness. That consent is remembered for the agent, and it does not lift the three refusals above. The built-in harness leaves the field unset, so this check does not apply to it. - [2]
ctxis the provider, model, and route for this turn. The return,AgentHarnessSupport, is yes or no, plus an optional priority and a reason. Auto mode asks plugin harnesses only. The built-in harness is not in that list. If none can serve the request, OpenClaw uses its own. The built-in id isopenclaw, and a plugin is not allowed to register that id. - [3]
runAttemptreceives the inputs for this turn and returns one attempt result. The built-in harness implements it by callingrunEmbeddedAttempt. The Codex plugin implements it by callingrunCodexAppServerAttempt. Same method, two programs.
Read it yourself: In src/agents/harness/selection-decision.ts, read the comment that the built-in harness is not part of the plugin candidate list. Then compare runAttempt in builtin-openclaw.ts with runAttempt in extensions/codex/harness.ts.
01.7
A tiny illustration
There is no real MVP for this chapter, because the harness is the thing we spend the whole book building. But here is the shape of the split in code, just to make it concrete. Notice how little the "agent" knows how to do on its own.
# The model is just a function: text in, text (or a tool request) out.
# It cannot do anything else. Everything else is the harness's job.
def call_model(prompt: str, tools: list) -> dict:
"""Stand-in for an API call to Claude or GPT.
Returns either {"type": "text", ...} or {"type": "tool_call", ...}.
The model NEVER runs the tool itself; it only asks."""
...
# The harness is everything around that function: it owns the files,
# the shell, the permissions, the memory, and the loop.
class Harness:
def __init__(self):
self.tools = {} # Ch 6: what the model is allowed to ask for
self.history = [] # Ch 3: the conversation so far
self.memory = "" # Ch 9: persistent project knowledge
self.permissions = {} # Ch 7: what may run without asking
def run(self, user_request: str):
# Ch 2 turns this comment into a real loop. For now, just note
# that the harness, not the model, is in the driver's seat.
...
The model is a single stateless function. The Harness class is where all the chapters live. Every later chapter fills in one of those attributes or methods.
01.8
Real code: the model answers, the environment acts
The Harness class you just read stores tools, history, memory, and permissions together, and call_model only talks. mini-swe-agent, a small Python coding agent, makes the same cut with protocols. A protocol is a list of methods any matching class must have. The model protocol has query and no execute. The environment protocol has execute and no query.
class Model(Protocol):
"""Protocol for language models."""
config: Any
def query(self, messages: list[dict[str, str]], **kwargs) -> dict: ... # [1]
def format_message(self, **kwargs) -> dict: ...
def format_observation_messages( # [2]
self, message: dict, outputs: list[dict], template_vars: dict | None = None
) -> list[dict]: ...
def get_template_vars(self, **kwargs) -> dict[str, Any]: ...
def serialize(self) -> dict: ...
class Environment(Protocol):
"""Protocol for execution environments."""
config: Any
def execute(self, action: dict, cwd: str = "") -> dict[str, Any]: ... # [3]
def get_template_vars(self, **kwargs) -> dict[str, Any]: ...
def serialize(self) -> dict: ...
Source: SWE-agent/mini-swe-agent, src/minisweagent/__init__.py (MIT)
What to notice
- [1]
querytakes the transcript and returns one dict. InLitellmModel, that dict is the assistant message, and the parsed actions sit onextra. The full API response isextra["response"]. The method calls the API. It does not run a command. If the reply names a tool the parser does not know, it raisesFormatErrorinstead of guessing. - [2]
format_observation_messagesturns command output into transcript messages. The tool-calling formatter usesrole: "tool"andtool_call_id, the id of the call this result answers. The text formatter usesrole: "user", because that model class does not pass a tools list to the API. - [3] On the normal path,
executereturns a result dict. If the command printsCOMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUTand exits 0,LocalEnvironmentraisesSubmittedinstead, and that is the environment ending the task. A sandbox is a different class with this sameexecute.
Agent, like the other two, has config, and the only methods it adds are run and save. The class that implements it is the glue the sketch left as ...: step asks the model, then runs the actions in that reply.
Read it yourself: Read query at line 81 of src/minisweagent/models/litellm_model.py, then _query just above it. You should find litellm.completion there, and no subprocess in the file. Then read execute in src/minisweagent/environments/local.py through _check_finished. Write down the keys of both dicts. The success path has output, returncode, and exception_info. The error path adds extra. Then open step in src/minisweagent/agents/default.py. It is one line: ask, then execute.
01.9
Real code: pi plugs a coding harness into a generic loop
mini-swe-agent keeps the model, the environment, and the agent in one program. pi splits them. @earendil-works/pi-agent-core streams a reply and runs tools, and it does not know about a git repo. @earendil-works/pi-coding-agent is the coding harness: createAgentSession hands that generic Agent a session and a way to call the model. thinkingLevel is how much reasoning to request. Two fields go in empty.
const agent = new Agent({ // [1]
initialState: {
systemPrompt: "",
model,
thinkingLevel,
tools: [], // [2]
messages: existingSession.messages, // [3]
},
convertToLlm: convertToLlmWithBlockImages,
streamFn: async (model, context, options) => {
const requestOptions = buildRequestOptions(model, options);
// ... (8 lines: warm this session's prompt cache)
return modelRuntime.streamSimple(model, context, requestOptions); // [4]
},
// ... (3 lines: extension hooks on the raw provider request and response)
sessionId: sessionManager.getSessionId(),
transformContext: async (messages) => {
const runner = extensionRunnerRef.current;
if (!runner) return messages;
return runner.emitContext(messages);
},
steeringMode: settingsManager.getSteeringMode(),
followUpMode: settingsManager.getFollowUpMode(),
// ... (3 lines: transport, thinking budgets, retry delay)
});
Source: earendil-works/pi, packages/coding-agent/src/core/sdk.ts (MIT)
What to notice
- [1]
Agentcomes from@earendil-works/pi-agent-core. It does not import the coding tools (read,bash,edit,write). The coding harness creates those and attaches them later. - [2]
toolsandsystemPromptare empty, socreateInitialSystemMessagereturns nothing and this constructor adds no system message. Settings and thetoolsoption are already reduced toinitialActiveToolNames, which is not on the agent yet._applyToolLoadoutassignsagent.state.toolslater.prepareLoadoutcan adjust those declarations first. If a prompt section changed,_preparePromptAndToolLoadoutreturns a system message with emptycontentand, insections, only the sections whose text changed. TheHarnessclass createsself.toolsonce. - [3]
messagesis a projection of an append-only session file.hasExistingSessionis true when that list is non-empty, so an empty projection is a new session. - [4] This
streamFnfills timeout andmaxRetriesfrom settings, then callsmodelRuntime.streamSimple, which loads the API key. The generic agent already hasgetApiKeyandmaxRetryDelayMs. This session leaves the key to the runtime and passes the retry delay on its own. The eight hidden lines start a cache warmer whenoptions.sessionIdequals this session's id.
transformContext runs before the model call. emitContext clones the list: context handlers see no system messages, and context_with_system handlers then see the full list. steeringMode waits until the current assistant message has finished its tool calls, and those calls still run.
Read it yourself: Read createInitialSystemMessage in packages/ai/src/utils/transcript.ts. Then find initialActiveToolNames in sdk.ts, and this.agent.state.tools = declared at agent-session.ts line 1623.
01.10
Read the source yourself
Read these in order. Every link is the commit this chapter quoted.
- Three protocols, then the glue. Start at mini-swe-agent
src/minisweagent/__init__.py, including the shortAgentprotocol under the two you already saw. Readqueryand_queryinmodels/litellm_model.py, thenexecutethrough_check_finishedinenvironments/local.py. Finish withstepinagents/default.py. You want the agent to call the model, then the environment. - The same split, as crates. Re-open the two slices of Codex
codex-rs/Cargo.toml. Then readcore/Cargo.tomluntil you have foundcodex-api,codex-execpolicy, andcodex-hooks. Then the first screen oflinux-sandbox/README.mdfor bubblewrap and seccomp. - A generic loop, filled in by a coding harness. Re-read the
new Agent({block in pipackages/coding-agent/src/core/sdk.ts. ThencreateInitialSystemMessageinpackages/ai/src/utils/transcript.ts, andinitialActiveToolNamesearlier in the samesdk.ts. The assignmentthis.agent.state.tools = declaredis at line 1623. The package readmepackages/agent/README.mddraws the same path:transformContext, thenconvertToLlm, then the model. - One product, several harnesses. Re-read the contract in OpenClaw
src/agents/harness/types.ts. ThenrunAttemptinbuiltin-openclaw.ts, andsupportsplusrunAttemptinextensions/codex/harness.ts. Finish inselection-decision.ts, where a forcedopenclawruntime and an auto selection that found no plugin both end at the built-in harness.
Exercise: In Codex, open codex-rs/execpolicy/tests/basic.rs and find justification_is_attached_to_forbidden_matches. The rule's pattern is only ["rm"], the decision is forbidden, and the command under test is rm -rf plus a path. Write down why a one-token prefix catches the rest of that command. That test is exercising the permission layer the Harness class stores in permissions.
01.11
Connecting to the bigger picture
This chapter is the frame. Chapter 2 starts filling it in with the most important moving part, the loop that drives call_model over and over until the work is done. Keep the two maps nearby: when a later chapter talks about compaction, you will know it belongs to "context engineering" (pillar 1) and the "knowledge" layer (layer 2). When it talks about guardian subagents, you will place it in "input" and "multi-agent." The maps turn a pile of techniques into a structure.
01.12
Key takeaways
- A coding agent is a stateless model plus a stateful harness. The model reasons and asks; the harness gathers context, runs tools, and enforces rules.
- The famous rule of thumb: building an agent is roughly 5% calling the model in a loop and 95% harness work (context, tools, sandboxing, error handling).
- Improving the harness (tool descriptions, permissions, memory, context management) usually beats fiddling with the prompt.
- Two useful maps: the six layers (input, knowledge, execution, integration, multi-agent, observability) and the seven pillars (context, memory, skills, contracts, tiered execution, deterministic computation, portability).
- The central loop is "dumb on purpose." Intelligence comes from the model plus the quality of the surrounding layers.
0 of 12 slides completed
Your learning progress stays in this browser.
Self-check · 5 questions
01 / 05
According to the chapter, why was the Snyk/Cursor security agent prompt only fifteen lines long?