How AI Coding Agents Work: System Prompt Assembly and Context Engineering

    As AI coding tools converge on the same underlying models, the engineering layer around the model becomes the real differentiator. This article breaks down the five core mechanisms behind a mature agent framework — runtime system prompt construction, tool systems, context compaction and re-injection, sub-agents for context isolation, and external tool connection protocols — compares them against typical open-source scaffolding, and distills a set of reusable design principles for building reliable AI coding agents.

    Introduction: Why an Agent’s Mechanics Matter More Than the Model

    AI coding tools are spreading quickly, and one misconception keeps recurring: that differences in output quality come entirely from the underlying large language model. In practice, once the models wired into different tools start to converge, what actually separates the experience is the layer of engineering scaffolding wrapped around the model — how the agent assembles prompts, how it exposes tools, how it manages context, and how it schedules sub-tasks.

    The value of a mature agent is that it turns the model’s general-purpose capabilities into engineering behavior that is predictable, controllable, and low-noise. Starting from a typical agent framework implementation, this article dissects five core mechanisms — system prompts, the tool system, context management, sub-agents, and external connection protocols — compares them with common open-source implementations, and closes with reusable design principles.

    1. The System Prompt Is Assembled at Runtime

    From hard-coded text to on-the-fly assembly

    Most early AI coding tools injected a fixed block of prompt text unchanged at process startup, and it stayed that way for the entire session. This is simple to implement but has two structural flaws. First, it cannot perceive the current environment — the working directory, the platform, and the connected tools all differ from session to session. Second, the prompt text drifts away from the capabilities that are actually available: if the text describes a tool that has been disabled, the model may try to call a capability that does not exist.

    The more mature approach treats the system prompt as a runtime artifact. At each session start, a build function — conceptually, buildEffectiveSystemPrompt — assembles the text on the spot, and the final content depends on the current environment, the enabled tool set, the connection state of external protocols, and any user configuration overrides. In effect, this upgrades the prompt from “static configuration” to “dynamic view.”

    The default prompt as a behavioral contract

    Even on the dynamic route, a relatively stable base prompt is usually retained. It works less like documentation and more like a contract that constrains model behavior. Typical clauses include:

    • Tools before shell commands. The model is asked to prefer dedicated tools — file reading, content search, filename matching — over equivalent general-purpose shell commands. Dedicated tools offer finer-grained permission control and more consistently structured returns, which significantly reduces both out-of-scope risk and parsing cost.
    • Output style constraints. Answers should be direct and concise. Decorative symbols, filler phrases, and meaningless confirmations are discouraged, as is restating information the user already knows. The goal is to compress token noise so output stays tight and is easy for downstream processes to consume.
    • How memory works. The prompt explains the automatic discovery paths for configuration files (a hierarchical lookup: user level → project root → subdirectories) and the conventions for writing them, so long-term preferences get loaded correctly.
    • Safety protocol. For irreversible or highly destructive operations such as forced pushes and hard resets, the model must first obtain explicit user authorization, putting high-risk actions into a human confirmation loop.
    • Skill invocation convention. The prompt documents how slash commands (/skill-name) are triggered, so the model knows how to dispatch pre-built reusable workflows.

    Incrementally injected runtime content

    Beyond the base contract, a batch of content has to be injected on demand at session start rather than hard-coded:

    • Tool descriptions. The agent iterates over the description methods of all currently enabled tools and stitches them into the prompt dynamically. As a result, disabling a tool also removes its description from the prompt, eliminating the class of errors where the model calls a tool that is not available.
    • External connection instructions. When external tools or data sources are connected, their usage instructions are injected as incremental content. This content should also be re-injected after any context compaction, so capability definitions are not lost during compression.
    • Skill index. The name, description, and applicable scenarios of installed skills are aggregated and injected, making it clear which slash commands can be dispatched in the current session.
    • Environment awareness. An environment enrichment function injects runtime context such as the current platform, date, and working directory, giving the model basic spatial and temporal awareness.
    • Tool retrieval hints. When a deferred-loading strategy is in place, an extra note tells the model how to discover capabilities that have not yet been loaded through search-type tools — a balance between prompt size and breadth of capability.

    2. Tool System and Context Management

    Tools are the agent’s hands and feet. The design pattern is usually “declarative definition plus structured return”: each tool supplies a name, a purpose description, a parameter schema, and its execution logic. The model initiates calls based on that declaration, while the framework handles validation, authorization, and result formatting. Good tool design encapsulates complex operations as atomic capabilities, so the model can orchestrate them without understanding the underlying details.

    Context management is the agent’s memory and field of view. As a conversation progresses, history keeps growing, and returning all of it every turn is both expensive and likely to overflow the window. Mature frameworks typically apply progressive compaction: when usage nears a threshold, the conversation history is summarized, and at the same time the “re-injection” mechanism described above restores key content such as the system prompt, tool descriptions, and external instructions. This ensures that compaction does not destroy non-regenerable information like capability definitions. In addition, pairing subdirectory memory files with on-demand reads strips large blocks of project conventions out of the main context and loads them only when needed — an effective way to control context bloat.

    3. Sub-Agents and Task Isolation

    A single context inevitably becomes bloated as task complexity grows. The core idea of the sub-agent mechanism is context isolation: work that can be completed independently and whose intermediate output does not need to flow back to the main thread — for example, “locate a certain class of implementation across the entire repository” — is handed to a sub-agent with its own context, and only a summary of the conclusion is returned to the main thread.

    This yields three benefits. First, token usage in the main context drops sharply. Second, different tasks can use different tool sets and prompt strategies, enabling fine-grained authorization. Third, parallel scheduling becomes possible, since mutually independent sub-tasks can proceed at the same time. The engineering difficulty lies in controlling the granularity of task partitioning and the information fidelity of the returned summary: cut too coarsely and isolation loses its point; cut too finely and scheduling overhead multiplies.

    4. External Connection Protocols: Connecting the Agent to the World

    To let an agent reach databases, search services, file systems, and other external systems, the industry has converged on a unified approach to context and tool connection protocols. An external service declares its capabilities and parameters in a standard form; the agent probes the connection at startup, loads those capability declarations, and turns them into tools the model can call. The value here is decoupling capability extension from the agent core — adding a data source requires no change to the core code, only an implementation of the protocol. This pluggable architecture is a key step in an agent’s evolution from a single-machine tool into an integrable platform.

    5. Side-by-Side Comparison: Mature Frameworks vs. Open-Source Scaffolding

    Placed next to comparable open-source implementations, the mechanisms above reveal several typical maturity gaps:

    • Static vs. dynamic prompts. Many open-source scaffolds still use fixed prompts with no environment awareness or on-demand injection, so the prompt description and the actual capabilities drift apart.
    • Handling of tool descriptions. Mature frameworks fold tool descriptions into the dynamic view and keep them in sync with enabled state; open-source implementations tend to list every tool redundantly in the prompt.
    • Context strategy. Mature frameworks generally support both compaction and re-injection, while open-source implementations rely more on simple truncation or returning everything in full.
    • Sub-agents and protocol integration. Complete task isolation and pluggable external connectivity are often missing or only shallowly implemented in open-source scaffolds.

    Overall, mature frameworks are more rigorous in prompt assembly, context compaction, tool synchronization, sub-agent scheduling, and external connectivity — and that is precisely why their experience is more stable.

    Conclusion: Reusable Design Principles

    Stepping away from any specific product, a general set of agent design rules emerges:

    1. Generate prompts dynamically, so that capability declarations stay strictly consistent with the runtime environment.
    2. Prefer dedicated tools over general-purpose commands, for finer permission control and more consistent structured returns.
    3. Manage context actively, using progressive compaction plus re-injection of critical information to control bloat.
    4. Isolate complex tasks with sub-agents, trading a small amount of scheduling overhead for a clean main context and parallel execution.
    5. Make capability extension protocol-based and pluggable, keeping the core decoupled from the ecosystem.

    None of these principles depend on a particular model or framework. Whether you are building an agent from scratch or engineering one on a platform such as Baidu AI Cloud, getting these mechanisms right is what ultimately determines how reliable an AI coding tool is and how high its experience ceiling can go.