Pluggable AI Agent Runtime: Plugin Selection and Architecture Practices

    This article explains how to build a pluggable AI agent runtime from an empty plugin tree, layered base capability packs, scenario plugins, and user configuration patches. It covers the core components a base pack should provide, the plugin categories to prioritize, safety controls for tools and approvals, and why complete logs matter for debugging and audit. It also suggests an adoption order for teams starting out.

    1. Understanding Plugin-Based Agent Runtimes

    In traditional applications, features are usually compiled into the main program as modules, services, or middleware. In newer agent systems, the model, tools, context, approvals, memory, and execution loop can all change from one scenario to another. A better approach is to assemble the system from an empty runtime, a plugin tree, and configuration patches.

    This kind of system can be divided into three layers:

    1. Runtime kernel: loads configuration, resolves dependencies, manages lifecycles, and records execution logs.
    2. Base capability packs: provide common capabilities such as model calls, sessions, tools, planning, sandboxing, context compression, and sub-agents.
    3. Scenario plugins and user patches: replace or add specific tools, policies, and interface capabilities for a given product.

    At startup, the configuration root can be initialized as an empty list. The final runtime is then built layer by layer from base capability packs and user patches. The product is not hard-coded into the main program. It is composed from replaceable capability units.

    The loading process works like this:

    1. Empty plugin tree
    2. ↓
    3. Base capability pack
    4. ↓
    5. Scenario capability pack
    6. ↓
    7. User configuration patch
    8. ↓
    9. Final agent runtime

    This approach suits systems that must support several agent types. One core runtime can assemble a coding assistant, a knowledge retrieval assistant, an automation assistant, or a multi-agent collaboration system. Teams do not need to maintain a separate core codebase for each product.

    2. What the Base Capability Pack Should Cover

    A complete base capability pack includes more than a model adapter. It should provide the full loop an agent needs to run.

    1. Model and call adapter

    The model adapter layer unifies how different model services are called. It handles message format conversion, streaming output, tool calls, error retries, and timeout control. Define a unified interface rather than letting upper-layer code depend directly on one model service’s request format.

    For example, a model call can be abstracted as:

    1. interface ModelAdapter {
    2. generate(input: ModelInput): AsyncIterable<ModelEvent>;
    3. supports(feature: ModelFeature): boolean;
    4. }

    Upper layers only need the generated results and the capability declarations. The adapter decides which model to use and whether it supports features such as visual input or tool calls.

    2. Session and state management

    The session module stores messages, tool calls, execution results, approval records, and context summaries. State should not live only in memory. Otherwise, a process restart makes recovery impossible, and problems become hard to trace.

    A sound approach has these parts:

    • Record session events in structured storage.
    • Model user messages, model responses, and tool results as separate types.
    • Assign a unique identifier to each execution.
    • Rebuild the current session state from events.
    • Redact sensitive content, or store it in tiers based on its sensitivity.

    3. Agent and execution loop

    The execution loop is the core of the system. It typically performs these steps:

    1. Read the current session state.
    2. Select the available tools and system rules.
    3. Call the model to generate the next action.
    4. Decide whether the action needs approval.
    5. Run the tool or create a sub-agent.
    6. Write the result to the log.
    7. Check the termination conditions and decide whether to continue.

    Design the execution loop around a factory or registration mechanism. Avoid keeping a single global implementation in the code. This lets developers swap loop strategies, such as a short-task mode, a planning-first mode, a strict approval mode, or a multi-agent collaboration mode.

    If a loop registration is removed, the system should fail early with a clear error. A message such as “agent execution factory is not registered” is direct, and it is easier to diagnose than a null pointer exception that appears later in the flow.

    3. Plugin Directions to Prioritize

    Choose plugins based on observability, runtime stability, and context efficiency, not on feature count.

    Layer 1: Observability and debugging

    The most common problem in agent systems is not that the model cannot answer. Developers simply do not know why it answered the way it did. A complete observability plugin should provide at least:

    • A session timeline
    • Model requests and responses
    • Tool call parameters and return values
    • Approval nodes and rejection reasons
    • Parent-child relationships between sub-agents
    • Changes in context length
    • Duration and error information for each step

    Treat a session as an execution tree, not a flat list of messages. The root node is the main agent. Child nodes are derived tasks. Tool calls are events under their nodes. The tree shows who created whom, which tool ran, and which step failed.

    The observability interface can include a session page, a context page, and a runtime status panel. For multi-agent systems, add an overview that shows the current agent, its parent, and all sub-tasks in one relationship graph.

    Layer 2: Cost and resource management

    Model calls consume resources in a measurable way. A cost plugin should show the cost of each call and also record:

    • Cumulative consumption per session
    • Consumption grouped by date, project, or user
    • The ratio of input tokens to output tokens
    • Resource use by model and task type
    • Budget limits and alert status
    • Degradation or blocking policies when limits are exceeded

    Cost statistics must rely on reliable events, not only on front-end estimates. After each model call completes, record the model identifier, input size, output size, call duration, and the information needed for pricing. If the actual cost cannot be calculated precisely, label it as an estimate. This keeps estimates from being mistaken for billing data.

    In enterprise environments, combine budget controls with the permission system. For example, routine tasks can use a base model, while complex tasks require additional approval. When a session exceeds its limit, the system can switch to summary mode or ask the user to confirm.

    Layer 3: Context management and compression

    Context length directly affects response quality, latency, and resource use. A practical context plugin should support layered management:

    • Keep recent messages in full.
    • Convert older messages into structured summaries.
    • Extract stable facts into long-term memory.
    • Keep only the key fields from tool outputs.
    • Load large files by reference instead of injecting them repeatedly.

    Compression should not simply truncate old messages. A more reliable process first identifies the task goal, confirmed facts, pending items, decision rationale, and constraints. It then produces a summary that can be verified.

    For example:

    1. Task goal: complete an automated operation
    2. Completed: checked configuration, generated execution plan
    3. Key constraint: production data must not be modified
    4. Pending: execute step 3 after approval

    After generating a summary, keep an index to the original events so you can trace back when needed. The goal of compression is not to delete history. It moves history from “always injected into context” to “retrieved on demand.”

    Also pay attention to prefix caching and context stability. If the system prompt, tool definitions, and long-term rules change often, cache reuse drops, and the model may interpret the rules inconsistently. Keep stable content separate from dynamic content, and keep the prefix structure as stable as possible.

    4. Execution Safety: Tools, Sandboxes, and Approvals

    Tool plugins let an agent move from conversation to action. They are also where risk is most concentrated.

    Tool design should follow the principle of least privilege:

    • Each tool exposes only the parameters it needs.
    • High-risk operations are denied by default.
    • File, network, and system command access are authorized separately.
    • Tool inputs are validated by type.
    • Tool outputs are limited in length and stripped of sensitive fields.
    • Every execution action is written to an auditable log.

    A sandbox isolates code execution, file operations, and network access. Do not treat it as an absolute security boundary. Use it together with permissions, resource limits, and human approval.

    Approval policies fall into three categories:

    1. Automatic approval: low-risk, read-only, reversible operations.
    2. Conditional approval: actions run automatically when path, amount, scope, or permission conditions are met.
    3. Human confirmation: writing to production data, sending external messages, or performing irreversible operations.

    Approval results are also session facts. Record the approver, the time, a summary of the action, and the final decision. This prevents a situation where the system acted but nobody knows why.

    5. Sub-Agents and Workflow Plugins

    Sub-agents suit complex tasks that can be split up. For example, one agent plans, another retrieves information, and a third verifies results. A sub-agent should not simply copy the main agent. It needs a clear scope of responsibility.

    When designing a sub-agent, define:

    • The input and output format of each sub-task
    • The tools it can access
    • The maximum execution time
    • The maximum recursion depth
    • The retry behavior after a failure
    • Whether it can create further sub-tasks
    • How its results are merged back into the main task

    Workflow plugins suit tasks with fixed steps. Compared with a f