Design Trade-offs in AI Agent Runtimes: A Plugin-Based Architecture Approach
As AI agent systems evolve from single model invocations to executing long-term, complex tasks, traditional centralized architectures become bottlenecks. This article explores a microkernel and plugin-based approach for designing AI agent runtimes. By decoupling core components—such as model adapters, agent loops, session management, file systems, sandboxes, and prompt assembly—into composable, replaceable plugins, developers can build more scalable, testable, and governable systems. We also examine the practical benefits and engineering challenges of this architecture.
In recent years, the engineering focus of AI agent systems has shifted from “how to invoke a model once” to “how to run complex tasks reliably, stably, and governably over the long term.” In traditional designs, model invocation, tool execution, context management, task loops, and prompt assembly are typically centralized in a single core agent object. While easy to get started with, this approach causes the core module to bloat as functionality increases, where any modification can affect the entire system.
A more radical approach is to design the agent runtime as a “microkernel plus plugins” architecture. The kernel only handles lifecycle management, dependency injection, event dispatching, and plugin loading. Capabilities like models, tools, sessions, and agent loops are provided by replaceable components. In other words, the system no longer assumes an irreplaceable “super agent core,” but decomposes the agent into a set of composable, replaceable, and interceptable capability modules.
1. From a Fixed Agent Core to a Composable Runtime
Traditional agent frameworks usually rely on a central object that simultaneously handles the following responsibilities:
- Receiving user input;
- Constructing prompts;
- Invoking the model;
- Deciding whether to use tools;
- Executing tools and backfilling results;
- Saving session history;
- Determining when a task ends;
- Handling exceptions, retries, and timeouts.
The advantage of this pattern is its intuitive structure, allowing developers to implement features quickly along a single main flow. The problem is also obvious: the central object bears too many responsibilities, and extensions usually require inheritance, source code modification, or adding conditional branches.
A plugin-based runtime attempts to separate these responsibilities. The system can retain a minimal scheduling layer responsible for discovering plugins, establishing context, passing events, and managing lifecycles. Other capabilities are integrated via standard interfaces. For example:
- Model adapters unify input/output formats across different models;
- Tool plugins declare capabilities, validate parameters, and execute actions;
- Session plugins handle saving and loading historical states;
- Agent loop plugins determine the next step’s behavior;
- File system plugins abstract file read/write operations;
- Sandbox plugins restrict execution boundaries;
- Sub-agent providers create and manage collaborative agents;
- Prompt plugins assemble, modify, or audit context.
The key to this architecture is not the sheer number of plugins, but that no single module is permanently hardcoded as the sole implementation. Developers can recompose these capabilities based on specific task scenarios.
2. What “Everything is a Plugin” Really Means
“Everything is a plugin” does not mean all code must be dynamically loaded, nor does it mean the system lacks basic capabilities. Rather, it emphasizes that except for the minimal runtime kernel, business capabilities should not rely on irreplaceable implementations.
A reasonable microkernel typically handles only four tasks:
- Creating the runtime context;
- Registering and resolving plugins;
- Dispatching lifecycle events;
- Managing startup, shutdown, and error propagation.
For example, the runtime context can be abstracted into the following structure:
type RuntimeContext = {llm: ModelProvidertools: ToolRegistrysessions: SessionStoreloop: AgentLoopfilesystem: FileSystemsandbox: Sandboxevents: EventBus}
The focus here is not the field names, but the direction of dependencies. Upper-layer business logic should not directly depend on a specific model, a particular database, or a single tool implementation; it should depend on abstract interfaces. When the runtime starts, concrete implementations are injected into the context.
Consequently, the same agent logic can run in different environments:
- In local development, using in-memory sessions and a restricted file system;
- In testing environments, using mock models and virtual tools;
- On the server side, using persistent sessions and an isolated execution environment;
- In enterprise environments, adding audit, permission, and compliance plugins.
3. Model Adapters Should Not Be the System Center
In many early agent implementations, model invocation was often the center of the entire system. The agent loop directly depended on a specific model client, and tool formats, streaming outputs, and error handling were tightly bound together. This leads to high model switching costs and can even affect upper-layer business code.
A better approach is to introduce a unified model adaptation layer. The adapter should handle at least the following issues:
- Message format conversion;
- Tool call structure conversion;
- Unification of streaming and non-streaming outputs;
- Token or length limitations;
- Timeouts and retries;
- Model error classification;
- Call tracing and usage logging.
The agent loop only needs to care about “submitting context to the model and getting a result,” without understanding the underlying model’s specific protocol. This prevents a large number of conditional branches in business logic.
At the same time, the model adapter can also assume policy control functions. For example, selecting different models based on task type, compressing context based on length, executing limited retries based on failure types, or switching to a stricter output mode for high-risk tasks.
It is important to note that adapters should not secretly change business semantics. Policies like model selection, retry counts, and context trimming are best implemented through explicit configuration or independent plugins. Otherwise, it becomes very difficult during debugging to determine whether an issue originates from the model, the agent loop, or the adaptation layer.
4. The Agent Loop Should Also Be Decoupled
The agent loop is the core behavioral logic of an intelligent agent, but “important” does not mean “must be hardcoded.” Different tasks have different requirements for the loop:
- A Q&A task might only require a single model call;
- A tool-based task requires multiple rounds of interaction between the model and tools;
- A planning task requires decomposing a goal first, then executing step by step;
- A review task requires adding a validation phase after output;
- A multi-agent task requires coordinating multiple roles and aggregating results.
If all scenarios rely on the same loop, the system will soon develop complex conditional branches. By designing the agent loop as a plugin, different strategies can be assembled based on the task.
A simplified loop interface can be represented as:
interface AgentLoop {run(input: AgentInput, ctx: RuntimeContext): Promise<AgentResult>}
Concrete implementations can include:
- A single-turn response loop;
- A tool-calling loop;
- A plan-execute loop;
- A reflect-correct loop;
- A multi-agent collaboration loop;
- An approval loop requiring human confirmation.
Additionally, the loop itself can expose events, such as beforeModelCall, afterModelCall, beforeToolCall, and afterToolCall. Auditing, metrics, permissions, and debugging functions do not need to intrude on the loop’s main body but can be implemented via event listeners.
5. Sessions, Files, and Sandboxes are Different Layers
Session storage, file systems, and sandboxes are often mixed together, but they solve different problems.
Session storage focuses on “what the agent knows.” It is responsible for saving messages, tool results, task states, and necessary metadata. A mature session plugin should also consider:
- Concurrent writes;
- Version control;
- History compression;
- Desensitization of sensitive fields;
- Session recovery;
- Lifecycle cleanup.
The file system focuses on “what the agent can read and write.” It should not default to equating with the host file system, but should provide virtual directories, read-only directories, or temporary workspaces based on permissions.
The sandbox focuses on “what the agent is allowed to execute.” Even if the file system is restricted, executing code, accessing the network, or starting processes can still pose risks. Therefore, the sandbox needs to provide resource limits, syscall isolation, network policies, and timeout control.
By turning these three into plugins, clearer security boundaries are formed. For example, one task can use persistent sessions but only access temporary files; another task can read/write to a workspace but is forbidden from network access. Different capabilities are no longer tightly bound to each other.
6. Prompt Assembly Should Support Interception and Auditing
Prompt assembly is more than just a string concatenation process. It typically includes system rules, user input, historical messages, tool instructions, environment information, and intermediate states. If all content is assembled directly inside the agent loop, unified governance becomes very difficult later.
Abstracting prompt assembly as a plugin can support the following capabilities:
- Inserting unified system instructions;
- Removing or masking sensitive information;
- Compressing overly long history;
- Injecting task-level context;
- Trimming tool descriptions;
- Auditing the final request;
- Logging what the model actually receives.
For example, a processing chain can be established:
type PromptStage = {transform(input: PromptInput): Promise<PromptInput>}
Multiple stages execute in sequence, with each stage responsible for one clear task. This reduces the complexity of individual modules and makes it easier to locate issues like prompt pollution, context loss, and instruction conflicts.
However, prompt plugins must have clear priorities and observability. Otherwise, when multiple plugins modify content simultaneously, hard-to-reproduce issues may arise. Engineering-wise, the input summary, output summary, and reason for change should be recorded for each stage, rather than just saving the final text.
7. Practical Benefits of Plugin-Based Architecture
1. Easier Extension
When adding new models, tools, or storage methods, there is no need to modify the core loop. You only need to implement the corresponding interface and complete registration. Feature extension changes from “modifying core code” to “adding composable units.”
2. Easier Testing
Each plugin can be tested independently. Models can use mock implementations, tools can use virtual environments, sessions can use in-memory storage, and the agent loop can verify state transitions through fixed inputs.
3. Easier Reuse
The same tool plugin can be used by multiple agents, and the same session plugin can serve different loops. Capability modules are no longer bound to a specific agent instance.
4. Easier Governance
Permissions, auditing, rate limiting, metrics, logging, and human-in-the-loop confirmations can all be added as cross-cutting plugins, rather than scattering governance logic across business code.
5. Better Suited for Long-Term Evolution
When model protocols, tool specifications, and execution environments change continuously, plugin boundaries can isolate these changes and reduce the risk of large-scale refactoring.
8. Engineering Pitfalls to Watch Out For
Pluginization is not unconditionally superior to centralized design. It introduces new complexity.
First is dependency management. Implicit dependencies may exist between plugins; for example, a certain loop requires the session plugin to support transactions, and a specific tool requires the sandbox to provide network control. If capability declarations and startup checks are missing, errors may only surface during runtime.
Second is debugging cost. A single model call might pass through context construction, prompt processing, permission validation, model adaptation, tool execution, and session writing. The system must establish a complete tracing identifier to link events within a single task together.
Third is version compatibility. Once plugin interfaces change, old plugins may stop working. Therefore, clear interface versioning, capability negotiation, deprecation cycles, and compatibility strategies are needed.
Finally, performance overhead. Event dispatching, dynamic resolution, and multi-layer abstraction add calling costs. For high-frequency, low-latency scenarios, over-splitting should be avoided, and stable plugins should be allowed to be statically composed or batch-processed.
9. Scenarios Suited for This Architecture
“Everything is a plugin” is better suited for the following situations:
- Needing to support multiple models or execution environments simultaneously;
- A large number of frequently changing tools;
- Requiring strict permissions, auditing, and isolation;
- The same set of capabilities needs to serve multiple agents;
- Needing to support local, server, and testing environments;
- The product is in a rapid evolution phase, and future implementations may be frequently replaced.
For one-off scripts or simple Q&A applications, a complete microkernel might be overkill. In such cases, a modular design with clear interfaces can be adopted first, introducing dynamic plugin mechanisms when complexity grows.
Conclusion
The core value of a plugin-based agent runtime lies not in splitting all code into many files, but in redefining system boundaries: the model is not the center, and the agent loop is not the only core. The truly stable parts should be the runtime contracts, lifecycle, and capability composition mechanisms.
When models, tools, sessions, files, sandboxes, prompts, and sub-agents can all be replaced, intercepted, and composed, the agent system evolves from a fixed process into an orchestrable runtime platform. At the same time, developers must ensure proper interface governance, dependency checks, observability, security isolation, and version management. Otherwise, “flexibility” can turn into uncontrollable complexity.
Therefore, when adopting this architecture, the most important question is not “are more plugins better?” but: which capabilities require stable abstraction, which should remain replaceable, and how to ensure that every composition has clear boundaries, trackable behavior, and verifiable results.
