Plugin-Based Design for Agent Runtimes: Architecture and Practice

    This article explains why agent runtimes are needed and how a plugin-based design can split models, tools, sessions, sandboxes, storage, execution loops, scheduling, and interfaces into replaceable components. It covers the responsibilities of the plugin kernel, the service and event mechanisms, configuration-based composition, four execution modes, security principles for tool calls, and the steps to build a minimal runtime.

    1. Why Agent Runtimes Are Needed

    A large language model only receives text and outputs text. To search for information, modify code, or read and write files, engineers must build a software layer around the model. This layer organizes multi-turn conversations, parses the model’s output into tool calls, runs the tools and feeds the results back to the model, manages session state, and limits execution permissions. The industry usually calls this layer the agent runtime, or Agent Harness. The relationship can be summarized as:

    Agent = Model + Runtime

    The model sets the upper limit of reasoning ability, and the runtime determines whether that ability can reliably carry out concrete tasks. Both are required.

    Early agent implementations often put loop logic, tool definitions, prompts, and the user interface in the same code. This approach is efficient during prototyping, but as projects grow, three problems appear:

    • Changing the model requires changes to business logic, which makes migration costly.
    • Tools and the loop depend on each other, so they cannot be tested separately.
    • The same capabilities are hard to reuse across entry points such as the command line, a web page, or batch jobs.

    Plugin-based architecture is designed to solve these problems.

    2. Core Idea: Split Each Capability into a Replaceable Plugin

    The basic principle of plugin-based architecture is that every capability in the runtime should be an independent component. Each component can be replaced, tested on its own, and loaded on demand. The common ways to split these components are shown in the table below.

    Component Responsibility Replacement example
    Model adapter Unifies the calling protocols of different models Switch from a cloud API to a locally deployed model
    Tool Wraps external operations such as search and file read/write Replace the search tool with an internal enterprise knowledge base interface
    Skill Combines prompts and tools by task Package a separate configuration for code review scenarios
    Session Saves and restores conversation history Change from in-memory storage to database storage
    Sandbox Limits the execution environment and permissions of tools Change from direct execution on the host to container isolation
    Storage Persists files, logs, and intermediate results Change from local disk to object storage
    Execution loop Sets the rhythm of interaction between the model and tools Change from step-by-step execution to planning first, then batch execution
    Scheduler Manages concurrent tasks and timed triggers Change from synchronous calls to message queue consumption
    User interface Provides a command line, web page, or API service Mount different interface plugins on the same kernel

    This split brings three direct benefits.

    First, replacement costs are low. When you change a model or storage backend, you replace only the corresponding plugin. The loop and tool logic stay the same.

    Second, testing is fine-grained. Tool plugins can be unit-tested with fixed inputs, and loop plugins can be replay-tested with a simulated model. The real model does not need to be called every time.

    Third, reuse is broad. The same kernel can mount different interface and scheduling plugins, which allows it to serve both interactive use and background batch processing.

    3. Three Responsibilities of the Plugin Kernel

    The plugin kernel needs to do only three things: load and unload plugins, resolve dependencies between plugins, and manage plugin lifecycles. Everything else, including model calls, tool execution, and interface rendering, is handled by plugins. The thinner the kernel, the clearer the boundaries between plugins, and the easier the system is to evolve.

    3.1 Dependency Declaration

    Each plugin declares which services it depends on. At startup, the kernel uses the dependency graph to decide the loading order. If a dependency is missing, the kernel fails immediately instead of failing partway through a run. Dependencies should be kept to a minimum. Plugins should depend only on service interfaces, not on the internal implementations of other plugins.

    3.2 Services and Events

    Plugins collaborate mainly through two mechanisms.

    • Services: synchronous capability interfaces, such as model completion or tool lookup. Use a service when the caller needs an immediate result.
    • Events: asynchronous notifications, such as tool execution completed, session ended, or error occurred. Observers, such as logging or monitoring plugins, get information by subscribing to events. Business plugins do not need to call them directly.

    3.3 Composing Components Through Configuration

    Component selection should happen in configuration, not in code. The example below is illustrative. Its names are generic category names and do not refer to any specific product.

    1. agent:
    2. model: model-adapter-default
    3. tools:
    4. - search
    5. - file-reader
    6. loop: loop-basic
    7. sandbox: sandbox-container
    8. storage: storage-local
    9. session: session-memory

    To switch models, add tools, or move to isolated execution, you change only this configuration, as long as the corresponding plugins are installed.

    4. Design Trade-offs of Four Execution Modes

    A runtime typically offers several execution modes. Each mode suits a different task scale and risk tolerance. The modes below are described in general terms.

    4.1 Standard Mode

    Standard mode follows a loop of “model reasoning, tool call, result feedback, then reasoning again.” The model decides each next action, which suits most interactive tasks. Its logic is intuitive and easy to debug. Its drawback is that every round trips to the model, so latency and cost accumulate when a task has many steps.

    4.2 Programmatic Tool Calling Mode

    In this mode, the model does not issue tool calls one at a time. Instead, it generates a structured execution plan or script. The runtime then orchestrates multiple tool calls in a controlled environment and returns the aggregated results to the model. This reduces the number of model round trips and suits batch reads, data transformation, and other tasks that can be planned in advance. The cost is stricter sandbox isolation and structural validation of generated plans, which prevents a plan from exceeding its permissions.

    4.3 Minimal Mode

    Minimal mode keeps only the model, a minimal tool set, and a basic loop. It omits components such as session persistence and complex scheduling. This mode suits capability evaluation, quick checks of prompt effects, and lightweight tasks in resource-constrained environments. With fewer components, results are easier to attribute.

    4.4 Creative Mode

    Creative mode relaxes constraints on the model. It lets the model break down goals on its own, explore multiple paths, and decide the order of tool use. This mode suits open-ended design and exploration tasks. Its outputs are the least predictable, so it needs thorough logging and human checkpoints.

    When choosing a mode, weigh three factors: whether the task steps can be determined in advance, how important reproducible results are, and how much latency and cost are acceptable.

    5. Security Boundaries for Tool Calls

    Tools are the main way an agent affects the outside world, so security design should start at the tool layer. The following principles are common engineering practices.

    1. Least privilege: Grant each tool only the permissions needed for its task. For example, a read-only file tool should not have write access.
    2. Parameter validation: Validate parameter types, value ranges, and path scopes at the tool entry point with a structured schema. Reject calls that do not meet the contract.
    3. Sandbox isolation: Tools that execute code or commands should run in an isolated environment, with restricted network and file access.
    4. Separation of data and instructions: Treat web page content and file content returned by tools as data, never as instructions to execute. This is a basic requirement for defending against indirect prompt injection.
    5. Human confirmation for high-risk actions: Pause operations such as deletion, sending, deployment, and permission changes until the user confirms.
    6. Audit logs: Record the name, parameter summary, result status, and duration of each tool call so that actions can be traced later.

    The example below shows how to run an external command safely. It does not pass the whole string to a shell. Instead, it splits the command into an argument list and checks that the program is on an allowlist, which prevents command injection.

    1. import shlex
    2. import subprocess
    3. ALLOWED_PROGRAMS = {"ls", "wc", "grep"}
    4. def run_shell_tool(command: str, timeout: int = 30) -> str:
    5. argv = shlex.split(command)
    6. if not argv:
    7. raise ValueError("Command is empty")
    8. if argv[0] not in ALLOWED_PROGRAMS:
    9. raise PermissionError(f"Program not allowed: {argv[0]}")
    10. result = subprocess.run(
    11. argv,
    12. capture_output=True,
    13. text=True,
    14. timeout=timeout,
    15. check=False,
    16. )
    17. return result.stdout

    This code is only a sketch. In production, the command should also run inside a sandbox, and the directories it can access should be restricted.

    6. Building a Minimal Replaceable Runtime from Scratch

    The steps below show how to build a minimal plugin-based runtime. The goal is to complete one full cycle of “model reasoning, tool call, result feedback,” with both the model and the tools replaceable.

    Step 1: Define the Plugin Interface

    Start by defining a unified plugin protocol. It should include a name, a dependency list, and initialization and teardown methods. The more stable the interface, the easier it is to reuse plugins later.

    Step 2: Implement the Service Registry

    The kernel maintains a service registry. During initialization, each plugin registers the services it provides, and dependent plugins look them up by name. The registry should run its checks at startup, and any missing service should raise an error immediately.

    Step 3: Implement the Execution Loop Plugin

    The execution loop plugin is the core of the runtime. The code below is an illustrative sketch of the basic loop structure.

    1. MAX_STEPS = 10
    2. class BasicLoopPlugin:
    3. name = "loop-basic"
    4. depends = ["model", "tools"]
    5. def setup(self, ctx):
    6. self.model = ctx.get_service("model")
    7. self.tools = ctx.get_service("tools")
    8. def run(self, session, user_input: str) -> str:
    9. messages = session.history + [{"role": "user", "content": user_input}]
    10. for _ in range(MAX_STEPS):
    11. reply = self.model.complete(messages, tools=self.tools.schem