Engineering Code Agents: From Models to Harness Engineering

    This article explains how a code agent client turns model capabilities into practical developer productivity. It covers what lies outside the model, including orchestration, tool interfaces, context management, permission models, and sandboxed execution. It proposes a layered architecture and engineering practices, and uses a release incident in which source map files shipped with an AI coding tool's client as a case study in build and release security.

    An AI coding tool’s client build artifacts shipped with source map files because of an oversight in the release configuration. As a result, a large amount of client code was exposed. The incident is a typical case of build and supply chain security. The more technically useful question is how a code agent client turns model capabilities into developer productivity. Client code is usually separate from the model service. What tends to leak is not model weights or training code, but orchestration strategies, tool interfaces, prompt templates, permission models, and internal interaction logic. This content shows the engineering complexity that sits outside the model.

    “Harness engineering” has been a frequently used term in the industry recently. The core idea is straightforward. Instead of expecting the model to become smarter, use a system to constrain its behavior. The model works like an engine, providing reasoning and generation. Client engineering works like the wiring harness, drivetrain, brakes, and dashboard. It determines whether the model’s capabilities are delivered stably, safely, and observably. This article presents a practical architecture and engineering practices for a general code agent implementation.

    1. The System Boundary: A Closed Execution Loop, Not Single-Turn Q&A

    A code agent is not simply “a longer code completion.” It is a closed loop of perceiving, deciding, acting, and observing. The model interprets intent, proposes plans, and selects tools. The client assembles context, executes tools, checks permissions, collects results, maintains state, and feeds observations back to the model for further reasoning. A single task may involve reading files, searching for symbols, generating patches, running tests, analyzing failures, and revising patches across many steps.

    The model sets the ceiling on a code agent’s capability. Client engineering mainly determines its usability, safety, and cost. Without an execution framework, the model can only output suggestions. With a controlled execution framework, the model can complete real work in a workspace.

    A complete code agent client can typically be divided into the following layers:

    1. Interaction and session layer: Handles multi-turn conversation, streaming output, task interruption, approval interaction, and session recovery. Long tasks must support checkpoints. Otherwise, a single interruption can lose all progress.
    2. Orchestration layer: Handles task parsing, plan decomposition, the execution loop, budget control, and state machine transitions. It decides when to continue, when to retry, and when to ask the user for confirmation.
    3. Context layer: Handles workspace indexing, file retrieval, snippet selection, summary compression, decision records, and memory management. Codebases are usually much larger than the context window, so context must be injected selectively.
    4. Tool layer: Provides atomic capabilities such as file reading and writing, search, patch application, command execution, test runs, and static checks. Tools are the only channel between the model and the real environment.
    5. Execution environment layer: Uses sandboxes, containers, or isolated workspaces to restrict access to files, networks, processes, and resources, so tool execution stays within bounds.
    6. Security policy layer: Handles permission decisions, risk grading, approval flows, path allowlists, sensitive information redaction, and auditing. The model should not be the security boundary. The policy engine should be.
    7. Observability and evaluation layer: Records task traces, tool parameters, execution results, approval records, latency, and cost. It supports replay, failure classification, and offline evaluation.
    8. Build and release layer: Handles artifact minimization, source map management, secret scanning, release gates, and supply chain security.

    3. The Execution Loop: Putting the Model in a State Machine

    The core of a code agent is a controlled loop. The following pseudocode shows the idea:

    1. task = parse_intent(user_input)
    2. context = context_manager.build(task)
    3. plan = planner.initial(task, context)
    4. for step in budget.steps:
    5. action = model.decide(task, plan, context)
    6. decision = policy_engine.check(action)
    7. if decision.requires_approval:
    8. action = await user_approve(action, decision.reason)
    9. if not decision.allowed:
    10. context = context_manager.record_rejection(action, decision)
    11. continue
    12. result = executor.run(action, sandbox)
    13. context = context_manager.update(context, action, result)
    14. trace.record(action, result, cost, latency)
    15. if evaluator.is_done(task, context):
    16. break
    17. plan = planner.revise(plan, context, result)
    18. return summarizer.final(task, context)

    Several points matter in this loop. First, the model only proposes actions and cannot bypass the policy layer. Second, every action produces a structured observation for the next round of reasoning. Third, step, time, and cost budgets are required to prevent infinite loops. Fourth, high-risk actions should enter an approval or dry-run mode. Fifth, traces must be recordable and replayable so that failure causes can be located.

    4. Tool Design: Few and Clear Beats Many and Messy

    More tools do not make a better agent. Too many tools raise the model’s selection cost and enlarge the attack surface. Tool design should follow principles such as atomicity, idempotence, auditability, readable errors, validatable parameters, and labeled permissions. For example, a patch tool should use a unified diff format, a command execution tool should apply risk grading, and a file write tool should restrict path boundaries.

    1. Tool:
    2. name: string
    3. description: string # Affects model selection. Must state when to use and when not to use it.
    4. input_schema: object # Parameter structure, types, and required fields
    5. risk_level: low|medium|high
    6. requires_approval: bool
    7. execute(input, sandbox) -> structured_result

    Tool descriptions are part of prompt engineering. A description should state what the tool does, when to use it, its input constraints, and what it returns on failure, so the model does not misuse it. Tool results should be structured, with a success status, an error type, readable information, and necessary evidence. Large amounts of irrelevant output should not be returned to the context.

    5. Context Management: Working Memory Must Be Rebuildable

    A code agent works on large workspaces, and the full set of files cannot fit into the context. Common strategies include retrieval based on symbols and dependency graphs, targeting by recent modifications and test failures, recall by semantic similarity, and selecting file snippets according to the task plan. The context layer should also maintain decision records, open items, a list of modified files, and test status, so the model does not lose track of the goal during a long task.

    Context compression requires care. Summaries must not drop key constraints, such as “do not modify a certain directory” or “keep interface compatibility.” Context pollution also needs to be prevented. External content returned by tools may contain misleading instructions, so it should be marked as untrusted data rather than executed as system instructions.

    6. Security and Permissions: Read-Only by Default, Writes Auditable

    A code agent has access to the file system and command execution, so security design must come first. Start with read-only access by default. Gate write operations and command execution behind approval based on risk level. Restrict paths to a workspace allowlist. Enable network access only when needed. Redact sensitive information from logs and context, and record audit logs for all high-risk actions. Defenses against prompt injection are equally important. Tool output, code comments, and external documents should all be treated as data and must not override system policy. A model can be induced to run dangerous commands, so the policy engine must independently verify action parameters and their potential impact.

    7. Error Recovery and Observable Evaluation

    Tool failures, failing tests, and model errors are normal. The system should support retry budgets, rollback, checkpoints, session recovery, and failure classification. The observability layer should record task traces, including user intent, context selection, model actions, tool parameters, execution results, approval records, latency, and cost. Evaluation metrics can include task success rate, test pass rate, first-attempt pass rate, rollback rate, approval rate, average number of steps, and the distribution of failure types. General-purpose capabilities from Baidu AI Cloud, such as object storage, log services, and container platforms, can support trace archiving, log retrieval, and isolated execution environments. Specific choices should account for the team’s compliance requirements and cost constraints.

    8. Build and Release Security: Lessons from the Source Map Exposure

    Source map files support debugging and error localization, but they should not be distributed publicly with production client packages. Before release, teams should minimize artifacts, separate development and production builds, and scan for source map files, secrets, debug symbols, and internal comments. Package manager release configurations should be included in code review, and automated release gates should block high-risk artifacts from reaching public channels. Client code is not equivalent to model weights. It can still expose tool registries, prompt templates, permission rules, and internal interfaces, so it carries real security value.

    In summary, the key to code agent implementation is not letting the model act freely. It is using an execution loop, tool contracts, context management, permission sandboxes, observable evaluation, and release gates to keep model capabilities on a governable track. This is the value of harness engineering: the model provides the power, and the engineering system determines whether it reaches its destination stably and safely.