From Core Loop to Multi-Agent: A Complete Guide to AI Coding Agent Architecture
AI coding agents are not chatbots—they are long-running engineering systems with side effects, retries, and safety boundaries. This article breaks down the full architecture of a production-grade coding agent: the core agent loop, context engineering, planning, subagents, memory, task scheduling, concurrency conflict handling, permissions, observability, and the general cloud capabilities typically used to deploy such systems. Readers will learn why the model sets the ceiling while the Agent Harness determines whether you can reliably reach it.
1. Breaking a Common Misconception: It’s Not a Chat Box, It’s an Engineering System
The biggest misunderstanding about intelligent coding tools is treating them as “chat boxes that write code.” A chat box follows a single-turn Q&A model: you ask, it answers, and all state lives in the conversation history. But an agent that can actually modify code, run tests, and read logs is, at its core, a long-running engineering system with side effects, failures, and retries.
It needs to read files, execute commands, observe outputs, and adjust its next action based on the results. It needs to remember the original goal after dozens of interaction rounds. It must avoid stepping on other tasks running in parallel, and pause to ask for confirmation before performing unauthorized operations. None of this is solved by “a smarter model”—it is determined by the surrounding engineering structure.
So the right question when evaluating a coding agent is not “how strong is the underlying model,” but “how complete is its Agent Harness.”
2. The Core Mental Model: The Model Is the Driver, the Harness Is the Car
This is the philosophical foundation of the entire architecture: intelligence comes from model training, not from the framework code you write.
Think of the large model as a driver and your Agent framework as the car. The driver’s skills were trained by the model vendor on massive data—you can’t press the gas pedal for them. But you can build a good car: steering wheel, dashboard, brakes, seatbelt, and mirrors—all essential.
| Role | Responsible for | Not responsible for |
|---|---|---|
| Model (Driver) | Understanding intent, planning steps, generating code, judging results | Persisting state, executing real IO, enforcing boundaries |
| Harness (Car) | Tools, knowledge, context management, permission control, scheduling and recovery | Making semantic decisions in place of the model |
The four pillars of a Harness:
- Tool Use: gives the agent hands—the ability to read and write files, execute commands, retrieve information, and call external APIs.
- Knowledge: domain documentation, coding standards, and API references loaded on demand, rather than stuffed into the prompt all at once.
- Context Engineering: making trade-offs within a limited window to prevent “amnesia” and attention dilution.
- Permission: defining what the agent can do, cannot do, and what requires human confirmation.
Once you understand this, every mechanism that follows can be seen as the same activity: adding parts to the car.
3. Stage One: A While Loop Carries the Whole System
Strip away all the fancy features, and the core of a usable coding agent is only a few dozen lines. Its skeleton is a loop:
messages = [{"role": "user", "content": goal}]while True:resp = model.generate(messages, tools=TOOLS) # Model output: text or tool callsmessages.append(resp)if resp.tool_calls:results = [execute(tc) for tc in resp.tool_calls] # Real execution, with side effectsmessages.append({"role": "tool", "content": results})continueif resp.is_final:return resp.text # Termination: the model deems the task complete
Three key design decisions in this code deserve emphasis:
- The message array is the single source of truth for state. There are no hidden global variables; the agent’s “memory” is
messages. This makes state serializable, replayable, and resumable—the foundation for all later memory and recovery mechanisms. - Tool calls are the only interface between the model and the world. The model itself cannot read files; it can only emit a structured “request” that the Harness executes and feeds back. This boundary is simultaneously a capability boundary and a security boundary.
- Termination must be backstopped by the Harness. Relying on the model’s self-report of “I’m done” is unreliable. In practice, you layer in budget limits (maximum rounds, tokens, elapsed time) and external validation (do the tests pass, does the build succeed).
Why must it be a loop rather than a single call? Because information in real engineering tasks is revealed incrementally: without reading the files you don’t know the structure; without running the tests you don’t know if the code is correct. The loop = an observe–decide–act closed cycle. This is the dividing line between an agent and generative Q&A.
4. Stage Two: Context Engineering Against Context Explosion
Once the loop is running, the first wall you hit is context. The message array grows monotonically, quickly causing three problems: linearly rising costs, longer latency, and diluted key information leading to worse decisions.
Common industry techniques, usually combined:
- Layered loading: provide the directory structure and index first; load full contents only after the model specifies paths—avoid ingesting the entire repository at once.
- On-demand retrieval: store standards, past decisions, and API docs in external storage, injected by relevance through retrieval tools.
- Rolling summaries: when a threshold is exceeded, compress early conversation into a structured summary (goal, changes made, unresolved issues, failed attempts) while keeping recent messages verbatim.
- Subagent isolation: delegate “read a lot of files” style dirty work to subagents with independent contexts that report back only conclusions.
- Explicit budgeting: treat the window as a finite resource to be allocated, not an infinite container.
BUDGET = {"system": 0.10, "summary": 0.20, "recent": 0.50, "tool_output": 0.20}def fit(messages, limit):if estimate_tokens(messages) <= limit:return messagessummary = summarize(messages[:-KEEP_RECENT]) # Compress early historyreturn [messages[0], summary] + messages[-KEEP_RECENT:]
A counterintuitive but important lesson: more context is not better. Stuffing in irrelevant information makes the model latch onto the wrong things—so pruning matters as much as adding.
5. Stage Three: Planning and Subagents
5.1 Think Before You Act: Explicit Plans
Complex tasks drift off course if you just dive in. The engineering answer is a plan mode: first read-only, producing a reviewable task list; execute only after user confirmation, and keep the list’s status updated throughout. The list doubles as a progress dashboard and a context-compression anchor—even if history gets summarized, goals and progress stay clear.
1. [done] Locate the config loading entry point2. [doing] Extract retry logic into a standalone module3. [todo] Add unit tests4. [todo] Run the full test suite and fix regressions
5.2 Subagents: Trading Context Isolation for Parallelism
The value of a subagent is not “being smarter,” but context isolation: it has its own window, can read dozens of files and fail a dozen times, while the parent agent receives only a short conclusion. This solves both context explosion and main-flow pollution.
Subagent design essentials: the goal description must be self-contained (it does not share the parent’s conversation), the return format must be structured, its available tools and budget must be constrained, and failures must be observable rather than silently degraded.
6. Stage Four: Memory, Scheduling, and Concurrency Conflicts
6.1 Three Tiers of Memory
- Short-term memory: the current session’s message array.
- Working memory: task lists and note files persisted to disk, surviving across turns and even sessions.
- Long-term memory: project conventions, past decisions, and known pitfalls—stored in structured storage or a vector index and recalled by relevance.
The key principle: memory must be editable and invalidatable. Stale memory is more dangerous than no memory, so writes need confidence annotations and periodic cleanup.
6.2 Task Scheduling
Multi-task scenarios need a dependency graph: parallelize independent tasks, serialize dependent ones, retry and roll back failures. The scheduler handles priority, concurrency, timeouts, and idempotency.
6.3 Concurrency Conflicts: The Real Hard Part of Multi-Agent Systems
When multiple agents modify the same repository simultaneously, conflicts are inevitable. Common solutions:
- Workspace isolation: each agent gets its own branch or container workspace; changes merge through review.
- File-level locks and leases: acquire a lease before writing, auto-release on timeout to avoid deadlocks.
- Optimistic concurrency: validate version numbers at commit time; on conflict, re-read and retry.
- Idempotency and rollback: design all side-effecting operations to be replayable and reversible.
def run_task(task):ws = create_workspace(task.id) # Isolationtry:with lease(task.files, ttl=300): # Lease lockpatch = agent.run(task.goal, workspace=ws)verify(patch) # External validation: build + testsreturn submit(patch) # Idempotent submitfinally:release(ws)
7. Permissions and Security Boundaries
More capability demands better brakes. A practical tiered policy:
- Three-level authorization—read/write/execute—with least privilege by default.
- Explicit confirmation for dangerous operations: bulk deletions, force pushes, and production changes require human approval.
- Sandboxed execution: commands run in restricted containers with limits on network, filesystem, and resource quotas.
- Prompt injection defense: treat external content (web pages, logs, dependency files) as untrusted data; never let “instructions” embedded in it be executed as commands.
- Full audit logging: record every tool call, its parameters, results, and duration for traceability and post-mortems.
8. Observability and Evaluation: Turning Mysticism into Engineering
Without measurement there is no improvement. At minimum, collect: task success rate, average rounds, token usage and cost, tool failure rate, human intervention count, and average completion time. Also maintain a regression evaluation set (real historical tickets with expected outcomes) and run it against every change to prompts, tools, or scheduling—otherwise you fix A and break B.
9. General Cloud Capabilities for Enterprise Deployment
Building such a system in the cloud typically reuses a few generic capability categories: a container platform to host sandboxed workspaces and elastic concurrency; object storage for artifacts, patches, and evaluation data; message queues for task distribution and peak shaving; logging services and monitoring/alerting for end-to-end tracing and anomaly notification; and relational/vector stores for long-term memory. Baidu AI Cloud offers products in these general categories that can be combined as needed, without building the underlying infrastructure yourself.
10. Conclusion
Back to the original question: are these tools really that impressive? The answer—the model determines the ceiling; the Harness determines whether you can reliably reach it. Starting from a few dozen lines of loop and progressively adding tools, context budgets, planning, subagents, memory, scheduling, concurrency control, and permission boundaries, you end up with a system that is explainable, traceable, and scalable. The greatest payoff of this process is not replicating some product, but gaining a capability: turning the intuition that “AI coding is magical” into measurable, optimizable, deliverable engineering practice.
