Coding Agent Framework Architecture and Engineering Implementation Guide

    This article explains how to design and deploy a coding agent framework for multi-step coding tasks. It covers plugin-based responsibility boundaries, containerized runtime deployment, custom plugin development, session management, and permission controls, with practical checklists and code examples.

    A coding agent framework aims to enable large language models to complete multi-step coding tasks, such as reading code, modifying files, running tests, and reporting results. A typical framework consists of a scheduler, plugins, session management, and a memory module. The following sections describe what each part should do and what to check, from design to implementation.

    1. Plugin Architecture: How to Divide Responsibilities

    “Everything is a plugin” is a common design approach. Model inference, code execution, file read/write, and external interface calls are encapsulated as plugins. The core scheduler is only responsible for dispatching requests, managing plugin lifecycles, and passing messages.

    This division has three direct benefits:

    • Adding a new capability only requires implementing the plugin interface; the scheduler does not need to be modified.
    • Plugins can be tested and replaced independently.
    • Permissions can be set per plugin, and high-risk capabilities can be tightened separately.

    The cost is that as the number of plugins increases, interface version management and dependency conflicts become more complex. Each plugin should declare its version number, required permissions, and input/output structures.

    The term “spatiotemporal composability” mentioned in some documents lacks a widely accepted definition and source, so this article does not use it as a design basis. The concurrency-related mechanisms that can be verified are asynchronous event-driven design, resource pooling, and task timeout control. How many sessions the system can handle concurrently depends on the model service rate limits, the code sandbox pool size, and the duration of a single task. These must be determined through stress testing and cannot be directly copied from a specific number.

    2. How to Deploy the Coding Agent Runtime

    Conclusion: Use containers to pin dependency versions, place code execution in an isolated environment, and run as a non-root user.

    Before deployment, confirm the following:

    • The Python version and all dependency versions are written to requirements.txt with exact version pins.
    • The model service address and key are injected through environment variables, such as MODEL_API_BASE and MODEL_API_KEY, and are not written into the image or code.
    • The code directory is mounted read-only, and the agent’s writable directory is mounted separately as a workspace.
    • The scheduler service and the code execution sandbox are deployed separately, each using its own container.
    • Set CPU and memory limits and a per-execution timeout for each container.

    Example Dockerfile:

    1. FROM python:3.11-slim
    2. RUN useradd --create-home agent
    3. WORKDIR /app
    4. COPY requirements.txt .
    5. RUN pip install --no-cache-dir -r requirements.txt
    6. COPY . .
    7. USER agent
    8. ENV WORKSPACE_ROOT=/workspace
    9. CMD ["python", "-m", "agent.server"]

    When using Kubernetes, you can configure autoscaling based on CPU usage or the number of queued sessions. Queued sessions reflect agent load better than CPU because the agent spends most of its time waiting for model responses.

    3. How to Develop Custom Plugins

    Plugins should implement a unified interface: provide name and version fields, implement the execute(params, context) method, and return a fixed result structure. The result contains four fields: status, data, error_code, and message. Callers use error_code to determine the failure reason and do not parse natural-language messages.

    The following file-write plugin restricts the write scope and rejects out-of-bounds paths. In production, do not call open on arbitrary paths directly.

    1. import os
    2. from pathlib import Path
    3. class FileWritePlugin:
    4. name = "file_write"
    5. version = "1.0.0"
    6. MAX_BYTES = 1024 * 1024 # Maximum size per write: 1 MB
    7. def __init__(self, config):
    8. # Writable root directory; resolved to an absolute path during initialization
    9. self.allowed_root = Path(config["allowed_root"]).resolve()
    10. self.allowed_extensions = set(
    11. config.get("allowed_extensions", [".py", ".md", ".txt"])
    12. )
    13. def _resolve_safe_path(self, raw_path):
    14. # resolve() expands ../ and symbolic links, so the check uses the real path
    15. target = (self.allowed_root / raw_path).resolve()
    16. if os.path.commonpath([str(self.allowed_root), str(target)]) != str(self.allowed_root):
    17. raise PermissionError("path outside allowed root")
    18. if target.suffix not in self.allowed_extensions:
    19. raise PermissionError("file extension not allowed")
    20. return target
    21. def execute(self, params, context=None):
    22. try:
    23. raw_path = params["path"]
    24. content = params["content"]
    25. if not isinstance(content, str):
    26. return self._error("invalid_type", "content must be a string")
    27. data = content.encode("utf-8")
    28. if len(data) > self.MAX_BYTES:
    29. return self._error("too_large", "content exceeds 1 MB limit")
    30. target = self._resolve_safe_path(raw_path)
    31. target.parent.mkdir(parents=True, exist_ok=True)
    32. with open(target, "wb") as f:
    33. f.write(data)
    34. return {"status": "success", "data": {"path": str(target)},
    35. "error_code": None, "message": "written"}
    36. except PermissionError as e:
    37. return self._error("permission_denied", str(e))
    38. except KeyError as e:
    39. return self._error("missing_param", f"missing parameter: {e}")
    40. except OSError as e:
    41. return self._error("io_error", str(e))
    42. def _error(self, code, message):
    43. return {"status": "error", "data": None, "error_code": code, "message": message}

    This code still has two caveats:

    • The write mode overwrites, so existing file content is lost. If existing content needs protection, back up the original file first or use append mode.
    • There is a race window between path checking and writing. If an attacker can replace a directory during that window, the check may become ineffective. Therefore, the container’s mount scope should still serve as a second line of defense.

    When developing a plugin, confirm the following one by one: field types of input parameters, output structure, timeout, required permissions, and whether repeated calls are safe (idempotency).

    4. How to Manage Sessions and Control Permissions

    A session record should contain at least the following fields:

    • session_id and user_id: identify the session and the initiator.
    • status: one of pending, running, waiting_user, done, or failed.
    • task_id: the associated task.
    • history: instructions and results for the latest N turns; content beyond that is compressed into a summary.
    • env: only whitelisted environment variables are stored.
    • created_at, updated_at, expires_at: used for auditing and cleaning up expired sessions.

    Permission control uses a default-deny principle: any operation that is not explicitly allowed is denied. Specific practices are as follows:

    • Command whitelist: only pre-listed command prefixes are allowed.
    • Network access: disabled by default; when needed, enable it per domain.
    • Delete and overwrite operations: require human confirmation and generate a snapshot before execution.
    • Audit logs: record time, session ID, plugin name, parameter summary, result, and duration. The log retention period must be determined in advance.

    The following command whitelist example only allows commands in the whitelist and does not go through shell parsing:

    1. ALLOWED_PREFIXES = [
    2. ("pytest",),
    3. ("python", "-m", "pytest"),
    4. ("git", "status"),
    5. ("git", "diff"),
    6. ]

    A command execution helper such as run_command(argv, timeout=60) should accept an argument list, validate that every element is a string, avoid shell parsing, and enforce the timeout. It should return a structured error when validation fails.