AI Coding Agent Architecture Breakdown: From System Prompts to Orchestration
This article breaks down the architecture of a mature AI coding agent, showing why system prompts and tool definitions are only the surface layer. It explains the engineering layers that actually determine reliability—context assembly, tool governance, permission control, sub-agent orchestration, memory, extensibility, and observability—and offers a five-track method for analyzing any agent system, common pitfalls to avoid, and a phased roadmap from prototype to platform.
Where the Misconception Comes From: The Prompt Is Only the Tip of the Iceberg
Most online discussions about coding agents focus on two things: what the system prompt says, and which tools are in the tool list. Both matter. The system prompt defines the agent’s role, behavioral rules, and interaction style, while the tools define the boundaries of what it can do.
But these two are closer to the “presentation layer” of a product’s capabilities than the “implementation layer.” Take the same prompt, connect the same set of tools, wrap them in a basic “model output → parse → execute → return” loop, and you can usually get something running that handles simple tasks. In complex engineering scenarios, however, its behavior often falls far short of a mature product. The gap concentrates in four areas:
- Orchestration layer: In a single session, the model must go through far more steps than a single “think—call” cycle. Planning, sub-task decomposition, result aggregation, failure retries, and context compression all require explicit control flow.
- Governance layer: Actions such as file reads and writes, command execution, and network access must pass through fixed stages—validation, risk classification, confirmation, execution, trimming, and auditing—rather than relying on the model’s own discretion.
- Division-of-labor layer: Complex tasks need different types of agents to handle different responsibilities, with the main agent keeping only the refined information needed for decisions.
- Perception layer: Capabilities such as commands, skills, plugins, and memory must be “declared” in a way the model can recognize. The model must first know what it can do and what the rules are before it can act correctly.
Only when these mechanisms stack together do users perceive the “stability” they feel during interaction. That stability does not come from any piece of copy; it comes from engineering. A simple formula captures it:
Actual agent capability ≈ Base model capability × Context organization quality × Tool governance quality × Orchestration and scheduling quality × Feedback and observability quality
This is a multiplicative relationship: if any factor approaches zero, the overall experience collapses. It also explains a common phenomenon—teams upgrade to a stronger model, yet the experience improves only marginally. The bottleneck is usually not the model, but the engineering factors above.
Dissection Methodology: How to Systematically Analyze an Agent System
You can analyze an agent system along five main tracks. The tracks cross-validate each other, making the conclusions more reliable.
- Structure track: How the directory is layered and how modules depend on each other. It reflects the division of responsibilities and where complexity is placed.
- Entry track: Where users can enter the system, and whether different entry points share the same core. It reflects whether the product is a “tool” or a “platform.”
- Control track: Which stages a user request passes through from input to output, which are deterministic program flows, and which are left to the model’s autonomous decisions. It reflects the boundary of determinism.
- Data track: How prompts, context, memory, and logs are produced, flow, get compressed, and persist within the system. It reflects the level of context engineering.
- Extension track: In what form capabilities are added, whether the core code must be modified, and how the model perceives them after loading. It reflects ecosystem design.
In addition, assess constraint strength. Prompts and instructions are “soft constraints”—the model may deviate. Program validation, sandbox isolation, and human confirmation are “hard constraints” with deterministic outcomes. A system’s reliability largely depends on whether key risks are backstopped by hard constraints.
First Conclusion: It Is Not a CLI Tool, but a Runtime Platform
3.1 Single Core, Multiple Entrances
Mature platforms often adopt a “single core, multiple entrances” structure: one agent runtime serving multiple interaction modes. Common ones include an interactive terminal, a new-project initialization guide, a context-ingestion mode for external tools and data sources, and a software development kit (SDK) interface for integration by other programs.
The value of this design lies in isolating change. Interaction interfaces change frequently, while the reasoning and execution core must remain stable. Once the core is decoupled from the entrances, adding a new interaction form requires no changes to the core logic, and behavior across entrances stays consistent. This is the same principle by which an operating system kernel supports multiple shells and multiple graphical interfaces.
3.2 Layered Directory Structure
Take a hypothetical smart coding platform, whose structure can be illustrated as follows:
smart-coding-agent/├── entrypoints/ # Interactive terminal, init guide, context-ingestion mode, SDK├── core/ # Sessions, messages, reasoning loop├── prompts/ # System prompts, environment snapshot templates├── tools/ # Tool definitions, registration, execution, and result handling├── services/ # Runtime services: config, credentials, storage, rate limiting├── commands/ # Slash-command parsing, built-in commands, plugin command loading├── agents/ # Agent definitions, coordinator, sub-agents├── memory/ # Memory directory, retrieval, and writes├── plugins/ # Plugin manifests, discovery, and isolation├── skills/ # Skill packages and progressive loading├── hooks/ # Lifecycle hooks├── tasks/ # Task persistence and checkpoints└── ui/ # Terminal UI rendering
By contrast, a minimal prototype usually has only four or five files: a main-loop file, a prompt file, a few tool files, and several tool functions. The gap between a prototype and a platform is essentially a gap in problem scale.
A prototype answers “how does the model call tools.” A platform must answer a harder set of questions: How does the model stay usable throughout long-running tasks? How are dangerous operations intercepted? How are internal conventions injected? How do team-built capabilities plug in? How is effectiveness measured and regression-tested?
The number of modules grows accordingly. This is the externalization of problem complexity, not “over-engineering” by design.
3.3 The Core Stays Neutral Toward Model Vendors
Many entrances are only half of platformization; the other half is a neutral core. The reasoning core should not be bound to a single model service or a specific protocol format. The model adaptation layer is responsible for only three things:
- Bidirectional conversion of message formats;
- Normalization of streaming output;
- Adaptation of the tool-calling protocol (requests, arguments, results, errors).
This way, in an environment where model capabilities iterate rapidly, switching models, doing multi-model routing, or invoking models by task tier requires replacing only the adaptation layer—the orchestration, permissions, memory, and ecosystem above remain unchanged. Architecturally, this mirrors how an operating system isolates hardware differences through device drivers and how a database isolates storage engines through interfaces.
Prompt Engineering: From a Piece of Copy to Dynamic Assembly
4.1 Layered Structure
A mature system’s prompt is usually assembled from three types of content, each with a different update frequency and magnitude of change:
- Stable contract: Role definition, behavioral rules, safety red lines, output style. This part barely changes across sessions and is best placed at the front.
- Environment snapshot: Working directory, directory-tree summary, version-control status, OS and runtime environment, and the list of available tools and skills. This part changes with the project and the moment.
- Session increment: User goals, sub-task plans, conclusions returned by sub-agents, and compression summaries. This part grows turn by turn.
4.2 Assembly Order Determines Cache Efficiency
Mainstream inference services commonly support “prompt prefix caching”: when the request prefix is identical, the already-computed context can be reused, reducing latency and cost. Therefore, the assembly order should follow a “decreasing stability” principle: put the most stable contract first and the most changeable content as late as possible, avoiding a small change that invalidates the entire prefix cache.
# Illustration: assemble the system prompt from highest to lowest stabilitydef build_system_prompt(env, session):parts = [render_contract(), # Stable contract: rarely changesrender_environment(env), # Environment snapshot: refreshed each sessionrender_tool_summaries(env.tools), # Tool list: name plus a one-line purposerender_skill_summaries(env.skills), # Skill list: name plus a one-line descriptionrender_memory_index(env.memory), # Memory index: entry summariesrender_session(session), # Session increment: plan, summary, user goal]return "\n\n".join(parts)
4.3 Prompts Themselves Need Engineering
Prompts should be managed like code:
- Assemble from templates and fragments that can be tested independently;
- Put them under version control, recording the intent behind each change;
- Run regression against a fixed set of task samples to prevent “fixing one scenario and breaking three others”;
- Separate system-level instructions from project-level conventions, with the latter injected by a convention file in the project.
4.4 Progressive Disclosure: Combating Context Bloat
Tool and skill descriptions expand quickly. A system with dozens of tools and hundreds of skills, if it stuffs all descriptions into context on every request, wastes budget and interferes with the model’s judgment.
A more reasonable approach is layered disclosure:
- The resident context holds only “name + one-line purpose,” ensuring the model knows the capability exists;
- After the model decides to use a capability, the full description and scripts are loaded on demand;
- Within a skill package, further layering is possible—for example, an overview file holds only an index, detailed content lives in sub-files, and is read only when used.
This is an information-organization style of “see the table of contents first, then turn to the chapter,” balancing context budget against capability awareness.
Tool Governance: From Capability Definition to Trusted Execution
Tools are the agent’s only channel to act on the real world, and the most risk-concentrated place. A mature system designs a fixed pipeline for every tool call:
- Definition and registration: Name, purpose, argument structure (schema declaration), risk level, and scope of applicability.
- Argument validation: Types, required fields, value ranges, and enum constraints. Model output is not always a valid structure, so validation must happen before execution.
- Scope constraints: Paths must fall within the workspace, commands must be on an allow list, and network access must have an explicit target. These are hard constraints that do not rely on the model’s discretion.
- Risk classification: Tiers by “whether it changes state” and “scope of impact.”
- Read-only: reading files, searching, listing directories;
- Modify: writing files, local replacement;
- Execute: running builds, tests, scripts;
- Critical: recursive deletion, force push, rewriting version history, production changes.
- Confirmation policy: Low-risk actions run automatically; medium- and high-risk ones require explicit confirmation or secondary authorization.
- Execution: Set timeouts, support cancellation, and isolate via subprocess or sandbox when necessary.
- Result handling: Trim overlong output by “keeping head and tail,” redact sensitive fields, and turn error messages into structured feedback.
Audit trail: Record the caller, argument summary, risk level, elapsed time, and result summary.
Illustration: tool execution pipeline
async def invoke_tool(ctx, call):
spec = ctx.registry.get(call.name)if spec is None:return error("unknown tool", call.name)args = validate(spec.schema, call.arguments)guard = ScopeGuard(workspace=ctx.workspace, policy=ctx.policy)violation = guard.check(spec, args)if violation:return error("policy violation", violation)level = classify_risk(spec, args)if level in ("modify", "execute", "critical") and not ctx.approved(call.id):return pending_confirmation(call.id, level)result = await run(spec, args, timeout=ctx.timeout)result = truncate(result, keep_head=200, keep_tail=50)ctx.audit.record(call, level, digest(result))return result
Why Output Trimming Matters
When a build fails, the compiler or test framework may output thousands of lines of logs. Passing them to the model verbatim wastes context and easily buries the key error. When trimming, keep the head and tail, prioritize errors, failing test cases, and summary information, and attach a “output truncated” notice so the model knows the information is incomplete.
Turning “Model Mistakes” into “System-Correctable” Outcomes
Errors returned by tools should be structured and actionable so the model can adjust its next step. For example:
{"ok": false,"code": "PATH_OUT_OF_SCOPE","message": "Path is outside the workspace: /etc/hosts","hint": "Use a path relative to the workspace, or request access first"}
With this, the model can adjust its strategy instead of repeatedly probing within vague error text.
Permission System: Deny by Default, Allow by Tier
The goal of permission design is not to “make the model obey,” but to turn “which actions can happen automatically” into deterministic, auditable rules.
6.1 Deny by Default, Allow Progressively
# Illustration: permission decision order (deny by default)def decide(request, policy):if escapes_workspace(request):return "deny"if matches(request, policy.deny_rules):return "deny"if matches(request, policy.allow_rules):return "allow"if risk_of(request) >= policy.ask_threshold:return "ask_user"return policy.default_action # Defaults to deny or ask_user
6.2 Session Tiers and Least Privilege
Set permission tiers by scenario:
- Read-only analysis mode: No file writes, no command execution—for code review and problem localization;
- Default edit mode: Allows reads and writes within the workspace; command execution requires per-instance confirmation;
- High-privilege mode: Suitable for containers or isolated environments, but confirmation for critical operations is still retained.
Whatever the mode, the permissions a session obtains should be the minimal set needed for the current task, and should be revoked promptly after the task ends.
6.3 Critical Operations Always Need Deterministic Backstops
Operations such as “recursive deletion,” “force push,” “rewriting version history,” and “production changes” should never be allowed based on the model’s judgment alone, no matter how stern the prompt. They must be intercepted by programmatic rules and confirmed by a human. Soft constraints guide; hard constraints backstop—the two cannot replace each other.
6.4 Engineering the Implementation
Project-level permission policies should be defined centrally and version-controlled alongside the code. Teams can use this to uniformly specify which commands may run automatically, which paths are forbidden for writes, and which operations require approval.
Agent Orchestration: Coordinator, Sub-Agents, and Context Isolation
7.1 Why Division of Labor Is Needed
When a single agent handles planning, retrieval, coding, verification, and summarization at once, context expands rapidly: early information gets diluted, attention scatters, loops lengthen, and costs rise. The essence of division of labor is context isolation. Each sub-agent receives only the information necessary for its own task and returns conclusions afterward.
7.2 Two Roles
- Coordinator (main agent): Responsible for understanding the goal, decomposing tasks, selecting executors, and aggregating results, while itself avoiding time-consuming operations as much as possible.
- Execution sub-agents: Divided by responsibility—for example, code exploration, solution planning, test verification. They have independent contexts and return only refined conclusions to the main agent.
7.3 Scheduling Essentials
- Parallel vs. serial: Independent tasks (such as searching multiple modules at once) can run in parallel; tasks with dependencies must run serially.
- Plan first: For complex tasks, produce an explicit plan first, then proceed according to it. The plan itself is an intermediate artifact users can review and revise.
- Checkpoints: Long tasks save progress periodically so a session can resume from a checkpoint after interruption.
- Failure convergence: Limit retry counts and fallback strategies to avoid infinite loops on a wrong path.
Cost guardrails: Set context and call-count limits for each sub-task.
Illustration: coordinator scheduling loop
async def orchestrate(goal, ctx):
plan = await planner(goal, ctx) # Produce a plan firstfor step in plan.steps:if step.depends_on and not plan.done(step.depends_on):continue # Dependency not done, skipresult = await step.agent.run(step.input, ctx.child_budget())plan.record(step, summarize(result)) # Return only a summaryreturn reviewer.review(plan, goal) # Review, then deliver
Memory and State: Letting Agents Accumulate Across Sessions
Memory determines whether an agent can “understand this project better the more it is used.” It can be divided into three layers:
- Project memory: Architecture conventions, technology choices, build and test commands, error-prone points—persisting long-term with the project and able to be version-controlled;
- Session memory: The current task’s goals, completed steps, and open questions;
- Task state: Todo lists and execution progress, used for process management of long tasks.
The difficulty of memory management lies not in “storing” but in “what to write and when to read.” Three common strategies:
- Structured writes: Split by topic into files or partitions instead of piling into one large file;
- On-demand reads: The system prompt holds only a memory index, and the model retrieves specific entries when needed;
- Deduplication and expiration: Merge and clean up duplicate or stale entries promptly to prevent memory rot.
Persistence of state and memory can leverage cloud primitives—for example, using object storage to hold project memory and checkpoints, and key-value storage to hold session state. For project memory shared among multiple people, entries should be reviewed before writing to avoid solidifying unverified speculation as fact.
Extension Ecosystem: Commands, Plugins, Skills, and Hooks
9.1 Slash Commands Are the Ecosystem Entrance
Mature systems usually provide a set of system-level commands—for example, viewing connected tools and data sources, managing memory, viewing and adjusting permissions, configuring hooks, managing plugins, viewing skills, managing tasks, making plans, initiating code reviews, and managing sub-agents.
The key is the command-loading mechanism: built-in commands, plugin commands, skill commands, skills packaged with the distribution, and user-built skills are all loaded through the same registry. The command system thus becomes the entrance to the entire ecosystem. Unified registration also brings benefits: completion, help information, argument validation, and permission checks apply uniformly to all commands.
9.2 Plugins and Skills: Declarative Extension
Extension capabilities should be declared through manifest files rather than requiring changes to core code:
# Illustration: skill manifest---name: api-contract-checkdescription: Check contract compatibility before API changes; applies to server-side API adjustmentsallowed-tools: read_file, grep, run_tests---# API contract compatibility check steps1. Locate the API definition files...2. Compare fields and types before and after the change...3. Run contract tests and summarize results...
A manifest includes at least the name, purpose description, dependent tools, entry file, and permission declarations. On load, the system first validates the manifest’s legality, then limits its usable scope according to the permission declarations. This “capability carries its own description and constraints” approach lets extensions be completed without touching the core.
9.3 Hooks: Solidifying Team Processes into the Lifecycle
The hook mechanism allows inserting deterministic programs at key points. Typical points include:
- Before a session or task starts;
- Before a tool call (can intercept or rewrite arguments);
- After a tool call (can format, supplement information, or redact);
When a task ends or a session closes.
Illustration: hook configuration
hooks:
before_tool:- command: "policy-check.sh" # A non-zero exit code blocks this callafter_tool:- command: "format-output.sh"session_end:- command: "archive-log.sh"
Common uses include enforcing a unified code style, automatically supplementing context, and reporting operation logs to internal systems. Hooks turn team conventions from prompt-based “advice” into deterministically executed rules.
Observability and Evaluation: Stability Comes from Measurement
“Stability” without measurement cannot be sustained. At minimum, track the following metrics:
- Task completion rate: Whether the task actually achieved its goal, not merely “produced output”;
- First-pass rate: The proportion of builds and tests passing on the first try after a change;
- Average tool calls: Reflects path efficiency;
- Human intervention count: Frequency of confirmations, corrections, and re-explanations;
- Context compression count: Reflects long-task management quality;
Cost per task: Converted from call volume and context size.
Illustration: hook-driven metric collection
after_tool:
- command: "report-metric.sh --event tool_call --fields name,duration,status"
Combined with session-level tracing, you can locate “which step is slow” and “which tool is wrong.” For evaluation, build a case set covering typical scenarios and run automatic regression after changes to prompts, tools, or models. Only by forming a “change—evaluate—observe—improve” loop can system quality be sustained.
Implementation Roadmap: From Prototype to Platform
| Phase | Core Work | Key Output | Acceptance Signal |
|---|---|---|---|
| 1. Skeleton | Separating multiple entrances from the core, model adaptation layer, prompt assembly, basic read-only tools | A runnable reasoning loop | The same task behaves consistently across entrances |
| 2. Governance | Tool pipeline, risk classification, permission policies, output trimming, audit | A trusted execution chain | Critical operations cannot be bypassed |
| 3. Extension | Command system, plugins and skills, hooks, memory | A sustainably extensible ecosystem | New capabilities require no core changes |
| 4. Scale | Coordinator and sub-agents, checkpoints, evaluation sets, metrics dashboard | A measurable, regression-testable platform | Every change is backed by data |
When hosted in the cloud, several general-purpose primitives can be combined:
- Container platform: hosts the agent runtime and provides an isolated environment;
- Message queue: decouples long tasks and smooths peaks and troughs;
- Object storage: persists checkpoints and project memory;
- Logging and monitoring/alerting: sets threshold alerts for tool calls, task failures, and abnormal latency.
For example, on Baidu AI Cloud, enterprises can select cloud products such as object storage, message queues, container platforms, logging, and monitoring/alerting as needed to build hosting and observable infrastructure for the agent runtime. When selecting, focus on three points: whether fine-grained permissions are supported, whether complete operation auditing is available, and whether deployment within a private network is possible.
Common Pitfalls
- Treating the prompt as everything: Without orchestration and governance, even the best prompt struggles to support complex tasks.
- Opening permissions without restraint: Short-term efficiency gains come at the cost of irreversible loss.
- Injecting all tools and skills: Context gets filled with description text, and the model ends up “not seeing” key information.
- Only soft constraints, no hard constraints: Placing safety entirely on the model’s discretion is the most common systemic risk.
- Focusing only on model capability, not evaluation: Every change is made by feel, and quality cannot be stabilized.
Conclusion
Back to the opening question: why can’t the same prompt and tools reproduce the same experience? Because the prompt is only the agent’s “presentation layer.” What truly determines the experience is the engineering system made up of context assembly, tool governance, permission boundaries, task orchestration, memory accumulation, ecosystem extension, and observability. This system is not unique to any one product; it is the underlying capability any agent that needs to do real work reliably and controllably over the long term must possess. Next time you evaluate an agent product, ask along the five tracks: How does it assemble context? What checkpoints does a tool call pass through? Who backstops dangerous operations? How are complex tasks divided? How is effectiveness measured? Only a system that can answer these questions clearly deserves the word “stable.”
