Building an Agent Runtime from Scratch: A Complete Guide to Agent Harness Architecture

    As large language models grow more capable, many teams invest heavily in intricate decision trees and workflow orchestration for their agents—only to find performance falls short. The bottleneck is often not the model itself but its working environment. This article introduces the concept of the Agent Harness—the complete runtime of tools, knowledge, observation, action interfaces, and permissions surrounding the model—and walks through six architectural layers for building one from zero: the Agent Loop, tool systems, progressive knowledge loading, long-context management and task planning, multi-agent collaboration, and permission governance, along with a practical four-week implementation roadmap.

    Building an Agent Runtime from Scratch: A Complete Guide to Agent Harness Architecture

    1. Why We Need to Rethink the “Agent Runtime Environment”

    As large language model capabilities have rapidly improved, more and more developers are building agents that can autonomously complete complex tasks. Yet a common pattern has emerged: teams pour enormous effort into designing elaborate decision trees and complex workflow orchestration, only to discover that their agent underperforms expectations.

    Where does the problem lie? Usually not in the model itself, but in the “working environment” the model operates in.

    Consider an analogy: a brilliant engineer locked in an empty room—no internet, no editor, no documentation—cannot exercise their talent no matter how skilled they are. LLMs are the same. The model is the “brain,” but it needs hands (tools), eyes (observation interfaces), memory (context management), and rules (permission boundaries) to produce real value.

    The complete environment built around the model is commonly known as the Agent Harness. It can be summarized with a simple formula:

    1. Harness = Tools + Knowledge + Observation
    2. + Action Interfaces + Permissions

    This article starts from the most fundamental Agent Loop and breaks down, layer by layer, how to build this environment—helping you construct your own agent runtime foundation from scratch.

    2. Architectural Philosophy: Pave the Road for the Model, Don’t Walk It

    Before diving into technical details, one core design philosophy must be established: the Harness’s job is to provide the environment, not to make decisions on the model’s behalf.

    Many failed agent projects make the same mistake—trying to use hardcoded rules and decision trees to “predict” how the model should act. This approach has three fundamental flaws:

    1. Fragility: Real-world tasks vary endlessly. Predefined branches can never cover every situation, and the system breaks or behaves absurdly when it encounters an unanticipated scenario.
    2. Capability ceiling: Rigid flows effectively “compress” the model’s intelligence down to the level the designer imagined. The stronger the model, the greater the waste imposed by these constraints.
    3. Maintenance nightmare: Decision trees grow indefinitely with business requirements, eventually becoming legacy code nobody dares to touch.

    The correct approach is one of restraint: give the model clearly defined tools, on-demand knowledge, sound context management, and explicit permission boundaries—then “politely step aside” and let the model reason and act autonomously in a clean environment. The Harness is the stage and the props; the model is the actor.

    3. Layer One: The Agent Loop—The Foundation of Everything

    The origin of every agent system is a structure that looks simple but is profoundly important: the Agent Loop.

    1. def agent_loop(task):
    2. messages = [system_prompt, user_message(task)]
    3. while True:
    4. response = model.generate(messages, tools=tool_schemas)
    5. messages.append(response)
    6. if response.has_tool_calls():
    7. for call in response.tool_calls:
    8. result = execute_tool(call) # Execute the tool
    9. messages.append(tool_result(result))
    10. else:
    11. return response.text # Model considers the task complete

    The loop’s logic is plain: the model generates a response → if the response contains tool calls, execute them and append the results to the context → let the model generate again → repeat until the model produces a final answer with no tool calls.

    Notably, this loop contains no predefined task flow whatsoever. The model itself decides which tools to call, in what order, and when to stop. This is the minimal expression of the architectural philosophy described above: the loop is responsible only for “passing messages” and “executing tools”; all decision-making power rests with the model.

    Several engineering details matter in implementation: tool outputs need truncation protection to prevent oversized results from blowing up the context; the loop needs a maximum iteration count or timeout as a safety net; and tool execution errors must be fed back to the model in a structured way rather than interrupting the loop, giving the model a chance to self-correct.

    4. Layer Two: The Tool System—Giving the Model Reliable Hands

    Tools are the model’s only channel for interacting with the outside world. A practical coding agent’s toolset typically covers these categories:

    • Command execution: running shell commands—the most general and powerful capability, covering compilation, testing, package management, and script execution;
    • File operations: reading, writing, and precisely editing files. The “edit” tool typically works by “matching an old string and replacing it” rather than rewriting entire files, which reduces error rates;
    • Search tools: finding filenames by pattern (e.g., glob matching) and searching code by content (e.g., regex-based full-text search);
    • Network access: fetching web pages and calling external APIs for real-time information.

    Three key principles guide tool design:

    First, atomicity and orthogonality. Each tool does exactly one thing, with no functional overlap between tools. Prefer a small, sharp toolset over a large, redundant one—tool descriptions consume precious context, and too many similar tools confuse the model’s selection.

    Second, precision of description. The tool’s JSON Schema and natural-language description are the model’s only basis for understanding it. Descriptions should clearly state “when to use this tool and when not to,” with typical usage examples.

    Third, readability of errors. When a tool fails, the returned message should help the model understand why and adjust its strategy. “File not found—is the path wrong? Try the file search tool to confirm” is far more valuable than “Error: ENOENT.”

    5. Layer Three: On-Demand Loading of Knowledge and Skills

    As an agent takes on broader task domains, a tension emerges: we want the model to command large amounts of domain knowledge (project conventions, framework usage, internal standards), yet cramming all of it into the system prompt is neither economical nor realistic.

    The solution is progressive disclosure, commonly implemented as a “skill” mechanism:

    • Each skill is an independent knowledge package containing a short metadata description (name + one-sentence summary) plus full detailed content;
    • At startup, only the metadata descriptions of all skills are injected into the context—typically just a few dozen tokens each;
    • When the model determines the current task requires a skill, it “expands” that skill via a tool call, loading the full content into context.

    This design converts knowledge cost from “permanent overhead” to “pay-per-use,” allowing the system to carry hundreds or thousands of skills without overwhelming the context window. In essence, it follows the same idea as demand paging in an operating system’s virtual memory.

    6. Layer Four: Long-Context Management and Task Planning

    The context window is an agent’s scarcest and most easily exhausted strategic resource. Over long tasks, tool outputs and file contents pile up rapidly, demanding active governance. Common combined strategies in the industry include:

    1. Context compression: when the context approaches a threshold, have the model summarize the conversation history and replace the raw details with the summary, preserving key conclusions and state;
    2. Task planning tools: give the model an explicit “to-do list” tool so it can decompose large tasks into sub-goals and track completion status itself. This keeps the model from “losing its way” on long tasks and makes execution observable to humans;
    3. Structured task graphs: for more complex scenarios, tasks can carry dependencies (B can only start after A finishes), with the system maintaining the dependency graph and scheduling ready tasks.

    One counterintuitive conclusion about task planning: externalizing the planning process as explicit tool calls works far better than letting the model “think it through silently” in a single generation. An externalized plan can be persisted, inspected, and corrected mid-flight—it constitutes the agent’s reliable “working memory.”

    7. Layer Five: Multi-Agent Collaboration and Isolated Execution

    When a task exceeds what a single context window can hold, multi-agent mechanisms become necessary. A mature Harness typically provides three collaboration primitives:

    Sub-agent spawning: the main agent can spawn a sub-agent and assign it a self-contained sub-task (e.g., “find all call sites of a given function in the codebase”). The sub-agent owns an independent context window and returns only a summary of its conclusions to the main agent. This way, the bulk of exploratory intermediate work stays isolated in the sub-context and doesn’t pollute the main thread.

    Asynchronous communication: when multiple agents work in parallel, coordination is needed. An elegant implementation is the “mailbox” pattern—agents communicate via asynchronous messages rather than tightly coupled synchronous calls, reducing coordination complexity and deadlock risk.

    Isolated parallel execution: when multiple agents modify code simultaneously, operating in the same working directory leads to conflicts. Borrowing the workspace isolation idea from version control, each agent can be given an independent working copy—modifying and validating separately, with results merged through an integration process at the end. This guarantees the safety and reversibility of parallel exploration.

    8. Layer Six: Permission Governance—The Greater the Power, the Clearer the Boundaries

    Granting a model the ability to execute commands and modify files inherently introduces risk. Permission governance is not a nice-to-have; it is a non-negotiable foundation of the Harness. A sound permission system includes at least:

    • Tiered controls: classify tool operations by risk—read-only operations (reading, searching) are allowed by default; write operations (file editing) are confined to the workspace; high-risk operations (arbitrary command execution, network requests, deletions) require explicit confirmation;
    • Human in the loop: for irreversible operations, the system pauses, presents the impending action to the user, and proceeds only after approval;
    • Persistent rules: users can declare “always allow this class of operation within this session” to avoid repeated interruptions;
    • Sandbox as a backstop: where possible, run the execution environment inside an isolated container, so that even abnormal agent behavior cannot affect the host machine.

    The essence of permission design is finding a balance between “autonomy” and “security” that fits your business scenario—and that balance point should be configurable and auditable.

    Combining all the layers above, the recommended build order is:

    1. Week 1: implement a minimal Agent Loop plus three tools—command execution, file read, and file write—so the agent can close the “read code → modify code → run tests” loop;
    2. Week 2: add search tools, refine tool descriptions and error feedback, and add loop iteration protection;
    3. Week 3: introduce skill-based knowledge loading and the task planning tool, and observe performance on long tasks;
    4. Week 4: implement context compression and sub-agent spawning to break past the limits of a single context;
    5. Ongoing iteration: strengthen permission governance and audit logging, and introduce multi-agent parallelism with isolated execution as needed.

    At the infrastructure level, such systems typically also need supporting general-purpose cloud capabilities—for example, object storage for persisting task artifacts and knowledge packages, message queues for asynchronous inter-agent communication, container platforms for isolated execution environments, and logging services with monitoring and alerting for runtime observability. Baidu AI Cloud, for instance, offers general-category services such as object storage, container platforms, and log monitoring that can support these requirements; developers can equally choose equivalent solutions based on their own environment.

    10. Conclusion

    The key to building a powerful agent lies not in how complex your control logic is, but in how clean and complete the runtime environment you build is. The Agent Loop provides the heartbeat, the tool system provides hands and feet, knowledge loading provides memory, context management provides endurance, multi-agent collaboration provides scale, and permission governance provides safety. Only the deep combination of these six layers forms the working environment an agent truly depends on.

    Remember the most important architectural philosophy: the Harness never tries to be the agent itself. It paves the road for the model, then steps aside. When you resist the urge to make decisions on the model’s behalf, the model’s productivity will often reward you beyond expectations.