Agent Runtime Framework Design: From Model to Production System

    This article breaks down the architecture of an AI agent runtime, the engineering layer that turns model output into controlled actions. It explains the three-tier state model of Turn, Step, and Tool, walks through the full event chain of a task, and shows how event-driven plugins handle context compression, telemetry, approvals, and result post-processing. It also covers key production practices such as least-privilege permissions, recoverability, observability, and evaluation loops.

    1. Why a Runtime Layer Is Necessary

    When building agent systems, a common mistake is to place all expectations on model capability: if the model is strong enough, the task will take care of itself. Engineering practice repeatedly shows that the model only solves the “thinking” part; the entire engineering system needed to “do” the work does not appear automatically. How context is organized and trimmed, how tools are registered and dispatched, how files are read and written, how terminal commands are executed, how complex tasks are decomposed, how recovery happens after a failure, and how the session is recorded all fall outside model inference and belong to engineering.

    As a result, the industry has gradually converged on a formulaic understanding:

    1. Agent = Model + Harness

    Here, the Harness can be understood as the “runtime foundation”: the model outputs intent, the runtime turns intent into controlled actions, and then feeds the action results back to the model in a structured form. This loop determines whether an agent is “demo-ready” or “production-ready.”

    It is worth emphasizing that a runtime is not a product built for one fixed purpose. Many people equate agents with AI coding tools, but coding is only one preset combination of a runtime. Swap out the toolset, prompt templates, and permission policies, and the same foundation can be assembled into agents for data analysis, operations inspection, document processing, and other tasks unrelated to programming.

    2. Three-Tier State Model: Turn, Step, Tool

    To make the runtime controllable, the first step is to split a session into state tiers with clear boundaries. A mainstream approach uses three tiers:

    • Turn: a user task claimed by the agent. It is the task-level boundary and the unit that owns timeouts, budgets, and the final result.
    • Step: a single model request and the messages or tool calls it produces. It is the inference-level boundary.
    • Tool call: a single structured capability execution that goes through pre-execute, in-execute, and post-execute handling.

    The three are nested: one Turn contains multiple Steps, and one Step may trigger multiple Tools.

    1. Turn
    2. ├── Step 1 → model returns plain text (task planning)
    3. ├── Step 2 → model returns tool calls → Tool A / Tool B
    4. │ ├── pre-execute → guards, approval, sandbox
    5. │ ├── execute
    6. │ └── post-execute → result normalization, truncation, redaction
    7. └── Step 3 → model produces the final answer based on results

    The direct value of this layering is that each tier has its own failure semantics. A failed turn means the whole task must be retried or escalated; a failed step usually only requires re-requesting the model; a failed tool can feed the error back so the model can correct itself. Without layering, any exception degrades into “restart the entire conversation,” which is unacceptable in both cost and user experience.

    3. The Full Event Chain of a Task

    The runtime makes these state transitions explicit as an observable chain, typically shaped like this:

    1. turn/start
    2. → agent/pre-step
    3. → step/start
    4. → assemble system prompt and tool schema
    5. → llm/stream
    6. → assistant/message
    7. → tool/call
    8. → tools/pre-execute (guards / approval / sandbox)
    9. → tools/execute
    10. → tools/post-execute
    11. → tool/result
    12. → step/end
    13. → turn/end

    Every link in the chain has a clear responsibility. agent/pre-step is the main battlefield of context engineering, where history trimming, memory injection, and retrieval result assembly happen. llm/stream lets callers consume incremental content in a streaming way, enabling token-by-token output and real-time interruption. tools/pre-execute is the security gate. tools/post-execute ensures that no matter what raw format a tool returns, the content written back to the model is clean and length-controlled.

    Illustrative code (pseudocode, only expressing where extension points sit):

    1. def on_event(event, ctx):
    2. if event.name == "agent/pre-step":
    3. ctx.messages = compress(ctx.messages, budget=ctx.token_budget)
    4. elif event.name == "tools/pre-execute":
    5. if event.tool.risk_level == "high" and not ctx.approved(event):
    6. return deny("manual confirmation required")
    7. elif event.name == "tools/post-execute":
    8. event.result = normalize(event.result, max_bytes=32_000)

    4. Event-Driven Extension Mechanism

    At every key node of the agent loop, the runtime emits events externally. Plugins insert their own logic by listening to events instead of modifying the loop source code. This is the dividing line between the “foundation” and the “application”: the core loop stays stable, while capability evolution happens in the plugin layer.

    Common plugin use cases fall into four categories:

    1. Context compression: summarize or trim history before the model request to control the token budget.
    2. Telemetry and tracing: consume streaming events to output structured logs, call chains, and latency metrics.
    3. Approval and compliance: pause before tool execution and wait for a human or policy engine decision.
    4. Result post-processing: unify formats, truncate overly long output, and filter sensitive information.

    5. Production Implementation Essentials

    • Least privilege: split tools by capability, and route file and terminal tools through sandboxes and allowlists by default.
    • Recoverability: persist Turn state so that after an exception the run can resume from the most recent Step instead of starting over.
    • Observability: connect the event stream to logging services and monitoring alerts, and set thresholds for tool failure rate, average steps, and token consumption.
    • Evaluation loop: use a fixed task set to regression-test prompts and tool descriptions, avoiding “fix one thing, break everything.”
    • Integration with general cloud capabilities: container platforms host sandbox execution, object storage keeps session artifacts, and message queues handle task distribution.

    Master these three things—layered state, the event chain, and plugin extension—and you can move an agent from a demo to a governable, operable engineering system.