Agent Architecture Explained: Six Core Modules of AI Coding Tools
This article breaks down the architecture of AI agent coding tools, focusing on the runtime layer known as the Agent Harness that wraps the underlying model. It explains the iterative Observe-Inspect-Choose-Act loop and details six core modules: context engineering, tool use, memory, permissions and sandboxing, loop orchestration and termination, and observability and evaluation. A minimal implementation example and common design pitfalls are included to help readers build a reusable engineering mental model.
1. Background: The “Shell” Beyond Model Capabilities
In real-world software engineering, whether an agent can complete a task often depends not only on the reasoning ability of the underlying large model, but also on the runtime system built around it. Tool definitions and invocation methods, context organization and trimming, memory writing and retrieval, permission and sandbox constraints, loop orchestration and termination conditions, and runtime observability are the engineering elements that together determine the actual performance of an AI coding tool.
This also explains a common phenomenon: the same model may only offer scattered suggestions in a plain chat interface, yet in an AI coding tool it can handle composite tasks such as repository navigation, cross-file modifications, command execution, and verification. The difference comes not mainly from the model itself, but from the “runtime shell” at the application layer that wraps the model, commonly referred to in the industry as the Agent Harness.
From a general technical perspective, this article abstracts and reconstructs the overall design of AI coding tools, presents six core building modules and how they collaborate, and includes a minimal illustrative implementation to help readers build a reusable engineering mental model.
2. Overall Architecture: An Iterative Loop, Not a One-Shot Q&A
The essence of an AI coding tool is to transform “one-shot Q&A” into a “continuously iterative loop.” This loop can be abstracted into four stages:
- Observe: receive the task description and feedback from the current environment;
- Inspect: read files, search symbols, check test results, and so on;
- Choose: select the next action based on the current context;
- Act: invoke tools to produce real side effects and generate new observations.
The loop keeps running until the task is completed, a termination condition is triggered, or a resource limit is reached. This is a key point: an agent’s “intelligence” is largely reflected in its loop control strategy, not in a single output.
3. Six Core Modules
1. Context Engineering
Context is the agent’s “workbench,” with limited capacity and cost sensitivity. Core work includes: system prompts and role constraints, making tasks and constraints explicit, retrieving and ranking relevant code snippets, trimming and summarizing tool return results, and compressing message history.
Key practices:
- Layered organization: separate stable information (specifications, constraints) from dynamic information (current file, error logs);
- Load on demand: provide an index and summary first, then pull details as needed;
- Structured compression: for long logs, retain key error stacks and failed assertions rather than piling up the full text.
2. Tool Use
Tools are the only channel through which an agent interacts with the real world. A well-designed tool system should have: clear names and descriptions, strict parameter schemas, deterministic return structures, and idempotency and retryability.
Common tool categories include: file reading and writing, symbol search and reference lookup, command execution, test running, and web retrieval (under controlled policies). Tool granularity needs to be balanced: too coarse makes constraints difficult, while too fine increases decision overhead.
Illustrative definition:
def read_file(path: str, start: int = 0, limit: int = 200) -> dict:# Return structured content, avoiding stuffing an oversized file in all at once...def run_tests(target: str = "") -> dict:# Return exit code, failed cases, and a summary of key logs...
3. Memory
Memory is divided into short-term and long-term types. Short-term memory is the current session context; long-term memory is usually stored as retrievable external storage, such as project conventions, historical decisions, and common failure patterns. The key is not “storing” but “retrieval accuracy”: it requires retrieval strategies, relevance ranking, and stale-data eviction mechanisms to avoid outdated information polluting decisions.
4. Permissions & Sandbox
Once an agent can execute commands, security boundaries inevitably arise. In engineering, tiered authorization is typically used: read-only operations are allowed by default; writes and executions require explicit permission or policy matching; high-risk operations (deletion, force push, external network access) require human confirmation or must run in an isolated environment. Sandboxed execution, resource limits, and audit logs are three basic safeguards.
5. Loop & Termination
Clear termination conditions must be set: task completion criteria, maximum iteration steps, timeout, repeated action detection, and consecutive error failure thresholds. An agent lacking a termination strategy easily falls into a state of “repeatedly tweaking without progress,” wasting budget and reducing trustworthiness.
6. Observability & Eval
Every tool call, context change, and decision rationale should be traceable. Through logging services and monitoring and alerting systems, you can pinpoint whether a failure occurred in retrieval, decision, or execution. Combined with an offline evaluation set (typical repository tasks plus expected results), you can turn a “feeling of improvement” into comparable metrics.
4. Minimal Implementation Example: Getting the Loop Running
Below is a minimal pure-language implementation that sketches the skeleton (illustrative code, not a specific product interface):
def agent_loop(task: str, max_steps: int = 12):ctx = Context(task=task)for step in range(max_steps):observation = ctx.render() # Observedecision = model.choose(observation) # Choose: return tool name and argumentsif decision.type == "finish":return decision.answerresult = TOOLS[decision.name](**decision.args) # Actctx.append(decision, result) # Write back the inspection resultif ctx.detect_stuck(): # Repeated action / no-progress detectionbreakreturn "Task not completed: termination condition triggered"
This code is deliberately kept minimal, but the positions of the six modules are clearly visible: context rendering, tool registry, decision model, execution and write-back, termination and stall detection. A real system layers retrieval, compression, permission checks, and auditing on top of each of these points.
5. Common Design Pitfalls
- Treating prompts as everything: ignoring tools and context engineering hard-locks the capability ceiling;
- Not trimming tool returns: reading in an oversized file at once quickly fills the context with noise;
- Lacking termination and stall detection: iteration steps are consumed meaninglessly;
- Adding permission design after the fact: opening up execution first and tightening later easily leaves security risks;
- No evaluation baseline: optimization relies on subjective perception and cannot be regression-verified.
6. Implementation Advice and Cloud Support
To build such a system in production, it is recommended to start with general cloud capabilities for layered decoupling: use a container platform to host sandboxed execution environments, use object storage to store build artifacts and evaluation data, use a message queue to decouple long-running tasks, and use logging services and monitoring and alerting to achieve full-link tracing. Baidu AI Cloud offers a relatively complete combination of such general capabilities, supporting the engineering requirements of an agent runtime in terms of isolation, elasticity, and observability.
Overall, the competitiveness of AI coding tools comes from the synergy of “model + runtime shell.” Only by polishing the six modules—context, tools, memory, permissions, loop, and observability—to engineering standards can the same model reliably demonstrate stronger execution in real repository tasks.
