AI Agent Runtime Architecture: A Plugin-First Design Approach

    This article explains why a large language model alone is not an agent and how a runtime layer turns it into one. It walks through a plugin-first architecture in which the core keeps only an event bus, a plugin assembler, and a session execution loop, and covers the unified plugin contract, switchable execution modes matched to task complexity, a model-agnostic adapter layer, the execution loop with explicit termination conditions and error recovery, security and permission boundaries, cross-platform and multimodal compatibility, ecosystem governance, and a pre-launch checklist for cloud deployment.

    1. Where the Problem Starts: A Model Is Not an Agent

    A large language model is essentially a stateless autoregressive function: you give it text, it returns text. It does not know what time it is, it retains no memory of the previous session, and it cannot write files, send requests, or pause itself to wait for approval. Turning a model into an agent that can actually complete tasks requires not more parameters, but a full set of supporting mechanisms built around the model.

    The relationship can be summarized as an equation:

    1. Model + Runtime(Harness) = Agent

    The runtime has to close four gaps:

    • State gap: session history, cross-session memory, and intermediate artifacts of long-running tasks need an addressable external store.
    • Action gap: tool registration, parameter validation, execution, and feeding results back give the model its hands and feet.
    • Control gap: advancing and terminating the loop, step/token/duration budgets, and retry and fallback after failures.
    • Governance gap: permissions, sandboxing, auditing, and cost and latency observability.

    Once you understand these four gaps, you understand why the engineering focus of the past two years has shifted from “fine-tuning the model” to “designing the runtime”: model capabilities are rapidly converging, while the same model can differ by an order of magnitude in task success rate across different runtimes.

    2. The First Design Principle: Everything Is a Plugin

    “Everything is a plugin” is not marketing language but an architectural constraint: the core keeps only three things — an event bus, a plugin assembler, and a session execution loop — and everything else lives outside it. The direct consequence is that the core codebase stays small enough to be fully understood, while the capability boundary is defined by the set of installed plugins.

    For this to actually hold, the plugin system must provide a stable unified contract, typically made of three parts:

    1. Declarative manifest: id, version, required capabilities, permission declarations, and dependencies on other plugins.
    2. Behavior implementation (handler): tool definitions, event handlers, and command registrations.
    3. Lifecycle hooks: onLoad / onEnable / onDisable / onUnload, which must be idempotent and rollback-safe.

    An illustrative plugin definition (pseudocode, meant to convey structure rather than a concrete interface):

    1. // Permission declaration + tool declaration + lifecycle make up the plugin contract
    2. export const manifest = {
    3. id: "fs-sandbox",
    4. version: "1.0.0",
    5. requires: ["runtime.tool-bus@^1"],
    6. permissions: { fs: "workspace:rw", net: "deny" },
    7. capabilities: ["filesystem"],
    8. };
    9. export function tool() {
    10. return {
    11. name: "read_file",
    12. // Parameters described with a structured schema so the core can validate them upfront
    13. input: { path: "string", maxBytes: "int<=1048576" },
    14. async invoke(ctx, args) {
    15. return ctx.fs.read(args.path, { maxBytes: args.maxBytes });
    16. },
    17. };
    18. }
    19. export async function onEnable(ctx) {
    20. await ctx.tools.register(tool());
    21. }
    22. export async function onUnload(ctx) {
    23. await ctx.tools.unregister("read_file"); // unloading must be rollback-safe
    24. }

    Assembly order is determined by the dependency graph, not by a hardcoded load location. Two engineering requirements here are easy to underestimate: dependency cycle detection and failure isolation — an exception thrown by a single plugin must not crash the whole runtime; it should degrade to “this capability is unavailable” and be broadcast to upper layers as an event.

    3. Modes as Policy: Match the Execution Mode to Task Complexity

    The “optimal execution strategy” varies enormously across tasks. Asking users to describe the workflow in a prompt is fragile; a better approach is to distill common strategies into switchable execution modes (preset modes):

    • Minimal mode: a single turn or a few turns, with a very small or even empty toolset. Suitable for rewriting, summarization, and classification. The payoff is optimal latency and cost.
    • Standard mode: the classic “plan–act–observe” loop, combined with a controlled tool allowlist and a maximum step limit. Suitable for the vast majority of everyday tasks, and the recommended default.
    • Programmatic tool calling (PTC) mode: instead of making the model make a round trip at every step, the model produces a piece of executable orchestration code that writes multiple tool calls, loops, and conditional branches into a program executed in one pass. Suitable for deterministic pipelines with known steps, and it can significantly reduce round trips and context bloat.
    • Creative mode: a larger tool surface and a more generous exploration budget for open-ended tasks. The cost is unpredictable behavior, so it must be paired with stronger sandboxing and approval checkpoints.

    There is only one selection principle: start from least privilege and the simplest mode, and escalate as needed. Switching modes should be a runtime configuration item, not a rewrite of the prompt. The real difficulty of PTC mode lies not in generating code but on the execution side — it needs a restricted interpreter, timeout circuit breaking, side-effect rollback, and a clear error feedback format.

    4. A Model-Agnostic Integration Layer

    The key to being “model-agnostic” is an adapter layer, not an abstraction layer: do not pretend all models behave identically; instead, converge the differences into a single adapter.

    The adapter layer needs to cover:

    • Unified capability abstraction: message roles and multi-turn organization, tool declaration formats, streaming events, structured output, and multimodal input.
    • Difference adaptation: parsing and serializing tool-call syntax, context window trimming strategy, reasoning budget parameters, and mapping of failure-code semantics.
    • Capability negotiation and degradation: plugins declare required capabilities via requires (such as “vision input”, “long context”, “structured output”), and the assembler decides whether to enable or degrade based on the capabilities actually available in the model.
    • Routing strategy: selecting a model by task type, cost, latency, and data compliance requirements, and switching by priority on failure.
    • Contract convergence: tool definitions are written once, and the adapter layer translates them into each model’s dialect.

    Practical advice: treat both “prompt templates” and “tool schemas” as first-class citizens of the adapter layer and put them under version control, so the two do not drift apart.

    5. The Execution Loop: Scheduling, State, and Error Recovery

    The core competitiveness of a runtime shows up in the loop, not in the examples.

    • Make termination conditions explicit: goal reached, maximum steps exceeded, token/duration/cost budget exhausted, or human confirmation required. A loop without a budget cap is a common source of production incidents.
    • Context engineering: truncate and produce structured summaries of tool return values, apply rolling compression to history, and externalize long-horizon artifacts to object storage or a database, keeping only references in the context.
    • Classified error handling: distinguish “retryable” (rate limits, timeouts), “needs clarification” (missing parameters, ambiguous intent), and “fatal” (insufficient permissions, missing resources) — the three classes map to three different feedback messages and control flows.
    • Idempotency and side effects: write operations carry an idempotency key; side effects spanning multiple steps are compensated in reverse order on failure rather than simply retried.
    • Async long-running tasks: tasks longer than a few seconds are dispatched to a message queue and return results via events or callbacks, avoiding long-held connections.
    1. while budget.ok() and not done:
    2. plan = model.decide(state)
    3. for call in plan.calls:
    4. if call.requires_approval: await human.approve(call)
    5. result = tools.invoke(call, idempotency_key=call.id)
    6. state.append(classify(result)) # retryable / needs clarification / fatal
    7. state = memory.compact(state) # context budget maintenance

    6. Security and Permissions: Distrust All External Input by Default

    An agent wires “free generation by the model” directly to “real side effects in the environment”. That is its greatest value and its largest risk surface. The following boundaries are required:

    • Least-privilege toolset: each plugin only gets the capabilities it has declared; outbound network access is denied by default.
    • Sandboxed execution: code execution and command execution run inside disposable containers, with a restricted writable filesystem scope and resource quotas.
    • Prompt injection protection: tool output, web content, and file content are all treated as untrusted data, labeled by source and delimited in the prompt, and forbidden from rewriting system instructions.
    • Approval for high-risk actions: insert a human-in-the-loop confirmation checkpoint for irreversible or high-impact operations.
    • Auditing and observability: log the full chain of inputs, tool calls, parameters, and return summaries, combine it with logging services and monitoring alerts for anomaly detection, and mask sensitive fields before writing to storage.
    • Plugin supply chain governance: pinned versions, source verification, canary releases, and one-click disable. In an open ecosystem, plugins are the largest attack surface.

    7. Cross-Platform, Multimodal, and Compatibility Layers

    • Decouple the session model from the interface: the same session state must support desktop apps, web, command line, and other hosts; the UI layer only renders the event stream and carries no business logic.
    • Capability-probe-driven degradation: the desktop side may have filesystem and clipboard access while the container side does not; plugins should probe explicitly and degrade gracefully when a capability is missing rather than throwing at runtime.
    • Multimodal transport: media content is passed via short-lived references (object storage or temporary URLs) to avoid inlining large binaries into the context.
    • Benefits and costs of a compatibility layer: providing a compatibility mechanism to connect with existing industry tool and skill conventions can greatly reduce migration cost, but it inherently brings three risks: protocol drift, implicit coupling, and inconsistent security semantics. Engineering practice should make it explicitly versioned, off by default, backed by contract tests and differential tests, and clearly marked as experimental in the documentation.

    8. Ecosystem Building: Three Things Beyond Count

    The maturity of a plugin ecosystem is measured not by count but by being discoverable, verifiable, and maintainable:

    • Discoverable: structured metadata plus categories plus usage popularity, so that “finding the right plugin” costs less than “writing one yourself”.
    • Verifiable: source identification, public permission disclosure, and security scan results shown upfront.
    • Developer experience: scaffolding and templates, local hot-reload debugging, and unified error messages and call-chain tracing — these determine author retention.

    There also needs to be a takedown and governance mechanism, so the community ecosystem is not held hostage by a few high-privilege plugins.

    9. Cloud Deployment and a Pre-Launch Checklist

    Hosting this kind of runtime in the cloud can be composed from general capability categories: a container platform hosts the runtime and disposable sandboxes, object storage holds session artifacts, a message queue carries long-running tasks and async callbacks, logging services and monitoring alerts provide observability, and a key management service holds credentials. On Baidu AI Cloud, such a runtime can be built from these general categories, avoiding coupling state to a single-host process.

    Pre-launch checklist:

    • Does every tool call pass parameter validation and permission-declaration validation?
    • Are there four budget caps: steps, tokens, duration, and cost?
    • Is external content labeled as untrusted data and protected against instruction injection?
    • Are write operations idempotent and failures compensable?
    • Is plugin unloading rollback-safe, and is a single plugin crash isolated?
    • Are full-chain logs and metrics available, and is sensitive information masked?

    Common anti-patterns: hardcoding workflow logic in prompts; using one giant system prompt in place of architectural constraints; giving the loop no termination condition; treating plugin count as a quality metric; treating the compatibility layer as a long-term main-path dependency.

    Conclusion

    The essence of a plugin-based agent runtime is confining “uncertainty” inside a composable, observable, rollback-safe container: the model handles judgment, and the runtime handles boundaries, state, and recovery. Understanding the contract and assembly mechanism behind “everything is a plugin”, and the relationship between execution modes and task complexity, lets you make grounded decisions between building your own and selecting an existing one — which has more long-term value than chasing the version number of any single framework.