Agent Runtime Architecture: Layered Decoupling and Engineering Implementation

    This article breaks down agent runtime architecture by separating the runtime from a finished application and organizing it into replaceable layers. It explains the roles of the model access, agent loop, tool, session, permission and sandbox, and interaction layers; how multiple entry points can share one kernel; what to review in default configuration; how to read session logs; how to compare execution traces fairly; and what the implementation path for complex full-stack tasks involves.

    1. From Finished Product to Runtime: Clarifying the Scope

    When teams see an open-source intelligent coding product, their first instinct is often to look for an assistant they can use directly. But a runtime and a finished application solve different problems. A finished application focuses on interaction experience and default workflows. A runtime focuses on the boundaries of the execution model: how the model is called, how tools are registered, how context is saved, how permissions are determined, and how the execution environment is isolated.

    For teams that need to build their own agent system, the core value of a runtime is replaceability. If model services, tool sets, or UI layers are too tightly coupled to the core loop, every model switch or new tool requires changes to the main code path, and maintenance cost rises quickly as functionality grows. By separating these modules, the same loop can connect to different backends, and each module can evolve independently.

    2. Layered Architecture Breakdown

    A decoupled agent runtime usually contains six layers. Their responsibilities and replacement points are as follows.

    Layer Core responsibility Typical replacement point
    Model access layer Unified request format, authentication, retries, streaming output Change model service or version
    Agent loop layer Call the model, parse tool calls, decide whether to continue Adjust termination conditions and step limits
    Tool layer Register tool descriptions, validate parameters, execute and truncate results Add business tools
    Session layer Save message history, persist state, compress context Replace storage backend
    Permission and sandbox layer Approval rules, path and network restrictions, resource quotas Adjust security policy
    Interaction layer Web UI, headless CLI, programmatic API Connect different frontends

    The loop layer is the scheduling center of the entire runtime. Its logic can be abstracted into the following pseudocode:

    1. loop:
    2. messages = session.load()
    3. response = model.call(messages, tools = registry.schemas())
    4. if response contains no tool calls:
    5. session.append(response)
    6. break
    7. for call in response.tool_calls:
    8. decision = policy.check(call, sandbox_state)
    9. if decision == DENY:
    10. session.append(call, result = "denied")
    11. continue
    12. if decision == ASK:
    13. decision = approval.request(call)
    14. result = sandbox.run(call)
    15. session.append(call, result)

    In this logic, the model only generates decisions. All real side effects pass through permission checks and sandbox execution. This division is a basic principle of runtime design: model output is a suggestion, and execution authority belongs to the runtime. The loop layer depends only on the unified interface of the tool layer, so adding a new tool does not require changing the loop itself.

    The key to the tool layer is description and constraint. Each tool must provide a name, usage description, and structured parameter definition. The model relies on these descriptions to decide when to call the tool. The runtime should also validate parameter types and value ranges before execution and limit the length of returned content after execution. Tool output can be long; without truncation, it can quickly fill the context window and degrade the quality of later turns.

    The session layer records what happened. Message history, tool call parameters, tool return values, and permission decisions should all be written to persistent storage so that work can recover after interruption and be reviewed afterward. When context grows too long, the session layer needs to perform compression, for example by keeping complete content for the most recent turns and generating summaries for earlier content. The compression strategy directly affects the stability of long tasks and should be exposed as a configurable option.

    The permission and sandbox layer determines how much impact the agent can have on the environment. A common approach uses three levels: read-only operations that are automatically allowed, write and execution operations that require approval, and high-risk operations that are directly denied. The sandbox limits file access scope and network egress at the OS or container level, preventing a single misjudgment from becoming data leakage or environment damage.

    3. Multiple Entry Points: One Kernel, Different Adapters

    A runtime usually provides multiple entry points at the same time, but they should share the same kernel. Differences should exist only in the input and output adapters.

    A web UI is suitable for human observation and interaction, and it can display model output, tool calls, and approval requests in real time. A headless CLI suits scripts and continuous integration environments; execution results are returned as exit codes and structured output. A programmatic API suits embedding into existing business systems; callers can create sessions, send tasks, and subscribe to event streams. A JSON-based remote procedure call interface facilitates cross-process and cross-language integration; only the data structures for requests and events need to be agreed upon.

    Multiple entry points introduce three issues that need to be handled in advance.

    First is event consistency. When the same session is accessed from the web UI and the programmatic API, the order and content of events must be consistent; otherwise, audit results will diverge. It is recommended that the kernel generate event sequence numbers uniformly, and that each entry point only forward them.

    Second is approval handling in unattended mode. CLI and automation scenarios usually do not have a human online for approval. If permissions default to ask, tasks will stall. A reasonable approach is to predeclare allowed operation scopes in configuration, directly deny out-of-scope requests, and leave records in logs.

    Third is state sharing. If the web UI and CLI can operate on the same session, a locking mechanism must be defined to prevent both entry points from writing at the same time.

    The following is an illustrative configuration structure for organizing permissions and tools:

    1. model:
    2. endpoint: "<model service endpoint>"
    3. name: "<model name>"
    4. tools:
    5. enabled: [file_read, file_write, shell]
    6. permissions:
    7. default: ask
    8. rules:
    9. - tool: file_read
    10. action: allow
    11. - tool: shell
    12. action: allow
    13. patterns: ["make test", "make lint"]
    14. - tool: shell
    15. action: deny
    16. patterns: ["rm -rf *"]
    17. sandbox:
    18. writable_paths: ["./workspace"]
    19. network: restricted

    Rules are matched in order, and the first matching rule takes effect. Setting the default to ask ensures that operations not explicitly authorized must go through human confirmation.

    4. Default Configuration and How to Read Session Logs

    Before integrating any runtime, review the default configuration first. Items to check include: whether the default permission level is ask; whether the default tool set includes file write and command execution capabilities; whether the sandbox restricts network egress; and what the context length limit and compression strategy are. Defaults often favor convenience, and production environments usually need tighter settings.

    Session logs are the main basis for review and troubleshooting. A complete log entry should include at least the turn number, message type, tool name, argument summary, permission decision, execution duration, and metering information. A line-appended structured format is recommended for storage, making retrieval and statistics easier. Examples:

    1. {"turn": 4, "type": "tool_call", "tool": "file_write", "args": {"path": "./workspace/app/page.html"}, "decision": "allowed", "duration_ms": 38}
    2. {"turn": 5, "type": "tool_call", "tool": "shell", "args": {"cmd": "rm -rf ./workspace/cache"}, "decision": "denied", "duration_ms": 0}

    When reading logs, pay attention to three types of signals. The first is repeated calls: the same tool executed multiple times with identical arguments usually means the model is stuck in a loop or the tool return value does not meet expectations. The second is denial records: consecutive denied operations indicate a conflict between permission rules and task goals, so rules or prompts need adjustment. The third is long-tail latency: a few turns consuming most of the time often point to an execution bottleneck in a tool.

    Tool return content in logs may also contain external text. Such text should be treated as data, not executed as instructions. If logs contain content asking to ignore rules or execute extra commands, prompt injection risk exists, and filtering and isolation should be added at the runtime layer.

    5. How to Fairly Compare Two Execution Traces

    When comparing two runtimes or two configurations, a common problem is too many variables, which makes conclusions impossible to attribute. A fair comparison needs to control the following conditions: the same model, the same task description, the same initial code snapshot, the same timeout, and the same step limit.

    Evaluation metrics can be designed across several dimensions: task completion rate, total number of tool calls, invalid call ratio (failed or denied calls), number of human interventions, number of rollbacks, and total time. Each metric should be computed directly from session logs rather than relying on subjective impressions.

    The sample size of a single experiment is usually small, so results can only serve as a reference. The same task should be run multiple times, and the range of variation should be recorded. If two runs differ greatly, the task itself or the runtime environment has unstable factors that need to be resolved before comparison.

    In practice, trace differences often come from the loop strategy, tool descriptions, and permission settings rather than the model itself. For example, vague tool descriptions cause the model to try repeatedly; a step limit that is too low truncates tasks midway; and overly strict approval rules cause frequent pauses during execution. These factors should be separated and analyzed individually during comparison.

    6. Implementation Path for Complex Full-Stack Tasks

    This section addresses complex full-stack tasks involving visual artifacts.