Understanding AI Coding Agent Architecture: Six Core Modules
This article breaks down the architecture of an AI coding agent through a minimal, standard-library-only implementation that exposes six core modules. It explains why the same foundation model performs very differently inside a mature agent harness than in a plain chat interface, and how context management, tool design, prompt-cache stability, memory, session continuity, and termination control work together. By tracing a real task such as fixing a failing unit test, it shows how these modules fit into a single observable, resumable, and budget-bounded loop, along with common pitfalls and practical engineering recommendations.
1. Why the Same Model Behaves Very Differently Inside Different “Shells”
In real engineering work, one frequently underestimated fact is that the runtime system built around a model—tool-set design, context organization, and memory and state management—can affect the final result as much as the model itself. This explains a common observation: the same generation of foundation model, once wrapped in a mature coding tool, performs noticeably better in a real repository than when code is pasted turn by turn into an ordinary chat interface.
The reason is not mysterious. A chat interface only provides the minimal loop of “one question, one answer,” while coding tasks are inherently long-horizon, multi-step, and strongly dependent on external state: reading files repeatedly, searching for symbols, running tests, and backing out based on errors. What carries these behaviors is not the model weights but the control program wrapped around the model. The industry usually calls this layer the Agent Harness.
It helps to clarify three distinct layers first, so that the discussion does not conflate different objects:
- Foundation language model: the core next-token prediction engine that determines “intuition for language and code.”
- Reasoning-enhanced model: still a language model, but through training or prompting strategies it spends more compute during reasoning, verification, and candidate search, trading higher cost for stronger complex problem-solving ability.
- Agent Harness: the control loop at the very top, which decides what to look at next, which tool to call, how to update state, and when to stop.
A memorable analogy is this: the model is the engine, a reasoning-enhanced model is a stronger but more fuel-hungry engine, and the harness is the transmission and drivetrain—it determines whether the engine’s power can be converted efficiently into actual movement. The analogy is not rigorous (a model can also be used on its own without a harness), but it is enough to convey the core argument of this article: a coding agent’s capability is the product of the model and the harness, not either one alone.
2. Overall Shape: A Reproducible Minimal Coding Agent
To explain the architecture clearly, the following constructs a minimal implementation that depends only on the language standard library (hereafter called the Mini Coding Agent). It does not aim for complete functionality; instead, it explicitly exposes the six modules so that each can be swapped and observed layer by layer.
The whole thing is a while loop in which each round completes “observe → inspect → decide → execute”:
# Illustrative skeleton, omitting exception handling and rate-limiting detailsdef run(task: str, max_steps: int = 40):state = State(task=task) # Module 5: session state and continuityfor step in range(max_steps):prompt = build_prompt(state) # Module 1: context managementreply = llm(prompt) # stable prefix, cache hit (Module 3)action = parse_action(reply) # protocol parsing; on failure, re-inject the errorif action.kind == "finish":return stateobservation = dispatch(action) # Module 2: tool invocationstate.append(action, observation) # Module 4: memory write and compressionreturn state
This skeleton is only about twenty lines, yet it already contains all the key design points. Each subsequent section corresponds to one module.
3. Module 1: Context Management—Deciding What the Model “Sees”
The context window is a scarce resource, and the management strategy directly determines success or failure. In practice, the context is usually split into four parts:
- Stable prefix: system instructions, tool list, coding conventions, and a directory-structure summary. This part should change as little as possible, so that it works with caching and reduces attention dilution.
- Task area: the user’s goal, acceptance criteria, and constraints.
- Working memory: the most recent several rounds of actions and observations, keeping the original details.
- Archive area: structured summaries of earlier history, expanded on demand.
The key principle is “load on demand rather than inject everything.” For example, facing a medium-sized repository, you should not stuff all files into the prompt; instead, first provide the directory tree and key entry files, and let the model actively start searches. Illustration:
def build_prompt(state):return "\n".join([SYSTEM_PREAMBLE, # stablestate.task_block(), # task and acceptance criteriastate.recent(8), # recent raw textstate.archive_summary(), # earlier summarystate.tool_schema(), # tool signatures])
4. Module 2: Tool Design—Turning “Capability Boundaries” into Callable Interfaces
Tools are the agent’s hands and feet. Design quality shows in three points: moderate granularity, parseable returns, and readable errors.
- Granularity: too coarse (such as “fix this bug”) cannot be executed; too fine (such as editing character by character) exhausts the step count. A reasonable granularity is “read a file fragment, replace by line range, regex search, run tests, list directories.”
- Parseable returns: unify everything into structured results containing status, body, and optional location information, so the model can precisely reference them in the next step.
- Readable errors: on failure, return a human-readable reason and suggestion rather than throwing a stack trace. Models are very good at self-correcting based on clear errors.
TOOLS = {"read_file": {"args": ["path", "start", "end"]},"search": {"args": ["pattern", "glob"]},"edit_lines": {"args": ["path", "start", "end", "new"]},"run_tests": {"args": ["target"]},}def dispatch(a):try:return ok(TOOLS[a.name](**a.args))except Exception as e:return err(f"{a.name} failed: {e}; check the arguments or use search to locate the target")
An often-overlooked practice: force a read before any write, attach line numbers to the content read, and anchor edits to line ranges. This can significantly reduce the probability of “editing the wrong place.”
5. Module 3: Prompt Cache Stability—An Underestimated Cost and Latency Lever
Most model services provide a prefix-caching mechanism: when the request prefix is exactly identical, the computation result can be reused, lowering latency and cost. To take advantage of this, the prefix must be byte-for-byte stable:
- Move volatile content (timestamps, random IDs, live counters) out of the prefix and place it at the end of the prompt;
- Keep the ordering of the tool list and system instructions fixed, without dynamic reordering;
- For archive-summary updates, “append a new block” rather than “rewrite the old block.”
In engineering practice, a simple check can guard this:
def assert_stable(prefix: str, snapshot: dict):h = hashlib.sha256(prefix.encode()).hexdigest()if snapshot.get("h") and snapshot["h"] != h:raise RuntimeError("The stable prefix was modified; the cache will be invalidated")snapshot["h"] = h
6. Module 4 and Module 5: Memory and Session Continuity
Memory has two layers: short-term is the raw trajectory, and long-term is structured conclusions. When the trajectory becomes too long, run compression: keep the task goal, confirmed facts, paths that have failed, and hypotheses pending verification, and discard verbose raw text.
def compress(state):state.archive = summarize([s for s in state.steps[:-8]if s.kind in ("edit", "test")])
Session continuity, in turn, requires state to be serializable and recoverable: write the task, step count, list of files read, and failure records into a local log or external storage (such as object storage or a message queue), so that after a process interruption it can resume from the most recent checkpoint. This step is the watershed from a “toy script” to a “usable tool.”
7. Module 6: Termination and Budget Control
A loop without a termination condition equals risk. Set at least four kinds of gates: maximum steps, maximum token budget, per-command timeout, and repeated-action detection. At the same time, define a clear success criterion (such as all tests green) and a graceful exit path (on timeout, output current progress and unfinished items), to avoid “endlessly fixing the same place.”
8. Wiring the Six Modules Together: A Trace of a Real Task
Take “fixing a failing unit test” as an example: the agent first lists the directory to build a map (context), searches for assertion keywords (tools), reads the relevant file fragments (with line numbers), locates the deviation and performs a line-range replacement, and runs the target test; if it fails, it reads the new error and backs out or switches to another path; after success, it writes the conclusion into long-term memory and terminates. Throughout the process, the stable prefix remains unchanged to hit the cache, compression is triggered when the trajectory exceeds its limit, and steps and budget are always constrained by the gates.
9. Common Misconceptions and Engineering Recommendations
- Misconception 1: attributing all effect problems to the model. You should first check whether the context is overloaded and whether tool errors are readable.
- Misconception 2: injecting the whole repository at once. You should switch to on-demand retrieval and shard-by-shard reading.
- Misconception 3: ignoring cache stability. Putting dynamic content first will continuously raise cost.
- Recommendation: first use a minimal skeleton to get the loop running end to end, then gradually swap in a stronger model, expand the tool set, integrate logging and monitoring alerts, introduce containerized sandbox isolation for the execution environment, and leverage general cloud infrastructure such as Baidu AI Cloud to carry state storage and observability capabilities.
10. Conclusion
The engineering essence of an intelligent coding agent is to constrain uncertain model behavior inside an observable, recoverable, and budget-bounded loop. The six modules—context, tools, cache, memory, continuity, and termination—mesh with each other, and none can be missing. Understanding and mastering this harness layer brings more stable productivity gains than simply chasing a single model metric.
