Beyond System Prompts: Engineering the Architecture of AI Coding Agents
System prompts and tool lists only scratch the surface of an AI coding agent. A reliable product depends on the underlying engineering across five layers—interaction, orchestration, capability, governance, and infrastructure. This article breaks down these layers, covering command registries, tool-call governance pipelines, context management, memory systems, multi-agent task scheduling, and safe extension mechanisms. It also provides a practical checklist for evaluating agent products based on system design rather than marketing claims.
Why System Prompts and Tool Lists Are Not Enough
When analyzing an AI agent product, the two most visible elements are the system prompt and the list of callable tools. While important, these represent only the surface layer of the product.
Two teams working from the same prompt—even with identical tool functions—can still deliver vastly different experiences. The gap typically comes from the underlying mechanics:
- Orchestration Logic: How prompts are assembled, when context is trimmed, and how history is retained.
- Governance Pipelines: The validation, approval, logging, and interception steps surrounding each tool call.
- Task Division & Scheduling: How complex work is decomposed, who executes subtasks, and how status is synchronized.
- Capability Awareness: How the model knows what tools exist and how new capabilities are introduced safely.
User-visible stability is the combined result of these mechanisms. No single sentence in a prompt can explain that level of reliability.
The Five-Layer Architecture of an Agent System
A mature agent system can be understood as five distinct layers:
- Interaction Layer: Handles entry points like terminals, graphical interfaces, APIs, and service endpoints.
- Orchestration Layer: Assembles prompts, manages session state, and decides what to invoke next.
- Capability Layer: Includes tool definitions, commands, skills, and plugins—the space in which the model can act.
- Governance Layer: Enforces permission checks, parameter validation, sandbox isolation, and audit trails for tool use.
- Infrastructure Layer: Provides configuration loading, persistent storage, logging, monitoring, and background tasks.
The clearer the boundaries between these layers, the easier the system is to maintain. Conversely, mixing responsibilities across layers means a simple prompt change can cause unexpected tool behavior.
Interaction Layer: One Runtime, Multiple Entry Points
A mature agent product rarely has a single usage mode. Common entry points include:
- Command-line interaction for developers working in a local repository.
- Setup and configuration flows for first-time initialization and environment checks.
- Protocol-based service modes that allow other programs to connect as clients.
- Software development kits (SDKs) for third-party applications embedding agent capabilities.
All of these entry points should share a single core runtime. The core handles session management, tool calls, and state maintenance; entry points only manage the form of input and output. This approach ensures that fixing a core logic bug immediately benefits every interface. If each entry point implements its own logic, behavioral inconsistencies are inevitable.
Here is a simplified structural example:
class AgentRuntime:"""Core runtime shared by all entry points"""def __init__(self, config, tools, policy, session_store):self.config = configself.tools = toolsself.policy = policyself.sessions = session_storedef handle_turn(self, session_id, user_input):session = self.sessions.load(session_id)return self._run_loop(session, user_input)# Different frontends are just wrappers around the same runtimeclass TerminalFrontend:def __init__(self, runtime):self.runtime = runtimeclass ServiceFrontend:def __init__(self, runtime):self.runtime = runtime
Command System: The Gateway to the Ecosystem
The command system is often viewed as a collection of shortcuts, but in a production-grade product it carries far more weight. It must uniformly manage commands from multiple sources:
- Built-in commands for checking status, modifying permissions, managing memory, and listing tasks.
- Plugin-provided commands registered by third-party extensions.
- Skill-provided commands registered by reusable capability packages.
- Dynamically loaded commands that appear based on context, such as project type.
The purpose of unified loading is consistency: regardless of the source, users see the same list format, and permission rules and conflict-handling logic are applied uniformly. The registry also needs to handle naming collisions, version compatibility, and disabled states.
class CommandRegistry:def __init__(self):self._commands = {}def register(self, command, source):if command.name in self._commands:existing = self._commands[command.name]raise ValueError(f"Command {command.name} is already registered by {existing.source}, "f"conflicting with {source}")self._commands[command.name] = command.with_source(source)def list_available(self, user_context):return [c for c in self._commands.values()if c.enabled and c.visible_to(user_context)]
The Governance Pipeline for Tool Calls
Tool invocation is the most failure-prone aspect of an agent. The model may generate invalid arguments, attempt to access unauthorized resources, or execute write operations at inappropriate times. Therefore, every tool call should go through a fixed pipeline rather than being executed directly.
A typical pipeline includes these stages:
- Resolution: Confirm the tool exists and is permitted in the current session.
- Validation: Check argument types, ranges, and required fields against the schema.
- Pre-hooks: Run user- or admin-configured check logic that can reject the call.
- Permission Decision: Determine whether to allow, deny, or ask the user based on the current permission mode.
- Execution: Run the tool in a sandboxed or restricted environment.
- Auditing: Record call parameters, result summaries, and duration for review and debugging.
- Result Processing: Truncate or summarize overly long output to avoid consuming context.
def run_tool(call, ctx):tool = ctx.registry.get(call.name)if tool is None or not ctx.session.allows(tool):return error("Tool does not exist or is not permitted in this session")args = tool.schema.validate(call.arguments)for hook in ctx.hooks.before_tool:decision = hook(tool, args, ctx)if decision.denied:return error(decision.reason)verdict = ctx.policy.check(tool, args, ctx.permission_mode)if verdict == "ask":verdict = ctx.ui.request_approval(tool, args)if verdict != "allow":return error("Call not authorized")result = ctx.sandbox.execute(tool, args)ctx.audit.record(tool.name, args, result.summary, result.duration)return truncate(result.output, limit=ctx.budget.tool_output)
This code is a generic structural illustration. The key insight is the ordering: validation before permission checks, auditing after execution, and output truncation before returning to the model. A misordered pipeline can create security or stability holes. For example, unvalidated arguments flowing directly into a permission check can break matching rules.
Permission mode design also deserves attention. Common patterns distinguish several modes: read-only mode, per-call confirmation mode, auto-allow for specific tools, and full-allow within controlled environments. Mode switches themselves should be logged as significant events.
Prompt Assembly and Context Orchestration
The system prompt is rarely a single fixed block of text. It is typically composed from multiple sources:
- Base behavior guidelines describing the agent’s role, boundaries, and output formatting.
- Runtime environment information such as OS, working directory, and current time.
- Project documentation files provided by the user in the repository.
- User preference settings like language, output length, and code style.
- Runtime state such as current task progress and a summary of available tools.
Static and dynamic parts should be distinguished during assembly. Stable portions change rarely, benefit from caching, and reduce per-turn processing costs. Dynamic portions vary with the conversation and should be placed last to preserve cache hits.
As conversations lengthen, context windows fill up. Common strategies include:
- Hierarchical retention: Recent turns are kept in full; older turns are compressed into summaries.
- Fixed key constraints: Explicit user requirements, prohibitions, and project conventions are excluded from compression and always remain in context.
- Tool output trimming: Long logs and large file contents are reduced to key excerpts with a note about the omitted portion.
- Externalized state: Task progress is stored outside the context window and read back on demand, rather than occupying space continuously.
Poor context compression manifests most directly as the model “forgetting” prior agreements. Compression strategies therefore need dedicated testing and cannot be validated by smooth single-turn responses alone.
Memory and State Management
A memory system solves cross-session information retention. It is distinct from the context window, which only exists within the current conversation—memory must be persistent.
Designing a memory system requires answering several questions:
- What to write: User preferences, project conventions, and confirmed facts are suitable. Temporary debugging details typically are not.
- When to read: Memory can be loaded entirely at session start, or retrieved by topic and loaded on demand.
- How to update: Outdated memories need correction or deletion, otherwise the system acts on stale information.
- How to isolate: Memories from different projects and different users must be stored separately to prevent cross-contamination.
State initialization is equally important. A robust system should perform configuration validation, dependency checks, and state recovery at startup. If initialization fails, the system should report the cause clearly instead of continuing with incomplete state.
Multi-Agent Division of Labor and Task Scheduling
Complex tasks often require decomposition. A common structure uses a coordinator to understand the goal, break down the work, and dispatch subtasks to specialized executors.
Key design points for division of labor:
- Context isolation: Subtasks receive only the information needed to complete their work—not the coordinator’s entire history.
- Scoped tools: Subtasks can only use tools relevant to their responsibility, limiting the blast radius of mistakes.
- Result summaries: Subtasks return structured summaries to the coordinator, not full execution traces.
- Visible state: Each task has an explicit state—pending, running, done, failed—so users can monitor progress.
from dataclasses import dataclassfrom enum import Enumclass TaskState(Enum):PENDING = "pending"RUNNING = "running"DONE = "done"FAILED = "failed"@dataclassclass SubTask:id: strgoal: strallowed_tools: liststate: TaskState = TaskState.PENDINGsummary: str = ""def dispatch(orchestrator, subtasks, max_parallel=3):running = []for task in subtasks:if len(running) >= max_parallel:orchestrator.wait_any(running)task.state = TaskState.RUNNINGrunning.append(orchestrator.spawn(task))return orchestrator.collect(running)
Parallel execution reduces total time but introduces conflicts. Two subtasks modifying the same file concurrently produce unpredictable results. The scheduler must therefore detect resource conflicts and serialize tasks that have dependencies.
Extension Mechanisms: Letting the Model Know What It Can Do
Agent ecosystems typically extend through plugins and skills. A frequently overlooked problem is that the model needs to know what capabilities exist, but should not receive every detail in the context at once.
Progressive disclosure is the better approach:
- Load only names and short descriptions of each capability at startup.
- Load the full specification and argument definitions only when the model determines a capability is needed.
- Return only a brief summary of execution results to the main session.
Extension metadata typically includes name, version, description, required permissions, dependencies, and entry point definitions. The loader should validate this information before registration—for instance, checking version compatibility and whether the declared permission scope matches actual behavior.
For security, third-party extensions should be restricted by default. Permissions must be explicitly declared and confirmed by the user. A failing extension should not crash the entire system; the loader needs to isolate exceptions and provide clear error reporting.
A Checklist for Evaluating Agent Products
With the framework above, a set of questions can be used to evaluate any agent product:
- Entry-point consistency: Do different interfaces behave consistently? Do they share the same core logic?
- Tool governance: Are tool calls protected by parameter validation, permission controls, and audit logging? Can users see what the model did?
- Context management: After long conversations, does the model still remember key constraints? Is the compression strategy explainable?
- Division and scheduling: Can complex tasks be decomposed? Are subtask permissions restricted? Are results traceable?
- Extension mechanism: Is there a review process for adding new capabilities? Are third-party permissions controllable?
- Failure handling: When tools fail, network errors occur, or context overflows, does the system give clear feedback instead of failing silently?
These questions do not depend on a specific brand or version. They focus on system design itself, making them applicable to evaluating comparable products and useful for the architecture planning of in-house agent projects.
Summary
The quality of an agent product depends on substantial engineering work beyond the prompt. Orchestration determines what the model sees at each step, governance determines what the model can do and what checks precede action, division of labor determines whether complex tasks complete reliably, and extension mechanisms determine how the capability boundary grows over time.
If you are designing or evaluating an agent system, start by drawing its five-layer structure and then check each layer for clear responsibilities and well-defined boundaries. This process usually brings more stability improvements than repeatedly tuning the prompt.
