Plugin-Based AI Coding Agents: Module Contracts and Security Practices

    This article explains how to design plugin-based AI coding agents around clear module contracts, covering the five core modules, hot-swap mechanics, and layered security controls. It includes adapter interfaces, tool registration, session logging, agent-loop boundaries, configuration assembly, and a selection checklist for teams deciding whether to build or adopt a runtime.

    AI coding agents have moved beyond single-turn code completion into workflow systems that can read and write files, run commands, execute tests, and iterate based on results. Such a system typically contains five modules: a model adapter, a tool registry, a session log, an agent loop, and an interaction layer.

    These modules change at different speeds. Model services might update interfaces every few months; tool protocols and security policies are more stable; team workflows and UI preferences vary. If all five are written in one program, switching models requires changing loop logic, and custom tools from one team are hard to reuse.

    Pluginization means each module communicates only through an agreed interface and does not directly reference another module’s implementation. There are three direct benefits:

    • Low replacement cost: changing a model or UI requires a config change or a new plugin.
    • Clear boundaries: adding a tool does not require modifying the loop control logic.
    • Parallel development: teams can build and publish plugins independently as long as they follow the same interface version.

    Pluginization also has costs. Interface design requires upfront investment, and cross-plugin version compatibility needs ongoing maintenance. For very small systems, a monolithic implementation may be simpler.

    1. Five module contracts and lifecycle

    Module Responsibility Input Output Contract essentials
    Model adapter Hides differences between model services Conversation messages, tool declarations Unified reply or streaming events Declare capabilities, normalize error types
    Tool registry Registers tools and dispatches execution Tool invocation requests from the model Structured execution results Validate parameters, check permissions
    Session log Records each turn’s events Events emitted by modules Append-only log file Redact before write, append-only
    Agent loop Controls reasoning and tool execution turns User task, model replies Continue-or-stop decision Set turn limits and stopping conditions
    Interaction layer Renders events and collects user confirmation Event stream Terminal/UI output, confirmation results Render only, no business logic

    1.1 Model adapter

    An adapter interface might look like this:

    1. from typing import Protocol, Iterator
    2. class ModelAdapter(Protocol):
    3. name: str
    4. max_context_tokens: int
    5. supports_streaming: bool
    6. supports_tools: bool
    7. def complete(self, request: "ChatRequest") -> "ChatResponse": ...
    8. def stream(self, request: "ChatRequest") -> Iterator["ChunkEvent"]: ...

    To integrate a new model, you only implement this interface. The agent loop does not need to change.

    In practice, three concerns need to be handled. First, message format conversion: different services have different requirements for system prompts and tool results, and the adapter is responsible for converting them. Second, timeout and retry: a single request timeout can be set to 60 seconds, with at most 3 retries and backoff intervals of 1, 2, and 4 seconds plus random jitter, capped at 30 seconds. Retry only on 429, 5xx, and network timeout; fail immediately on 400, 401, and 403. Third, error normalization: service-specific error codes should be mapped to unified types.

    Upstream error Unified type Retry?
    429 RateLimitError Yes
    5xx UpstreamUnavailable Yes
    Network timeout TimeoutError Yes
    Context too long ContextLimitError No, truncate history
    401 / 403 AuthError No, prompt to check key

    Error logs must not contain API keys, Authorization headers, or full request bodies.

    1.2 Tool registry

    Each tool should register the following fields:

    • name: globally unique tool name
    • description: functional description used by the model to select the tool
    • parameters: JSON Schema used at runtime to validate arguments
    • risk_level: one of read, write, exec, network
    • requires_confirmation: whether human confirmation is needed
    • timeout_seconds: execution timeout
    • max_output_chars: output character limit
    • plugin_id: owning plugin identifier

    Example tool definition:

    1. {
    2. "name": "read_file",
    3. "description": "Read the text content of a specified file in the project",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "path": {"type": "string", "description": "Path relative to the project root"},
    8. "max_lines": {"type": "integer", "minimum": 1, "maximum": 2000}
    9. },
    10. "required": ["path"],
    11. "additionalProperties": false
    12. },
    13. "risk_level": "read",
    14. "requires_confirmation": false,
    15. "timeout_seconds": 5,
    16. "max_output_chars": 8000
    17. }

    The dispatch order is: model emits a tool call request, registry validates parameters, checks permissions, decides whether confirmation is required, executes in a sandbox, truncates output, redacts sensitive data, writes results back to context, and finally appends an audit record.

    Output truncation is often overlooked. Tool output can be tens of thousands of characters; writing it directly back to context consumes space needed for subsequent reasoning. A common approach is to keep the first 4,000 characters and the last 2,000 characters, insert a marker showing the original length, and store the full output in a separate file. The context then contains only the file path and a summary.

    1.3 Session log

    Session logs use append-only JSONL with one event per line. Recommended fields include timestamp ts, session_id, turn_id, event_type, tool, status, and duration_ms.

    Logs must be redacted before writing. If redaction fails, the write should be rejected—fail closed rather than writing unredacted content.

    1.4 Agent loop

    The loop controller is a simple state machine: wait for a user task, request the model, execute tools, and decide whether to continue. It should not contain logic for any specific tool.

    Suggested stopping conditions include: no tool call in the model reply; reaching a turn limit such as 30; user interruption; or the same error occurring three consecutive times. The loop checks these conditions at the end of each turn. Model adapters and plugins may be replaced only between turns, never in the middle of a reasoning turn.

    1.5 Interaction layer

    The interaction layer renders events and surfaces actions that require human confirmation. It subscribes to the event stream and does not call models or tools directly. Terminal interfaces, IDE plugins, and web UIs can share the same event protocol and only replace the interaction layer itself.

    2. Configuration assembly and plugin example

    A config file can declare which plugin each module uses:

    1. runtime:
    2. session_log_dir: ./.agent/logs
    3. max_turns: 30
    4. model:
    5. plugin: openai_compatible
    6. base_url: ${MODEL_BASE_URL}
    7. api_key_env: MODEL_API_KEY
    8. timeout_seconds: 60
    9. max_retries: 3
    10. tools:
    11. - plugin: fs_tools
    12. allow_paths: ["./src", "./tests"]
    13. - plugin: shell_tools
    14. sandbox: container
    15. allowlist: ["pytest", "npm test"]
    16. require_confirm: true
    17. ui:
    18. plugin: terminal

    Secrets are injected only through environment variables; the config file stores only the variable name.

    Each plugin carries a manifest that declares its ID, version, API version, entry point, and required permissions:

    1. id: shell_tools
    2. version: 1.2.0
    3. api_version: "1"
    4. entry: shell_tools.plugin:register
    5. permissions:
    6. - fs.read:./src
    7. - exec.run:allowlist

    The plugin entry function registers tools with the registry:

    1. def register(registry):
    2. registry.add_tool(
    3. name="run_tests",
    4. description="Run project test commands in a sandbox",
    5. parameters=RUN_TESTS_SCHEMA,
    6. risk_level="exec",
    7. requires_confirmation=True,
    8. timeout_seconds=120,
    9. max_output_chars=8000,
    10. handler=run_tests_handler,
    11. )

    At startup, the loader checks each plugin’s api_version against the runtime. Incompatible plugins are rejected with a clear error.

    Hot-swap procedure

    Hot swapping should follow this order:

    1. Check the new plugin’s manifest and api_version.
    2. Load it in an isolated temporary environment and run the plugin’s self-tests.
    3. After self-tests pass, atomically switch the registry to the new version.
    4. Before unloading the old version, wait for in-flight calls to finish; cancel them if they exceed the timeout.
    5. If an exception occurs after the switch, restore the old version directory and point the config back to the old version number.

    Rollback depends on two prerequisites: keep the old version directory until the new version has run stably for a while, and pin plugin versions in config instead of using “latest”.

    3. Security controls

    Security controls should be implemented layer by layer in the tool dispatch flow.

    1. Permission checks: assign capabilities on a least-privilege basis. File tools can access only whitelisted paths. Before access, resolve the real path and reject requests that escape the project directory through symlinks or “../“.
    2. Human confirmation: for tools with risk_level write, exec, or network, show the exact operation before execution. For file writes, show a diff; for commands, show the full command line. Continue only after user confirmation.
    3. Command sandboxing: run commands in a container or restricted process, use a non-root user, mount directories outside the project read-only or not at all, disable network access by default, set CPU, memory, and time limits, and keep only allowlisted environment variables.
    4. Log redaction: before writing logs or returning content to the model, match common secret patterns, Authorization headers, and .env file contents, and replace them with fixed placeholders.
    5. Audit records: every tool invocation should record the requester, time, parameter summary, decision result, and execution status. Audit records should be stored separately from session logs and have restricted read/write permissions.

    The failure-handling principle is: do not terminate the whole loop because one tool failed; return structured errors to the model.

    • Permission denied: return permission_denied with the rejected path or command category.
    • Sandbox timeout: terminate the entire process group and return timeout.
    • User denies confirmation: return user_denied; the model can propose a different approach.
    • Redaction failure: refuse to write that log entry and record an error event without the original content.

    4. Selection checklist and conclusion

    To decide whether to build a runtime framework in-house, compare boundary control, maintenance cost, ecosystem, and migration risk. Self-building suits teams that need strict permission models, audit formats, or deep integration with internal systems. Adopting an existing framework suits rapid validation, but you need to confirm that the plugin interface is stable and that unwanted auto-execution capabilities can be disabled.

    Use the following checklist for selection:

    Dimension Check item
    Compatibility Is the plugin interface versioned? Can it connect to target model services? Is the config format readable and version-controllable?
    Observability Are structured events emitted? Can logs be searched by session and turn? Are duration and error types measurable?
    Security Are path whitelists and human confirmation supported? Can commands run in a container or restricted process? Is log redaction configurable?
    Maintenance As plugin count grows, is there a defined upgrade and rollback process? Can teams maintain plugins independently?
    Rollback Can plugin versions be pinned? Can the old version be restored if switching fails?

    Regardless of the chosen approach, complete three verifications before launch: use a fixed task set to check tool invocation and truncation logic; use unauthorized paths and dangerous commands to test permission checks and sandboxing; use outputs containing secret-like strings to test log redaction.

    The value of pluginization is separating fast-changing parts from slow-changing parts. When module contracts are clear, components can be replaced independently; when permission checks, confirmation, and redaction are built into the dispatch flow, teams can safely introduce third-party plugins.