Agent Runtime Architecture: Designing and Building a Plugin-Based System
This article explains why AI agents need a dedicated runtime layer and how to design one around plugins. It covers a layered kernel where the agent loop, model adapters, session storage, and tool registry are all plugins, the Turn/Step/Tool lifecycle boundaries, event-driven flow control, context engineering and tool governance, observability and failure recovery, and general guidance for deploying such a runtime in the cloud. Readers will learn how a thin, composable runtime supports long-term evolution.
1. Why Agents Need a Runtime Layer
When building agent applications, teams often focus on model selection, prompt tuning, and the number of tools. Yet what really determines whether a system can evolve over time is usually the engineering layer outside the model. The industry is converging on a simple formula: model + runtime = agent. The model handles “thinking”—reasoning and content generation. The runtime handles “doing”—context assembly, tool dispatch, file I/O, terminal execution, task decomposition, error recovery, and session logging.
If these capabilities are hard-coded into a fixed kernel, the system quickly reaches an impasse: every new capability requires changes to core code, and regression testing costs rise sharply. Differences in workflow across business scenarios cannot be expressed, so they can only be handled by piling up branches and feature flags. This is exactly the value of a plugin-based runtime—push the “variable parts” down into replaceable components, and converge the “invariant parts” into a very thin dispatch layer.
2. A Layered Kernel and the Boundary of “Everything Is a Plugin”
A typical and rigorous architectural approach is to keep only the lowest-level plugin lifecycle scheduling capability, and provide everything else as plugins. The agent main loop, model adapters, session storage, tool registry, and UI layer are not hard-wired privileged components; they are native parts of the runtime.
A common misunderstanding needs to be cleared up here: plugins are not “bolt-on extensions” but the building blocks of the framework. The alternative is another common approach—keep a complete fixed kernel and mount a plugin system around its periphery, which is essentially “a tool within a tool.” The differences between the two routes are amplified across three dimensions:
- Replaceability: With a fixed kernel, model adapters and session storage are often hard to replace as a whole; with full pluginization, replacing them means swapping in a different plugin implementation.
- Composability: Full pluginization allows a “coding scenario” to be treated as one preset combination rather than the only form, making it possible to assemble task-oriented agents unrelated to programming.
- Evolution cost: The smaller the kernel, the smaller the radius of upgrades and regression, and the easier it is for community contributions to focus on a single plugin.
3. Lifecycle Layers: Turn / Step / Tool
To make extension points precise, state boundaries must first be clear. A mature industry practice is to split an interaction into three layers:
- Turn: A user task claimed by the agent, marking the boundary of business semantics.
- Step: A model request and the messages or tool calls it produces, marking the boundary of model interaction.
- Tool: A structured capability execution that includes pre-call, in-call, and post-call processing chains, marking the boundary where side effects occur.
A typical flow looks like this:
turn/start-> agent/pre-step-> step/start-> assemble system prompt and tool schema-> llm/stream-> assistant/message-> tool/call-> tools/pre-execute (guards / approval / sandbox)-> tools/execute-> tools/post-execute-> tool/result-> step/endturn/end
The direct benefit of layering is that extension locations become semantically clear: context compression can intervene before a model request; telemetry can observe streaming events; approval can suspend execution before a tool runs; and result post-processing can standardize formatting before writing back to the model.
4. Event-Driven Design and Flow Control
Emit events at every key point in the agent main loop. Plugins insert logic by subscribing to the events they care about, without modifying the main loop source. Example code:
# Pseudocode: expresses the extension pattern onlyctx.on("tools/pre-execute", async def hook(call, next):if call.name in DANGEROUS and not approved(call):return deny("Manual approval required")return await next()) # allow, proceed to executionctx.on("step/end", async def hook(step, next):metrics.observe(step) # observe without changing the flowreturn await next())
Two engineering points deserve attention. First, hooks should distinguish “observational” from “decision-making”: the former should not change the result, while the latter must explicitly return allow or deny. Second, the hook chain needs timeouts and exception fallbacks to prevent a single plugin from hanging the entire flow.
5. Context Engineering and Tool Governance
Once the runtime pluginizes context assembly and the tool registry, teams can swap strategies per scenario: use rolling summaries to compress history for long tasks, use structured templates to fix output for strongly constrained tasks, and use a minimal toolset to reduce the attack surface in sensitive scenarios. Tool governance should cover four points: schema validation (strongly typed inputs and outputs), idempotent design (retriable), permission tiers (read/write/execute), and sandboxing with resource quotas. Approval and guardrails as standalone plugins are easier to audit than logic scattered across business code.
6. Observability, Failure Recovery, and Evaluation
Streaming events are naturally suited to observability: mapping node events to metrics, logs, and traces makes it possible to reconstruct “why the model made this decision.” Failure recovery should be implemented as plugins for retries, degradation, and human takeover. For evaluation, it is advisable to build layered regression: single-plugin cases, flow cases, and end-to-end task success rate and cost, forming a sustainable quality baseline.
7. General Guidance for Cloud Deployment
If you choose to build your own runtime, you can combine general cloud capabilities to reduce operational overhead: container platforms host the runtime and sandboxes, object storage holds sessions and artifacts, message queues decouple long-running tasks, logging services and monitoring alerts close the observability loop, and key management services store credentials. Baidu AI Cloud offers corresponding capabilities in these general categories, which can be combined as needed without changing plugin interfaces.
8. Conclusion
Pluginization is not the goal itself, but a means to make the runtime composable, observable, and governable. You can self-check whether an architecture is sound with three questions: Is the core thin enough? Are the extension points semantically clear? Are failures recoverable and auditable? Only when all three are in place does an agent system have the ability to evolve over the long term.
