Skip to content

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.

LayerWhat it doesWhere in this guide
1. InputSession boundary, trust, what the agent is allowed to doCh 7
2. KnowledgePersistent instructions and context that survive long sessionsCh 9
3. ExecutionDispatching tools and running the loopCh 2, 6
4. IntegrationExternal systems and packaged extensions (MCP, plugins)Ch 10
5. Multi-agentDelegated work that does not blow up the main contextCh 11
6. ObservabilityDeterministic 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.

PillarThe core ideaWhere in this guide
1. Context engineeringDecide what enters the context window, and what stays outCh 3, 4, 5
2. Memory managementKnowledge that lives outside the model's weightsCh 9
3. Skills as workflow encodingPackage a repeatable procedure the agent loads on demandCh 10
4. Agent contracts and orchestrationGive each subagent a clear input/output contractCh 11
5. Tiered executionAnswer cheaply when you can, escalate only when you mustCh 5, 11
6. Deterministic computationPush exact work into code, not the model's headCh 10
7. Portability and shareabilityThe whole setup lives in the repo, so a teammate can clone itCh 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. [1] core is 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 separate codex-api client.
  2. [2] hooks runs your code at named moments, including before a tool runs. The Harness class later in this chapter has no such pause: the model asks, and that class runs the tool. history holds the types for model history and for persisted rollout records. rollout stores the session files.
  3. [3] execpolicy is the permission check that class stores in permissions. A rule matches the start of a command, written in Starlark, a small configuration language, and the decision is allow, prompt, or forbidden. That is the input layer. skills loads skill folders, and it notices when a command reads a skill document or runs a skill script.
  4. [4] linux-sandbox confines a command on Linux. Its readme says bubblewrap for filesystem and namespace isolation, and seccomp to filter system calls. sandboxing is the shared policy for Linux, macOS, and Windows. memories/read injects saved notes into the prompt. otel exports logs, traces, and metrics. tools builds 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. [1] host-only means 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. [2] ctx is 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 is openclaw, and a plugin is not allowed to register that id.
  3. [3] runAttempt receives the inputs for this turn and returns one attempt result. The built-in harness implements it by calling runEmbeddedAttempt. The Codex plugin implements it by calling runCodexAppServerAttempt. 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. [1] query takes the transcript and returns one dict. In LitellmModel, that dict is the assistant message, and the parsed actions sit on extra. The full API response is extra["response"]. The method calls the API. It does not run a command. If the reply names a tool the parser does not know, it raises FormatError instead of guessing.
  2. [2] format_observation_messages turns command output into transcript messages. The tool-calling formatter uses role: "tool" and tool_call_id, the id of the call this result answers. The text formatter uses role: "user", because that model class does not pass a tools list to the API.
  3. [3] On the normal path, execute returns a result dict. If the command prints COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT and exits 0, LocalEnvironment raises Submitted instead, and that is the environment ending the task. A sandbox is a different class with this same execute.

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. [1] Agent comes 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. [2] tools and systemPrompt are empty, so createInitialSystemMessage returns nothing and this constructor adds no system message. Settings and the tools option are already reduced to initialActiveToolNames, which is not on the agent yet. _applyToolLoadout assigns agent.state.tools later. prepareLoadout can adjust those declarations first. If a prompt section changed, _preparePromptAndToolLoadout returns a system message with empty content and, in sections, only the sections whose text changed. The Harness class creates self.tools once.
  3. [3] messages is a projection of an append-only session file. hasExistingSession is true when that list is non-empty, so an empty projection is a new session.
  4. [4] This streamFn fills timeout and maxRetries from settings, then calls modelRuntime.streamSimple, which loads the API key. The generic agent already has getApiKey and maxRetryDelayMs. This session leaves the key to the runtime and passes the retry delay on its own. The eight hidden lines start a cache warmer when options.sessionId equals 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.

  1. Three protocols, then the glue. Start at mini-swe-agent src/minisweagent/__init__.py, including the short Agent protocol under the two you already saw. Read query and _query in models/litellm_model.py, then execute through _check_finished in environments/local.py. Finish with step in agents/default.py. You want the agent to call the model, then the environment.
  2. The same split, as crates. Re-open the two slices of Codex codex-rs/Cargo.toml. Then read core/Cargo.toml until you have found codex-api, codex-execpolicy, and codex-hooks. Then the first screen of linux-sandbox/README.md for bubblewrap and seccomp.
  3. A generic loop, filled in by a coding harness. Re-read the new Agent({ block in pi packages/coding-agent/src/core/sdk.ts. Then createInitialSystemMessage in packages/ai/src/utils/transcript.ts, and initialActiveToolNames earlier in the same sdk.ts. The assignment this.agent.state.tools = declared is at line 1623. The package readme packages/agent/README.md draws the same path: transformContext, then convertToLlm, then the model.
  4. One product, several harnesses. Re-read the contract in OpenClaw src/agents/harness/types.ts. Then runAttempt in builtin-openclaw.ts, and supports plus runAttempt in extensions/codex/harness.ts. Finish in selection-decision.ts, where a forced openclaw runtime 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?

Related chapters