Everything as a Plugin: A Design and Deployment Guide for AI Agent Runtimes

    This guide explains how to build a modular AI agent runtime by separating models, tools, skills, and interfaces into replaceable plugins. It covers runtime context management, routing, retries, execution modes, plugin security, cloud deployment, and a practical pre-launch checklist.

    Plugin-Based Design: Decomposing an Agent into Replaceable Modules

    Many AI applications place model calls, business logic, and tool integrations in the same application layer. When requirements change, even a small modification can affect the entire system. A plugin-based design separates an agent into several independent module types. Each module communicates with the framework through a standardized interface.

    The four most common plugin types are:

    1. Model plugins: Encapsulate large language models from different providers and with different parameter scales. The underlying model can be selected according to task difficulty and budget.
    2. Tool plugins: Encapsulate external capabilities such as API calls, database queries, and code execution sandboxes.
    3. Skill plugins: Encapsulate domain-specific prompt templates, reasoning steps, or result-processing rules.
    4. Interface plugins: Handle input and output and connect the agent to a command-line interface, web application, or API.

    The framework uses a registry to manage plugin registration, versions, and lifecycles. The registry can support hot swapping, but safe hot swapping requires three capabilities.

    First, it must check versions and dependencies to prevent library conflicts between plugins. Second, it must perform health checks and refuse to mount a new plugin if initialization fails. Third, it must support rollback so the system can return to the previous working version if a replacement causes problems in production.

    Without these three safeguards, hot swapping can introduce failures directly into a live environment.

    Runtime Frameworks: Model + Harness = Agent

    The basic formula for an AI agent is:

    Model + Harness = Agent

    The model handles intent understanding, reasoning, and planning. The harness—the runtime framework—handles context management, state maintenance, and plugin scheduling. A capable harness needs three core functions.

    Context Window Management

    During a long conversation, the framework can truncate history using a sliding window or write long-term memories to a vector store for retrieval when needed.

    A sliding window is simple to implement but may discard early information. Vector retrieval preserves long-term memory, but retrieval can miss important details. A practical design should therefore retain the most recent several turns in their original form as a fallback.

    Intent Parsing and Routing

    The framework identifies tool-call requests in the model output, validates their parameters, and converts them into standardized program calls.

    If parameter validation fails, the framework should return the error to the model so it can generate a corrected request instead of executing the invalid call directly.

    Error Handling and Retries

    When a tool call times out or the network connection is interrupted, the framework should retry according to a defined policy and use exponential backoff. This prevents repeated failures from overwhelming downstream services.

    For write operations, an idempotency key is required before retrying. Otherwise, the same order or transaction could be submitted twice.

    The following example shows a plugin interface with version, permission, and timeout fields. It also demonstrates parameter validation, secret retrieval, and exception handling.

    1. import os
    2. from abc import ABC, abstractmethod
    3. from typing import Any, Dict
    4. import requests
    5. class BasePlugin(ABC):
    6. @abstractmethod
    7. def get_metadata(self) -> Dict[str, Any]:
    8. """Return plugin metadata: name, version, description, parameters,
    9. required permissions, and timeout in seconds."""
    10. @abstractmethod
    11. def execute(self, params: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
    12. """Execute the plugin logic. The caller must receive a result within
    13. the configured timeout and validate the response structure."""
    14. class WeatherToolPlugin(BasePlugin):
    15. def get_metadata(self) -> Dict[str, Any]:
    16. return {
    17. "name": "get_weather",
    18. "version": "1.0.0",
    19. "description": "Get current weather information for a city",
    20. "parameters": {"city": "string"},
    21. "permissions": ["network:weather-api"],
    22. "timeout_seconds": 5,
    23. }
    24. def execute(self, params: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
    25. city = params.get("city")
    26. if not isinstance(city, str) or not city.strip():
    27. return {"status": "error", "message": "city must be a non-empty string"}
    28. # Read secrets from environment variables or a secret service.
    29. # Do not hard-code or print them in logs.
    30. api_key = os.environ.get("WEATHER_API_KEY")
    31. if not api_key:
    32. return {"status": "error", "message": "Weather API key is not configured"}
    33. try:
    34. resp = requests.get(
    35. "https://weather.example.com/v1/current",
    36. params={"city": city.strip()},
    37. headers={"Authorization": f"Bearer {api_key}"},
    38. timeout=5,
    39. )
    40. resp.raise_for_status()
    41. data = resp.json()
    42. except requests.RequestException:
    43. return {"status": "error", "message": "Weather service is temporarily unavailable"}
    44. # Validate the response structure before passing data to the model.
    45. weather = data.get("weather")
    46. temp = data.get("temp")
    47. if not isinstance(weather, str) or not isinstance(temp, str):
    48. return {"status": "error", "message": "Invalid weather service response"}
    49. return {"status": "success", "weather": weather, "temp": temp}

    The permissions field in this example supports least-privilege access control. The framework should allow a plugin to access only the network addresses and file paths declared in its permissions. All other access must be denied.

    Timeouts should be controlled centrally by the framework. The plugin-level timeout is a second line of defense.

    Four Execution Modes and How to Choose Among Them

    A runtime framework typically provides four execution modes. Developers should select one based on the characteristics of the task.

    1. Standard Mode

    Standard mode uses patterns such as ReAct—alternating reasoning and action—or Plan-and-Solve, in which the model plans before execution.

    At each step, the model produces its reasoning process and next action. The framework executes the action, returns the result to the model, and begins another reasoning round.

    This mode is suitable for multi-step business processes that require dynamic decisions. The trade-off is higher latency and token usage because the model is called at every step.

    2. PTC Mode: Programmatic Tool Calling

    In PTC mode, the model generates a program that calls tools. The program runs in a sandbox, can invoke multiple tools in batches, and returns an aggregated result to the model at the end.

    Intermediate results do not pass through the model, reducing both the number of model calls and token consumption.

    PTC differs from a predefined workflow because the model writes the tool-calling logic at runtime. In a predefined workflow, the developer defines the execution graph in advance and the model makes decisions only at selected points. This approach is known as workflow orchestration.

    3. Minimal Mode

    In minimal mode, the model produces a final answer or a single tool call. The framework executes the call and returns the result without performing multi-step planning.

    This mode provides the lowest latency and the most predictable cost. It is suitable for single-step tasks such as question answering, classification, and information extraction.

    It is not suitable for tasks that require repeated adjustments based on intermediate results, because the model has no opportunity to correct its initial decision.

    4. Creative Mode

    In creative mode, the model generates new tool code or skill templates at runtime. These artifacts can be registered only after review.

    This mode is useful for exploring new capabilities, but its output is less stable. Generated code may contain errors or perform unauthorized operations.

    The following restrictions apply:

    • Generated code must pass static analysis and sandbox testing.
    • New plugins must be approved by a person or an automated pipeline.
    • New plugins must not be mounted automatically in production.
    • Creative mode should be enabled only in development or offline environments.

    Execution Mode Comparison

    Dimension Standard Mode PTC Mode Minimal Mode Creative Mode
    Typical use case Multi-step workflows requiring dynamic decisions Batch tool calls with large intermediate results Single-step Q&A, classification, and extraction Exploring new tools or skills
    Model call frequency Once per step; many rounds Usually one program-generation call; fewer rounds Once Multiple generation and review steps
    Token usage and latency High Lower Lowest High, with additional review time
    Result determinism Moderate; depends on each reasoning round Relatively high; program logic is fixed after generation High Low; output requires human confirmation
    Main risk Uncontrolled cost and repeated loops Generated code errors or unauthorized access Cannot correct the first decision Unsafe generated code
    Recommended use When the steps cannot be determined in advance When many tools and large data volumes are involved Consider this the default for simple tasks Offline development only

    A Practical Selection Process

    1. Determine whether the task can be expressed as a fixed sequence of steps. If it can, prefer workflow orchestration instead of asking the model to make every decision.
    2. If the task produces a single-step output, use minimal mode.
    3. If the task requires multiple decisions and each step depends on the previous result, use standard mode. Set a maximum number of rounds and a cost limit.
    4. If the task requires multiple tool calls and processes large amounts of intermediate data, use PTC mode. Restrict the sandbox’s network and file permissions.
    5. Use creative mode only during development. In production, allow only reviewed plugins to run.

    Plugin Security Governance and Cloud Deployment

    Plugins may come from different sources and require different permissions and resources. Security governance must therefore cover the entire lifecycle, from registration to execution.

    • Source validation and signing: Register only signed plugin packages from trusted sources. The registry should reject a plugin immediately if signature verification fails.
    • Permission allowlists: A plugin’s declared permissions must be included in an allowlist. Network access should be limited to specific domains, and file access should be restricted to designated directories.
    • Sandbox isolation: Run tool plugins and PTC-generated code in separate containers or isolated processes. Limit CPU, memory, and execution time.
    • Secret management: Store secrets in a cloud provider’s secret management service or in environment variables. Grant the minimum required access and rotate secrets regularly. Plaintext secrets must not appear in source code, configuration files, or logs.
    • Audit logging: Record the time of each plugin call, the caller, a summary of the parameters, the return status, and the duration. Sensitive fields must be redacted.
    • Resource limits: Set invocation-rate, concurrency, and token limits for each plugin to prevent one plugin from exhausting shared quotas.
    • Canary releases and rollback: Send a new plugin version to a small portion of traffic first and monitor its error rate and latency. Automatically switch back to the previous working version if metrics deteriorate.
    • Network policies: Allow the runtime framework’s subnet to access only required services. Route outbound traffic through a centralized gateway for auditing and rate limiting.

    For cloud deployments, it is recommended to deploy the runtime framework, plugin registry, and sandbox service separately. Apply independent access controls to the registry and secret management service.

    Collect logs and monitoring data in a centralized system, and retain them according to the organization’s compliance requirements.

    Pre-Launch Checklist

    Confirm each item before deploying to production:

    • Locked dependencies: Pin the versions of all plugin and framework dependencies. Build artifacts must be reproducible.
    • Health checks: Run a health check before mounting each plugin. Reject the plugin if the check fails.
    • Rollback plan: Preserve the previous version before replacing a plugin, and document a rollback drill.
    • Idempotency keys: Require an idempotency key for every write operation and reuse the same key during retries.
    • Timeouts and retries: Configure a timeout for every tool. Use exponential backoff and set a maximum retry count.
    • Permission allowlists: Ensure that plugins have only their declared permissions. Block all undeclared access.
    • No secrets in source code: Scan repositories and container images to verify that they contain no plaintext secrets.
    • Audit logs: Ensure that invocation records are searchable and sensitive fields are redacted.
    • Resource limits: Configure and verify concurrency, invocation-rate, and token limits.
    • Execution mode review: Ensure that creative mode is disabled in production and that PTC sandbox permissions are restricted.

    The value of a plugin-based design is that components can be replaced without modifying the core application. Stable operation, however, depends on whether the implementation details—hot swapping, permission controls, health checks, and rollback—are handled correctly.