Layered Architecture and Engineering Practices for AI Coding Agents
This article breaks down the engineering challenges behind terminal-based AI coding agents, presenting a six-layer architecture, a unified tool contract, an explicit state-machine main loop, context compression strategies, tiered permission models, and boot-time parallelization. It offers practical design patterns that keep model-driven behavior reliable, controllable, and auditable in real-world development workflows.
Why Agent Engineering Matters
Large language models move from pure conversation to task execution when systems must read and write files, run commands, search code, and call external services. The difficulty lies not in a single model call, but in reliably converting model output into controlled operations and maintaining stability across multi-turn, long-running tasks.
This article does not discuss the internals of any specific product. Instead, it abstracts the common engineering problems faced by terminal-based agents and explains widely adopted solutions in the industry.
Layered Architecture: Clear Responsibilities, Replaceable Boundaries
A typical terminal agent can be split into six layers:
- Entry layer: process startup, argument parsing, runtime environment checks.
- Presentation layer: terminal UI rendering, input editing, progress indicators, and action confirmations.
- Core engine layer: session management, prompt assembly, model API invocation, and response parsing.
- Execution layer: tool registration and dispatch, handling concrete actions like command execution, file I/O, and code search.
- Coordination layer: subtask delegation, multi-agent collaboration, and remote session access.
- Management layer: permissions, configuration, state storage, logging, and observability.
The core principle of layering is that upper layers depend only on interfaces exposed by lower layers, and lower layers do not sense the upper layers. For instance, a tool implementation should not care how its result is rendered in the terminal. The benefit is that replacing the UI framework or adding a new tool does not require changing the core engine.
Here is an illustrative tool registration interface, provided only to explain the design:
from typing import Protocolclass Tool(Protocol):name: strdescription: strdef input_schema(self) -> dict: ...def run(self, args: dict, ctx: "ToolContext") -> "ToolResult": ...class ToolRegistry:def __init__(self) -> None:self._tools: dict[str, Tool] = {}def register(self, tool: Tool) -> None:self._tools[tool.name] = tooldef get(self, name: str) -> Tool:if name not in self._tools:raise KeyError(f"Tool not registered: {name}")return self._tools[name]
Tool System: Unified Contract and Plugin-Style Extension
The tool system is the “hands” of the agent. Engineering practice typically requires every tool to satisfy the same contract, including its name, functional description, structured input parameter definitions, required permission level, and an execution function. The model only sees the contract description, never the implementation details.
A unified contract brings three benefits:
- Adding capabilities without modifying the core loop: as long as the contract is implemented and the tool is registered, the model can invoke it.
- Input validation: parameters are validated against the structured definition before entering the execution function, reducing errors from malformed input.
- Declarative permissions: each tool pre-declares a permission level (read, write, execute), which the permission system uses for decision making.
When external tool services are integrated, extra handling is needed for identity authentication, timeout control, and result truncation. External content is untrusted data and should be sanitized like ordinary input, never treated as instructions.
Main Loop: Modeling a Task as a State Machine
The agent’s main loop can be viewed as a finite state machine. A single task typically goes through the following states:
- Receive user input and format it into a model-readable message structure.
- Request a model-generated reply.
- Determine the reply type: plain text ends the turn; a tool call moves to the execution phase.
- Execute the tool and append the result back into the message history.
- Check the budget (turns, token usage, elapsed time) and termination conditions, deciding whether to continue, finish, wait for user confirmation, or exit with an error.
Explicitly listing states helps with debugging. The following code shows a basic state transition skeleton:
from enum import Enum, autoclass State(Enum):AWAITING_MODEL = auto()EXECUTING_TOOLS = auto()AWAITING_CONFIRM = auto()DONE = auto()FAILED = auto()def step(state: State, ctx) -> State:if state is State.AWAITING_MODEL:reply = ctx.model.generate(ctx.messages)if reply.tool_calls:ctx.pending = reply.tool_callsreturn State.EXECUTING_TOOLSreturn State.DONEif state is State.EXECUTING_TOOLS:if ctx.budget_exhausted():return State.FAILEDctx.run_tools(ctx.pending)return State.AWAITING_MODELreturn state
An explicit state machine also makes it easy to insert human-in-the-loop nodes like “wait for confirmation” and to recover or roll back from a failure in any state.
Context Management: Compression and Long-Term Memory Separation
The model’s context window is limited, while coding tasks often produce large volumes of file content and command output. Without management, the history quickly exceeds the limit or critical information is buried in noise.
Two common approaches exist:
- Session compression: when token usage approaches a threshold, summarize the historical messages. The summary should retain the user’s goal, key decisions already made, unfinished items, and relevant file paths, while discarding verbose raw tool output.
- External long-term memory: information that must survive across sessions (e.g., project conventions, coding standards, build commands) should be written into documentation files in the project directory and read at the start of each session, rather than relying on conversation history.
A simplified compression trigger strategy:
def maybe_compact(messages, max_tokens: int, ratio: float = 0.8):used = count_tokens(messages)if used < max_tokens * ratio:return messagessummary = summarize(messages[:-6]) # keep the most recent messages as raw textreturn [summary, *messages[-6:]]
Compression loses detail, so retaining the raw text of the most recent few turns is an important trade-off.
Permissions and Safety: Layered Decisions, Default Deny
Because agents can execute real actions, permission design is a security baseline. Mature systems typically make decisions at three layers simultaneously:
- Tool layer: whether the tool is allowed in the current session.
- Rule layer: whether specific parameters comply with rules, such as whether a path is inside the workspace or a command matches an allowed list.
- Mode layer: the current operating mode defines default behavior, such as read-only mode, confirm-before-every-operation mode, or auto-execution mode.
The following principles should be followed:
- Default deny: operations not explicitly authorized are never executed.
- Delete, overwrite, network send, and similar operations require explicit confirmation.
- Run commands in restricted environments where possible, limiting accessible paths and network.
- Credentials must never enter prompts or logs.
A simplified rule-layer example:
from pathlib import Pathdef check_write_path(target: str, workspace: str) -> bool:root = Path(workspace).resolve()dest = (root / target).resolve()return dest.is_relative_to(root) # prevent path traversal outside the workspace
Startup Performance: Parallelism and Latency Hiding
When an agent starts, it typically reads configuration, validates credentials, establishes network connections, loads feature flags, and connects to external services. If done sequentially, users notice obvious waiting. Common optimizations include:
- Parallel prefetch: during the module loading phase, launch credential reads and network preconnections concurrently, overlapping wait time with import time.
- Render first, complete later: render the UI immediately and let non-critical initialization finish in the background.
- Lazy loading: feature flags, remote services, and other non-essential components load after the first screen.
import asyncioasync def boot():keychain, conn, flags = await asyncio.gather(load_credentials(),warm_up_connection(),fetch_feature_flags(),)render_ui()await connect_optional_services(keychain)
Note that parallel initialization requires independent tasks. If dependencies exist, arrange them in dependency order and design degradation paths for failed tasks.
Practical Recommendations
To build your own agent or tool-oriented system based on these ideas, follow this sequence:
- Define a unified tool contract and permission model before implementing specific tools.
- Organize the main loop with an explicit state machine, setting timeouts and budgets for each state.
- Establish context compression and project documentation mechanisms early to avoid rework.
- Log and audit all write operations and command executions.
- Measure startup time to evaluate parallel optimization results, rather than relying on intuition.
The essence of agent engineering is confining model uncertainty within controllable boundaries. Layering, contracts, state machines, tiered permissions, and observability are the common tools that achieve this goal.
