Plugin-Based Architecture for Agent Runtime Frameworks: Principles and Practice

    This article explains why large language models need an agent runtime framework (harness), clarifies the difference between agent products and runtimes, and describes a "everything is a plugin" design. It covers the agent loop structure, the Skill/Tool/Hook extension layers with Guard, Approval, and Sandbox boundaries, plugin composition and lifecycle management, session event logging, the end-to-end tool-call chain, and practical steps and common pitfalls for building and validating your own runtime framework.

    1. Why Agents Need a Runtime Framework

    The basic output of a large language model is a sequence of tokens. The model itself cannot read files, call APIs, persist state, or judge whether an operation is safe. To make a model complete tasks such as “query data, modify configuration, generate a report,” the system must build an organizational layer around the model that converts model output into executable actions and feeds execution results back to the model.

    This layer is commonly called the agent runtime framework, often referred to as a “harness” in English. Its responsibilities fall into four categories:

    1. Model adaptation: hide interface differences between models and unify request/response formats.
    2. Tool management: register callable functions, describe parameter schemas, execute calls, and return structured results.
    3. Session and state: record conversation history, tool-call traces, and intermediate artifacts, supporting replay and auditing.
    4. Loop control: decide when to continue reasoning, when to invoke tools, and when to terminate the task.

    Without a unified framework, teams commonly face problems such as: every project re-implementing similar scheduling logic; tool permissions lacking unified constraints; and errors being hard to locate because there is no complete event record.

    2. Distinguishing Agent Products from Runtimes

    When discussing agent software, two concepts must be distinguished first.

    • Agent products face end users and focus on interaction experience, business workflows, and result delivery.
    • Runtimes face developers and focus on how tasks are decomposed, scheduled, isolated, and observed.

    The runtime framework sits between the two. The product layer can swap out interfaces and business logic, while the runtime framework provides a stable execution foundation. Separating the two helps teams iterate on upper-layer features without changing the underlying execution logic.

    3. The “Everything Is a Plugin” Design Philosophy

    The core claim of “everything is a plugin” is that the framework itself provides only a minimal kernel, and all capabilities are mounted as plugins. Model adaptation, tool registration, session recording, loop policies, and permission checks are all plugins. Plugins communicate through explicit interfaces and declare their dependencies.

    This design brings three benefits:

    • Replaceability: when switching model providers or storage backends, you only replace the corresponding plugin.
    • Composability: the same kernel can be assembled with different plugin combinations for different scenarios, forming multiple preset configurations.
    • Testability: each plugin can be verified independently, reducing overall debugging cost.

    The following pseudocode shows the basic form of plugin registration:

    1. kernel = create_kernel()
    2. kernel.register(model_adapter, provides="model")
    3. kernel.register(tool_registry, provides="tools", requires=["model"])
    4. kernel.register(session_log, provides="session")
    5. kernel.register(agent_loop, requires=["model", "tools", "session"])
    6. kernel.register(approval_guard, requires=["tools"])
    7. kernel.start()

    At startup, the kernel builds a dependency graph from requires and provides and initializes plugins in topological order. If a dependency cycle or missing dependency appears, it should fail at startup rather than surfacing during runtime.

    4. The Structure of the Agent Loop

    The agent loop is the core control flow in the runtime framework. A typical loop contains four steps:

    1. Assemble context: aggregate the task goal, message history, available tool descriptions, and a state summary.
    2. Request the model: send the context and obtain text or structured action output.
    3. Execute actions: if the output contains tool calls, parse and validate the parameters and execute; if the output is a final answer, end the loop.
    4. Record events: write the model output, tool calls, and execution results into the session log, which becomes the context source for the next round.

    The loop must define termination conditions—commonly a maximum step count, a cumulative cost cap, a timeout, and manual interruption. Without these limits, the model may fall into an infinite loop of repeatedly calling the same tool.

    1. loop:
    2. if step_count >= max_steps: break
    3. context = assemble(task, session.history(), tools.describe())
    4. output = model.generate(context)
    5. session.append(output)
    6. if output.is_final: break
    7. for call in output.tool_calls:
    8. check = guard.evaluate(call)
    9. if check.denied: session.append(denied_event(call)); continue
    10. result = executor.run(call)
    11. session.append(result)
    12. step_count += 1

    5. Extension Layers: Skill, Tool, and Hook

    Extension capabilities are usually divided into three layers, from coarse to fine granularity.

    Skill is a task-oriented capability package. It bundles a set of prompt templates, workflow instructions, and related tools together—for example, “code review” or “report generation.” A Skill answers the question of “how to act in a certain class of tasks.”

    Tool is an atomic capability callable by the model, such as reading a file, querying a database, or sending a request. Each tool must declare its name, purpose, parameter schema, and return format. Parameter validation should be completed before tool execution, avoiding passing illegal input to underlying systems.

    Hook is a callback attached to lifecycle nodes, triggered for example before a tool call, after a tool call, or at session start and end. Hooks suit cross-cutting concerns such as logging instrumentation, metrics collection, and result formatting.

    Above these three layers, execution boundaries are enforced through three mechanisms:

    • Guard (pre-check): evaluates calls against rules to determine whether they are legal—for example, whether a path is within the allowed range or parameters exceed thresholds.
    • Approval: requests human confirmation or higher-level policy approval for high-risk operations; if not approved, the operation is not executed.
    • Sandbox: confines tool execution to an isolated environment, restricting filesystem, network, and process permissions to limit the blast radius of mistakes.

    The three have distinct responsibilities and should not substitute for one another. Guards quickly reject clearly violating requests, Approval handles borderline cases requiring judgment, and the Sandbox provides the last line of defense when the first two fail.

    6. Plugin Composition and Lifecycle

    Plugin composition has two dimensions.

    • Static composition: the plugin set and dependency order are fixed at startup. This suits production environments, where behavior is predictable.
    • Dynamic composition: plugins are mounted or unmounted at runtime. This suits development, debugging, and gradual feature rollouts.

    In either mode, plugins should follow a unified lifecycle: initialize → start → run → stop → destroy. The framework must ensure the stop phase proceeds in reverse dependency order, so upstream plugins do not keep sending requests after downstream resources have been released.

    Hot updates are the most error-prone part of dynamic composition. Replacing a plugin involves three kinds of problems:

    1. State migration: how caches or session data held by the old plugin are handed over to the new one.
    2. In-flight calls: whether unfinished tool calls should be awaited, cancelled, or retried.
    3. Dependency recomputation: whether other components depending on the plugin need their bindings re-resolved.

    In practice, it is recommended to separate plugin state from behavior: put state in serializable storage and implement behavior as stateless functions. Then, when behavior is replaced, state does not need to be migrated.

    7. Session Event Logs

    Session records should not only store the final conversation text, but record every action as an event stream. Typical events include: user input, model output, tool-call requests, guard decisions, approval results, tool execution results, and error information.

    Event logs bring three benefits:

    • Debugging: you can reconstruct step by step where the agent deviated from expectations.
    • Auditing: every tool call carries a timestamp, parameters, and a result, making accountability traceable.
    • Replay: replaying the entire flow with recorded model outputs lets you validate changes to the tool layer and guard rules without calling the model.

    Logs should treat sensitive information distinctly. Parameters may contain credentials or personal data, which must be redacted before writing; secrets should be read from environment variables or a key management service and must never appear in logs or code.

    8. The Complete Chain from Tool Call to Runtime

    Take “read a configuration file and suggest modifications” as an example. The complete chain of one tool call is:

    1. The model outputs a structured tool-call request containing the tool name and parameters.
    2. The runtime framework parses the request and validates it against the tool’s parameter schema.
    3. The Guard checks the path and permissions and decides to allow the call.
    4. The operation is not in the high-risk category, so it proceeds directly to execution without approval.
    5. The executor reads the file inside the sandbox and returns the result truncated to the agreed length.
    6. The framework writes the request and result into the event log and appends them to the next round’s context.
    7. The model generates suggestions based on the file content, and the loop ends.

    Every stage can be tested independently. For example, you can write a set of unauthorized-path test cases for the Guard and truncation test cases for overly long outputs in the executor.

    9. Designing and Validating a Custom Runtime Framework

    When building your own framework, it is recommended to proceed in the following order.

    Step 1: Define the boundaries. List the model types, tool categories, deployment environments, and security requirements the framework must support. The clearer the scope, the more stable the plugin boundaries.

    Step 2: Determine the minimal kernel. The kernel handles only plugin registration, dependency resolution, lifecycle scheduling, and event dispatch. All business capabilities go into plugins.

    Step 3: Design preset combinations. Provide several plugin combinations for common scenarios—for example, a lightweight configuration supporting conversation only, a standard configuration with tool calling, and a controlled configuration requiring strict approval. Presets help new users get started quickly and help teams compare behavioral differences across configurations.

    Step 4: Establish validation methods. You can observe and test along these dimensions:

    • The distribution of loop step counts and the timeout ratio, to judge whether termination conditions are reasonable.
    • Tool-call failure and rejection rates, to judge whether parameter descriptions are clear and guard rules are too strict or too loose.
    • Result differences for the same task under different plugin combinations, to judge whether hidden coupling exists between plugins.
    • Fault-injection tests—for example, simulating model timeouts, tools returning malformed output, and plugin startup failures—to verify the framework’s degradation and error-reporting behavior.

    These metrics should be based on your team’s own baseline data rather than directly borrowing external empirical figures.

    10. Common Pitfalls

    • More plugins mean more flexibility: increasing plugin count amplifies dependency complexity. Keep the core path simple first, then extend gradually.
    • Implicit dependencies: sharing state between plugins via global variables makes hot updates and testing difficult. All dependencies should be declared explicitly.
    • Overly broad default permissions: if tools have full filesystem and network permissions by default, induced model output poses serious risk. Apply the principle of least privilege and grant access on demand.
    • Evaluating only the final result: assessing answer quality alone misses errors in intermediate steps. Every action in the event log should also be checked.

    The value of an agent runtime framework lies in bringing the model’s uncertain output into a controllable, observable, and replaceable engineering system. Plugin-based design is a common path to that goal, but the key remains clear boundaries, explicit dependencies, and thorough validation.