Building an Agent Harness: Engineering Practices and Key Design Decisions for AI Coding Agents

    An agent harness is the programmatic layer that turns a large language model into a working AI coding agent. This article explains why a harness is needed, breaks down its six core components—model invocation, tool scheduling, permissions, context management, state persistence, and observability—walks through a reference execution loop, and covers cost control, evaluation, failure recovery, human-in-the-loop design, common pitfalls, and practical rollout advice.

    Why an Agent Harness Needs to Exist

    A large language model by itself only generates text from input. To complete multi-step tasks—reading a codebase, modifying files, running tests, and adjusting based on the results—you need a programmatic orchestration layer around the model. The industry commonly refers to this layer as an agent harness. It converts model output into executable actions and feeds execution results back to the model.

    Without this layer, common problems include unstable tool call formats, context overflow in long tasks, unrecoverable errors, unclear permission boundaries, and execution processes that are hard to audit. These issues are partly related to model capability, but they are mostly engineering problems that require deterministic program logic for constraint and fallback handling.

    Core Components

    1. Model Invocation Layer

    This layer communicates with model services and wraps request parameters, timeouts, retries, and streaming output handling in a unified way. It should isolate interface differences between services so that upper-level logic only deals with a single message structure. Two points are worth noting: only requests that can be safely replayed are suitable for automatic retries, and a cap should be placed on single-response length to prevent a single request from consuming too many tokens.

    1. Tool Registration and Scheduling

    Each tool must declare its name, purpose description, parameter structure, and risk level. Parameter structures are typically described with JSON Schema. The harness parses tool call requests returned by the model, validates parameters against the schema first, and then decides whether to execute. When validation fails, the error message should be fed back to the model so it can correct itself, rather than aborting the task outright.

    1. Permissions and Security Boundaries

    Follow the principle of least privilege. File read and write access should be confined to the working directory, and network access should be limited to whitelisted endpoints. Irreversible operations—deletion, publishing, payments—must require human confirmation. High-risk tools should run in an isolated sandbox, which can be implemented with containers or lightweight virtualization, with limits on CPU, memory, and runtime.

    1. Context Management

    Long tasks accumulate historical messages continuously. Common practices include truncating and summarizing tool outputs, keeping only file fragments relevant to the current step, writing key decisions to external notes files, and triggering compression as context approaches its limit. When compressing, preserve the user’s original goal, completed steps, open questions, and constraints—losing this information directly causes the task to drift off course.

    1. State Persistence

    Task state should be persisted to disk, including plan lists, executed actions, intermediate artifacts, and failure records. After a process crash, the system can resume from a checkpoint, and the records also help with later reviews. Object storage or a relational database can be used. The key is a clear schema and atomic writes for each state update, to avoid half-written intermediate states.

    1. Observability

    Log an input summary, model output, tool calls, latency, and token usage for every turn. Core metrics include task success rate, average step count, cost per task, tool failure rate, and frequency of human intervention. Logs must be sanitized—keys and sensitive user data must never be written to logs. General-purpose capabilities such as logging services and monitoring alerts can be reused directly.

    A Reference Execution Loop

    The following code shows the basic loop of an agent harness. It is for illustrating structure only, not any specific implementation.

    1. MAX_STEPS = 30
    2. def run_task(goal, llm, tools, policy, store):
    3. messages = [system_prompt(), {"role": "user", "content": goal}]
    4. state = store.load_or_create(goal)
    5. for step in range(MAX_STEPS):
    6. messages = compact_context(messages, max_tokens=policy.context_limit)
    7. reply = llm.chat(messages, tool_schemas=tools.schemas())
    8. store.append_event(state.id, step, reply)
    9. if not reply.tool_calls:
    10. return reply.text
    11. for call in reply.tool_calls:
    12. ok, reason = policy.check(call)
    13. if not ok:
    14. result = f"Execution denied: {reason}"
    15. else:
    16. try:
    17. result = tools.run(call.name, call.args, timeout=policy.tool_timeout)
    18. except ToolError as e:
    19. result = f"Tool execution failed: {e}"
    20. messages.append(tool_message(call.id, truncate(result, policy.output_limit)))
    21. store.append_event(state.id, step, {"tool": call.name, "ok": ok})
    22. raise RuntimeError("Max steps exceeded; task terminated and requires manual review")

    This code reflects several principles. The step count must have an upper limit to prevent the model from falling into an infinite loop. Tool calls must pass a policy check before execution. Failure messages are fed back to the model, giving it a chance to correct itself. Every step is written to an event log, ensuring the process is replayable.

    Key Engineering Concerns

    Cost control: Token consumption grows roughly linearly with step count, so every task should have a budget cap. You can assign models by stage—for example, a lighter model for planning and a more capable model for critical reasoning. Whether to tier models depends on task quality requirements and must be validated with an evaluation set, not just intuition.

    Evaluation: Do not rely on single demos. Build a fixed task set covering normal paths, edge-case inputs, and deliberately injected error scenarios. Run it automatically after every change to the harness or prompts, and compare success rates, average step counts, and regressions.

    Failure recovery: Common failures include tool timeouts, parameter errors, and the model repeating the same action. Handle these with action deduplication detection, consecutive failure counters, and timeout circuit breakers. For example, if the same tool returns the same result three times in a row, the harness should proactively switch strategies or request human intervention.

    Human-in-the-loop: Place confirmation points before irreversible operations rather than asking the user at every step, which would break the workflow. Users can choose the level of automation at task start—for example, read-only operations run automatically, write operations require confirmation, and publishing requires double confirmation.

    Common Pitfalls

    First, equating the harness with prompt engineering. Prompts are only one part; permissions, state, and observability matter just as much.

    Second, assuming more tools is better. A growing tool count increases the probability of the model picking the wrong tool and consumes large amounts of context. A more reasonable approach is to dynamically load a subset of tools based on the task type.

    Third, ignoring cost and latency. A single request looks cheap, but costs amplify quickly in multi-step loops. Before launch, estimate the distribution of per-task costs rather than only looking at averages.

    Fourth, lacking replay capability. Without complete event records, you cannot determine whether a problem lies with the model, the tools, or the policy—troubleshooting becomes guesswork.

    Rollout Advice

    Start with a minimal closed loop: one model, three to five read-only tools, and a replayable event log. Validate task success rate and cost curves first, then gradually add write operations and sandbox isolation. Each time you expand capabilities, expand the evaluation set in step, so quality stays under control as capabilities grow.