Agent Runtime Architecture: Session Logs and Extension Design

    This article examines agentic coding tools from a runtime perspective rather than a product perspective. It covers the shared layers behind web, CLI, SDK, and package-based entry points; explains why a persistent session event log should be the source of truth and how trajectory views can be projected from it; discusses how to define cache hit ratio, token throughput, and tool-call latency; and describes how decoupling through an event protocol enables extension points. It also outlines methods for controlled comparisons, preview-stage risks, and a practical rollout sequence.

    1. From Product View to Runtime View

    Intelligent coding tools are often treated as out-of-the-box applications. Architecturally, however, such a tool contains at least seven independent layers: model access, toolset, session management, permission policy, sandbox execution, agent loop, and interface layer. When these layers are exposed through stable interfaces, the system comes closer to a runtime. Developers can replace any one layer without rewriting the entire system.

    This distinction changes how the system is evaluated. If it is treated as a finished product, the focus is on interface maturity, installation experience, and day-to-day coding efficiency. If it is treated as a runtime, the focus is on whether the layering is clear, the interfaces are stable, the logs are complete, and the extension points are sufficient. These two types of evaluation do not conflict, but completeness may be asymmetric: the runtime’s openness may already be mature while the default product experience still needs refinement.

    2. Common Entry Points and Layer Relationships

    The same runtime often provides multiple entry points. They share the core loop and differ only in transport and interaction form.

    Entry type Typical use Main concerns
    Web interface Interactive coding, visual session inspection Frontend rendering, session switching, state synchronization
    Headless CLI Scripted execution, running tasks in CI Exit codes, standard output format, timeout control
    Language SDK Embedding into internal platforms or tools Version compatibility, asynchronous invocation model, error types
    Package manager installation Fast deployment and version pinning Dependency isolation, upgrade strategy

    A recommended validation order is to first run a minimal task through the headless entry point and confirm that model calls, tool execution, and result persistence all work correctly. Then connect the web interface or SDK. This isolates problems to a specific layer instead of switching back and forth between multiple entry points.

    3. The Session Event Log Is the Source of Truth

    The most important constraint in runtime design is this: any content visible to the model must first be written to a persistent log before it can enter the context. This constraint brings three direct benefits.

    First, it is replayable. Any session can be replayed by sequence number, which makes problems easier to reproduce.
    Second, it is auditable. Every tool call, every segment of model output, and every permission decision is recorded for later tracing.
    Third, it is recoverable. After a process interruption, the context can be rebuilt from the log rather than relying on in-memory state.

    In this design, Trajectory is not an independently instrumented monitoring layer. It is a read model projected from the event log. There is only one data source, so monitoring data cannot become inconsistent with the actual execution record. The following code is illustrative and shows the basic projection idea; it is not an interface from a specific product.

    1. from dataclasses import dataclass
    2. from typing import Any
    3. @dataclass(frozen=True)
    4. class Event:
    5. seq: int # Monotonically increasing sequence number that determines replay order
    6. kind: str # e.g., user_message, model_output, tool_call, tool_result
    7. payload: dict[str, Any]
    8. TRAJECTORY_KINDS = {"model_output", "tool_call", "tool_result"}
    9. def project_trajectory(events: list[Event]) -> list[dict]:
    10. """Project a trajectory view from the event log without maintaining extra state."""
    11. view = []
    12. for event in sorted(events, key=lambda e: e.seq):
    13. if event.kind in TRAJECTORY_KINDS:
    14. view.append({"seq": event.seq, "kind": event.kind})
    15. return view

    This projection approach has another benefit that is easy to overlook: changing the projection rules does not require data migration. As long as the raw events are complete, any new view can be obtained by reprojecting them.

    4. Defining Observability Metrics

    Observability dashboards usually show four types of metrics: cache hits, input and output token counts, token generation rate, and tool-call latency. The value of a metric depends on whether its definition is clear, so in practice teams should agree on the calculation method before making comparisons.

    A common way to calculate cache hit ratio is to divide the number of cached prefix tokens by the total number of input tokens.

    1. def cache_hit_ratio(prompt_tokens: int, cached_tokens: int) -> float:
    2. if prompt_tokens == 0:
    3. return 0.0
    4. return cached_tokens / prompt_tokens

    Hit ratio is closely related to how context is organized. Servers usually match cache by prefix, so if the order or content of historical messages is rewritten on every turn, the prefix becomes invalid and the hit ratio drops. The engineering response is to keep the prefix of the system prompt and historical messages stable and append new content only at the end.

    Token generation rate needs to separate first-token latency from the sustained generation phase. If the two are mixed together, the rate is pulled down by first-packet latency and the conclusion becomes distorted. It is better to record the first-token arrival time and the end time separately, then divide output tokens by the sustained generation duration.

    Tool-call latency should be broken down by tool category. File reads, command execution, and network requests have very different latency distributions. Combined statistics can hide the real bottleneck.

    5. Decoupling and Extension Points

    The extensibility of a runtime depends on the boundaries between layers. Common extension points include:

    • Model access adapter: converts a unified request format into the invocation method for different model services.
    • Tool registry: declaratively registers tool names, parameter schemas, and executors.
    • Permission policy: applies tiered approval by tool category, file path, or command pattern.
    • Sandbox executor: restricts filesystem access scope and network egress.
    • Agent loop: controls the loop of “model output, tool call, result feedback,” including termination conditions and maximum steps.
    • Interface layer: only subscribes to the event stream and renders it; it does not call internal functions directly.

    The key to decoupling is to use an event protocol rather than shared internal functions. The interface layer consumes only events, so replacing the interface does not affect execution logic. Inter-process communication can use a general JSON-RPC message format, allowing clients written in different languages to connect to the same runtime.

    Permission policy design should follow the principle of least privilege. A recommended approach is to divide tools into three tiers: read-only, write, and execute. Read-only operations are allowed by default, while write and execute operations require approval by path or command pattern. This reduces interruptions and concentrates risk in a small number of high-risk operations.

    6. Method for Controlled Experiments

    When comparing the execution results of two runtimes, a common problem is that there are too many variables, making conclusions difficult to attribute. A more reliable method is as follows:

    1. Pin the model version so that both sides use the same underlying model.
    2. Fix the task description and the initial repository state.
    3. Fix the acceptance criteria, such as the number of passing tests, whether the build succeeds, and whether artifacts meet requirements.
    4. Record tool-call count, failed retry count, total time, and token usage.
    5. Repeat each experiment group multiple times and report the distribution rather than a single result.

    Data from a single run is affected by network fluctuations, cache state, and model randomness. It can be used to observe phenomena but cannot directly lead to a ranking. The experiment report should state the environment, versions, metric definitions, and sample size so that readers can reproduce it.

    7. Boundaries and Risks

    A preview-stage runtime carries the following risks, which should be evaluated one by one before production use.

    • Interface changes: preview APIs and configuration items may change. Pin the version number and run regression tests before upgrading.
    • Log sensitivity: event logs may contain code, paths, and command output. They need redaction and restricted access.
    • Automatic execution: command execution tools should run in a sandbox, with approval and timeout mechanisms retained.
    • Metric definitions: cache fields returned by different servers may have different meanings. Check the documentation before use and confirm the denominator and statistical scope.

    First, complete deployment in an isolated environment and use the headless entry point to execute a read-only task. Confirm that logs and the trajectory view are generated correctly.

    Second, design three to five representative tasks covering read, modify, and verify operations, and establish baseline data.

    Third, connect observability metrics to the existing monitoring system and unify metric definitions before making cross-system comparisons.

    Fourth, extend the tool registry and permission policy according to team needs. Each new tool should include approval rules and test cases.

    Fifth, establish a security baseline, including log redaction rules, sandbox configuration review, and key management. Keys should be stored in environment variables or a dedicated secret service and must not be written into code or logs.