Everything-as-a-Plugin: Why Agent Runtimes Need a Microkernel Architecture

    As agent applications grow, centralized agent loops often become large, hard-to-replace controllers. This article explains an agent microkernel design in which models, tools, sessions, file systems, sandboxes, approval mechanisms, sub-agent schedulers, and even prompt assembly are treated as plugins. It covers capability-based runtime composition, reversible side effects, dynamic dependency changes, pluggable agent loops, typed events, the benefits and costs of the approach, and practical engineering guidance for production systems.

    Everything-as-a-Plugin: Why Agent Runtimes Need a Microkernel Architecture

    As agent applications evolve rapidly, many systems start with a centralized Agent Loop design: a core loop receives user input, calls the model, selects tools, maintains context, and generates the final result. This approach is easy to start with, but as features accumulate, the core module often expands into a large controller that is difficult to replace, test, and extend.

    A more radical approach is to stop treating the Agent Loop as an irreplaceable center and instead split the entire agent runtime into a set of loadable, replaceable, and composable plugins. Models, tools, sessions, file systems, sandboxes, approval mechanisms, sub-agent schedulers, and even the prompt assembly pipeline are all just ways of providing capabilities. The runtime itself keeps only minimal context, events, dependency management, and lifecycle mechanisms.

    This design can be described as an “agent microkernel” architecture, where everything is a plugin.

    1. From a Centralized Agent to a Composable Runtime

    Traditional agent frameworks usually contain several fixed modules:

    1. A model invocation module;
    2. A tool registration and execution module;
    3. A session history storage module;
    4. An Agent Loop;
    5. A prompt construction module;
    6. A file and network access module;
    7. A security approval and execution isolation module.

    In early projects, this module breakdown is sufficient. The problem is that these modules are often strongly coupled. For example, the Agent Loop directly depends on a specific model interface, the tool executor directly depends on the local file system, the session module defaults to a particular database, and the prompt module reads fixed configuration directly.

    When requirements change, modifications tend to spread along the call chain:

    • Replacing the model requires changing the loop logic;
    • Switching from a local file system to a remote file system requires changing tool implementations;
    • Adding a container sandbox requires changing the executor;
    • Introducing multi-agent collaboration requires rewriting task scheduling logic;
    • Adding auditing, monitoring, and human approval requires inserting conditionals in multiple places.

    The core change in a plugin architecture is that the core no longer cares who the concrete implementation is. It only cares whether a capability currently exists and how to access it through a standard interface.

    For example, a tool does not need to know whether files are ultimately provided by a local directory, a remote service, or an isolated container. The tool only declares that it needs file read/write capability, and the runtime handles binding to a specific provider.

    2. What the Microkernel Should Retain

    “Everything is a plugin” does not mean the system has no core at all. The reasonable approach is to retain a microkernel that is small enough but stable.

    This microkernel usually handles the following responsibilities.

    2.1 Runtime Context

    Context is the unified entry point for plugins to access system capabilities. It can include model providers, the tool registry, session repositories, the event bus, configuration, logs, and cancellation signals.

    Context should not carry too much business logic; otherwise, it will evolve into a new “large core.” Its main role is to provide capability discovery, dependency access, and lifecycle association.

    2.2 Plugin Loading and Unloading

    The runtime needs to know when a plugin is loaded, initialized, paused, and unloaded. A plugin is not just a function; it may also contain multiple registration actions, such as:

    • Registering tools;
    • Registering model adapters;
    • Registering event listeners;
    • Adding prompt fragments;
    • Exposing services;
    • Creating scheduled tasks;
    • Establishing external connections.

    Therefore, the plugin lifecycle must be managed explicitly.

    2.3 Event Dispatch

    Many behaviors in agent systems are naturally event-shaped, such as model request start, tool call completion, session creation, loop interruption, and task failure. An event bus can decouple logging, monitoring, auditing, and extension logic from the main flow.

    2.4 Dependency Management

    Plugins often depend on one another. For example, a tool may need file system, approval service, and sandbox capabilities. The runtime needs to determine whether dependencies are satisfied and notify relevant plugins when dependencies change.

    2.5 Reversible Side Effects

    This is an important difference between a plugin system and an ordinary module system. Every external effect produced when a plugin is loaded should have a corresponding cleanup action.

    3. Reversible Side Effects: Making Unloading Reliable

    Loading a plugin is not just executing an initialization function once. It may register many things with the system. If unloading only deletes the plugin object without undoing those registrations, hidden residue will remain:

    • Tools still appear in the tool list;
    • Event listeners continue to receive events;
    • Timers continue to run;
    • Prompt fragments are still appended;
    • Service references point to invalid objects;
    • External connections are not closed;
    • Caches and temporary files are not cleaned up.

    Therefore, plugin registration actions should return a reversible operation, or the runtime should record all side effects centrally.

    A schematic interface can be designed as follows:

    1. type Revert = () => void | Promise<void>;
    2. interface Plugin {
    3. name: string;
    4. setup(ctx: RuntimeContext): Revert | Promise<Revert>;
    5. }

    The plugin completes registration during initialization and returns a cleanup function. During unload, the runtime calls cleanup functions in lifecycle order.

    A more complete implementation should also consider the following issues:

    • Whether cleanup actions are idempotent;
    • Whether to continue cleaning other resources after one cleanup fails;
    • Whether fallback reclamation can run when a plugin exits abnormally;
    • How to handle multiple plugins registering tools with the same name;
    • Whether new requests are allowed during unload;
    • How to cancel tool tasks that are already executing.

    The value of reversible side effects is that they elevate resource management from a developer convention to a structured runtime capability.

    4. Dynamic Composition: Responding Automatically to Dependency Changes

    A plugin system must support not only loading and unloading over time, but also dynamic replacement within the runtime space.

    Dynamic composition can be understood as follows: a plugin declares only which capabilities it depends on, rather than binding to a fixed implementation. When capability providers appear, disappear, or are replaced, consumers can adapt automatically.

    For example, a code execution tool depends on the following capabilities:

    • File system;
    • Sandbox;
    • Approval service;
    • Logging service.

    These capabilities may have multiple implementations:

    • The file system can be a local directory, remote storage, or a temporary workspace;
    • The sandbox can be process isolation, container isolation, or a restricted interpreter;
    • The approval service can be an automated policy or human confirmation;
    • Logs can be written to local files, a message queue, or a centralized logging system.

    The tool itself should not contain extensive branching logic to determine which implementation is currently in use. A more reasonable approach is capability-oriented programming:

    1. interface ExecutionTool {
    2. run(input: unknown, ctx: {
    3. fs: FileSystem;
    4. sandbox: Sandbox;
    5. approval: ApprovalService;
    6. }): Promise<unknown>;
    7. }

    The runtime is responsible for dependency injection. If the sandbox is replaced, the tool does not need to change. If the approval service is temporarily unavailable, the runtime can pause the relevant tool or mark it as unavailable for execution.

    This mechanism also helps with multi-tenant isolation, test doubles, and runtime environment migration.

    5. The Agent Loop Can Also Be a Plugin

    Designing the Agent Loop as a plugin is the most controversial and most valuable part of this architecture.

    An agent loop usually contains the following steps:

    1. Read the current session state;
    2. Assemble the model input;
    3. Request a model-generated result;
    4. Determine whether the result contains tool calls;
    5. Execute tools;
    6. Write tool results back to the session;
    7. Decide whether to continue the loop or finish.

    Traditional architectures hard-code these steps into a loop function. A plugin architecture can abstract the loop itself as a strategy, allowing replacement based on the scenario:

    • Single-turn question-answering loop;
    • Multi-step task loop;
    • Plan-execute loop;
    • Reflection loop;
    • Multi-agent collaboration loop;
    • Streaming interaction loop;
    • Controlled loop with human approval.

    In this case, the runtime only provides base capabilities and the event stream, while the Agent Loop plugin decides how to advance the task.

    It is important to note that although loop plugins are replaceable, they must follow unified state and cancellation protocols; otherwise, different loops will be difficult to coordinate. At a minimum, the following should be standardized:

    • Input message format;
    • Tool call description;
    • Intermediate state;
    • Completion, failure, and cancellation states;
    • Maximum steps and timeout control;
    • Event record format.

    6. Prompt Assembly Should Also Be an Extension Point

    Prompts are often regarded as simple string concatenation, but in enterprise agents they are actually a dynamic orchestration process.

    A prompt may contain:

    • System instructions;
    • User tasks;
    • Tool descriptions;
    • Current time and environment information;
    • Permission boundaries;
    • Session summaries;
    • Historical tool results;
    • Domain knowledge;
    • Runtime state.

    If all content is hard-coded in the Agent Loop, it becomes difficult to adjust dynamically by tenant, task, or permission later.

    A more reasonable solution is to split prompts into multiple composable fragments and allow plugins to insert, modify, or filter content at different stages. For example, a security plugin can append constraints before the model request; a session plugin can provide a history summary; a tool plugin can dynamically generate descriptions of currently available tools.

    At the same time, prompt extensions must have priority, source identifiers, and conflict handling mechanisms to prevent multiple plugins from overwriting each other and producing unpredictable results.

    7. Typed Events Are the Foundation of Observability

    The event bus cannot simply pass arbitrary objects. For production systems, events should have explicit types and stable structures.

    Typical events include:

    • Session created;
    • Model request start and end;
    • Tool call start and end;
    • Plugin load and unload;
    • Dependency appears and becomes invalid;
    • Agent Loop enters the next step;
    • Task completed, failed, or cancelled.

    Typed events provide three benefits. First, plugin developers get clearer programming constraints. Second, logging, auditing, and monitoring systems can consume events reliably. Third, compatibility changes can be identified during system upgrades.

    Events should also include request identifiers, session identifiers, plugin identifiers, timestamps, and error information so that the full trace of a task can be followed.

    8. Benefits and Costs of This Architecture

    A plugin-based microkernel has clear advantages.

    Main Benefits

    • Strong replaceability: Models, storage, loops, and execution environments can be replaced independently;
    • Easier testing: Virtual models, in-memory sessions, and mock file systems can be used;
    • Lower extension cost: New capabilities are mainly added through plugins;
    • Better isolation: Different tenants or tasks can load different capability sets;
    • Clear lifecycle: Resource acquisition and release can be managed centrally;
    • Suitable for long-term evolution: Once core protocols are stable, peripheral capabilities can keep iterating.

    But the costs are equally clear:

    • Debugging paths become longer, and problems may occur during dependency discovery, event dispatch, or plugin initialization;
    • Dynamic replacement increases the difficulty of state consistency;
    • Implicit dependencies between plugins can make system behavior opaque;
    • Version compatibility and interface governance become more important;
    • Over-pluginization can make simple features complex.

    Therefore, “everything is a plugin” should not be understood as requiring all code to be split into independent plugins. Instead, it should follow a principle: only capabilities that need independent replacement, independent deployment, independent testing, or independent authorization are worth turning into plugins.

    9. Engineering Recommendations for Implementation

    In actual implementation, the following steps can be used:

    1. Define stable capability interfaces before designing plugin directories;
    2. Classify plugins into core capabilities, runtime strategies, and peripheral extensions;
    3. Establish a corresponding undo mechanism for every registration action;
    4. Make dependency states explicit, including available, missing, invalidated, and being replaced;
    5. Support cancellation, timeout, and resource reclamation for all asynchronous tasks;
    6. Add version fields to events to avoid breaking consumers during upgrades;
    7. Use capability allowlists to limit the resources plugins can access;
    8. Record the source, version, dependencies, and runtime status of each plugin;
    9. Prioritize testing loading, unloading, replacement, and exception recovery in test environments;
    10. Retain audit records for critical operations.

    For security-sensitive agents, plugin permissions also need to be separated from tool permissions. A plugin may have read access to a service, but it does not necessarily have permission to execute high-risk operations. File system access, network access, process execution, and credential reading should all be completed through explicit authorization.

    Conclusion

    The competitiveness of agent systems will depend not only on model capability, but also on whether the runtime can quickly adapt to different tasks, environments, and governance requirements. Designing the runtime as a plugin-based microkernel essentially addresses three problems: how to replace capabilities, how to manage side effects, and how to handle dependency changes.

    Model adapters, tools, sessions, prompts, the Agent Loop, file systems, and sandboxes are no longer untouchable core components; they become runtime capabilities that can be composed as needed. Through reversible side effects, responsive dependencies, typed events, and unified lifecycle management, agent systems can evolve from single applications into extensible platform infrastructure.

    This approach is not without complexity, but it moves complexity from “continuous expansion of core code” to “protocols, lifecycle, and dependency governance.” For agent systems that require long-term maintenance, multi-environment deployment, and continuous extension, this is usually a more engineering-resilient choice.