How Agentic Coding Tools Work: A Source Code Reading Guide

    This article breaks down the common architecture of agentic coding tools through a source-code reading lens. It explains how these systems move beyond conversational suggestions to deliver closed-loop results, covering the core agent loop, termination conditions, tool system design, context budget management, prompt engineering, security models, and multi-agent observability. Readers will gain a clear framework for understanding and building controllable agentic coding systems.

    How Agentic Coding Tools Work: A Source Code Reading Guide

    1. Background: The Shift from “Giving Advice” to “Delivering Results”

    When you ask a general-purpose large language model to “fix this bug,” a purely conversational system typically responds with natural-language suggestions: add a null check before a certain conditional branch, or adjust a loop boundary by one. The actual editing, compiling, testing, and regression still fall to the human. The model acts as an advisor, and the human is responsible for its correctness.

    The agent form, by contrast, is expected to deliver results. To complete the same task, the system must autonomously chain together a long sequence of actions: enumerate the repository structure, read relevant source files, search for symbol definitions and references, infer the call chain, generate a patch, run the build and tests, parse failure stack traces, apply further fixes, and repeat verification until convergence. This leap from “text suggestions” to “closed-loop execution” introduces a set of engineering problems that conversational systems never face:

    • State and loop control: There must be clear criteria for when to continue, when to converge, and when to abort.
    • Action space design: What the model can do, at what granularity, and what it returns to the model.
    • Context budget: A codebase far exceeds the window capacity, so content must be loaded on demand and evicted promptly.
    • Permissions and risk: Writing files and executing commands have real side effects and must be controllable and reversible.
    • Observability: Every reasoning step and tool result must be traceable for debugging and auditing.

    The following sections break down the general implementation approach for such systems, layer by layer, along these dimensions.

    2. The Agent Main Loop: Confining Uncertainty in a Finite State Machine

    The core is an iterative “reason-act-observe” loop. The pseudocode can be abstracted as:

    1. messages = [system_prompt, user_task]
    2. for step in range(MAX_STEPS):
    3. resp = model.generate(messages, tools=tool_schema)
    4. if resp.tool_calls:
    5. results = [dispatch(tc) for tc in resp.tool_calls] # run in parallel or serially
    6. messages += [resp, *results]
    7. else:
    8. return resp.text # no tool call is treated as convergence
    9. raise BudgetExceeded(MAX_STEPS)

    There are four engineering essentials. First, multiple termination conditions: besides “the model no longer requests tools,” you should also set a step limit, a token budget limit, a per-tool timeout, and a total duration limit to avoid infinite loops that burn money. Second, errors enter the loop rather than being thrown: the result of a failed tool should be fed back to the model in a structured form (including error codes and key stderr), letting the model correct itself. This is what distinguishes an agent from a script. Third, batching and parallelism: independent read operations can run concurrently, while write operations must be serial with conflict detection. Fourth, externalized state: conversation history, the list of modified files, and executed commands should be kept in a structured state outside the loop, making snapshots and recovery easier.

    3. Tool System: Granularity, Contracts, and Idempotency

    Tools are the only interface between the model and the world, and their design quality directly determines the upper bound.

    Granularity trade-offs: Too fine (line-by-line editing) amplifies the number of calls and the probability of errors; too coarse (completing a refactor in one sentence) is uncontrollable. A common industry compromise is to provide a set of orthogonal primitives such as “read file (with line ranges),” “write file,” “exact string replacement,” “list directory,” “search content,” and “execute command.”

    Clear contracts: Each tool needs a clear name, purpose description, parameter schema, and return schema. Parameters should be as flat as possible, avoiding deep nesting that leads the model to fill them in incorrectly.

    Idempotency and reversibility: Write tools should support a “read-before-write” precondition check (comparing file versions to prevent overwriting others’ changes) and retain the original content to support undo.

    An illustrative tool declaration:

    1. {
    2. "name": "edit_text",
    3. "description": "Replace the uniquely occurring old fragment with new in the specified file",
    4. "parameters": {
    5. "file_path": "string",
    6. "old": "string, must match uniquely",
    7. "new": "string"
    8. }
    9. }

    4. Context Management: Spending the Limited Window Where It Counts

    Codebases often reach millions of lines and must be loaded on demand. Reusable strategies include:

    1. Layered summarization: repository-level structure diagram → module responsibilities → file-level signatures, drilling down layer by layer.
    2. Search first: use keyword or symbol search to locate candidate files, then read the relevant ranges precisely, rather than loading whole files.
    3. Compression and eviction: truncate lengthy tool outputs and mark them as “omitted,” summarize and archive early rounds, keeping decision conclusions while discarding process noise.
    4. External memory: write todos, confirmed facts, and lessons from failures into a separate notes file for reuse across rounds, equivalent to giving the model external working memory.

    5. Prompt Engineering: Layering and Front-Loading Constraints

    A high-quality system prompt usually includes: role and goal, environment and conventions (tech stack, directory norms, commit habits), code of conduct (read before write, minimal changes, mandatory self-testing), tool usage instructions, and output format requirements. The key lesson is to write constraints as checkable rules rather than abstract slogans, for example “a build must be run once after changes” and “no unused dependencies may be added.” Also avoid overly long prompts that conflict with each other; inject content in segments ordered as “stable rules — task context — dynamic search results.”

    6. Security Model: Least Privilege by Default

    • Sandbox isolation: place command execution in a container or restricted environment, limiting network access, filesystem write scope, and resource quotas.
    • Tiered authorization: read operations are allowed automatically, while writes and execution require a whitelist or human confirmation; high-risk actions need secondary confirmation.
    • Sensitive information governance: inject secrets via environment variables rather than plaintext into the context, and redact output.
    • Full-chain auditing: record each tool call, its parameters, results, and duration to support replay.

    7. Multi-Agent Collaboration and Observability

    Complex tasks can be split into “planner-executor-reviewer” roles that exchange structured artifacts via a message queue or shared blackboard; but collaboration amplifies context and cost, so it should be enabled only when the task can be cleanly partitioned. For observability, it is recommended to add structured instrumentation at every step (summary of reasoning, tool name, token consumption, state changes) and connect to a general logging service with monitoring and alerting, forming a traceable chain.

    8. Conclusion

    The key to understanding such systems is not memorizing a specific implementation, but grasping four main threads: loop convergence, tool contracts, context budget, and permission boundaries. To deploy this in your own environment, you can build sandboxes on a container platform, store artifacts in object storage, and ensure observability with a logging and monitoring system. Baidu AI Cloud can provide support in these general infrastructure categories. Once you master this skeleton, replacing any underlying model or toolset lets you quickly build stable and controllable agentic coding capabilities.