Coding Agents: Runtime Logic and Core Building Blocks
This article explains why a coding agent needs an orchestration layer beyond the base model, distinguishes LLMs, reasoning models, and agents, and describes the core control loop. It then covers six major building blocks—repository context, prompt structure and cache reuse, tool design, context reduction, session memory, and long-task coherence with delegation—along with engineering trade-offs and practical implementation steps.
Why an Agent Layer Is Needed Beyond the Model
The same base model can perform very differently in an ordinary chat window and in a programming work environment. Most of that difference comes from the system around the model. A model can only receive text and output text. Reading files, running tests, recording change history, and staying aligned with a goal across long tasks all require surrounding programs.
These surrounding programs are usually called an agent orchestration layer, or agent harness. It places the model in a loop and decides what information to provide at each step, which tools may be called, how task state is updated, and when to stop. For software development tasks, the design quality of the orchestration layer directly determines whether results are reliable.
1. Distinguishing Three Concepts
A large language model (LLM) is a neural network trained on a large amount of text. It receives input, generates tokens one by one, and finally outputs text. It does not actively execute any operation by itself.
A reasoning model is still an LLM, but it has been specifically trained or optimized through prompt engineering to spend more computation when answering. It generates intermediate reasoning steps, checks conclusions, or searches among multiple candidate answers. This type of model is suitable for problems that require multi-step derivation, such as complex debugging, but its capability is still limited to a single generation process.
An agent is a control layer built on top of the model. Given a goal, it repeatedly executes a loop of “observe, decide, act, update state” until the goal is completed or a termination condition is triggered. It is important to distinguish these three concepts. When evaluating a coding tool, conflating model capability, reasoning strategy, and the surrounding system makes it difficult to identify the real direction for improvement.
2. The Control Loop of a Coding Agent
A minimal control loop can be written as follows:
def run_agent(goal, model, tools, max_steps=30):state = init_state(goal)for step in range(max_steps):prompt = build_prompt(state, tools) # assemble contextreply = model.generate(prompt) # model proposes next actionaction = parse_action(reply) # parse into structured instructionif action.name == "finish":return action.resultobservation = tools[action.name](**action.args) # execute toolstate = update_state(state, action, observation) # record resultraise RuntimeError("Exceeded maximum steps without completion")
This code reflects three key points of an agent. First, the model decides only the next step each time, rather than writing the entire plan at once. Second, tool execution results are written back into state and become the basis for the next round of reasoning. Third, the loop must have explicit termination conditions and a step limit to avoid unlimited execution that consumes resources.
A real system will add permission checks, error retries, human confirmation points, and logging on top of this skeleton, but the basic structure is the same.
3. Six Core Building Blocks
1. Repository Context
The model does not understand the project. The orchestration layer needs to collect basic repository information at the start of a session, including directory structure, main languages and frameworks, build and test commands, recent commit history, and project documentation files. This information forms a stable environment snapshot that allows the model to determine where code should be placed and what style to follow in the first round.
What to collect requires judgment. Putting the entire repository into the prompt is both expensive and distracting. Usually, only the directory tree, key configuration, and file summaries relevant to the task are provided, while the model reads the rest proactively when needed.
2. Prompt Structure and Cache Reuse
A prompt usually consists of several parts: fixed system instructions, tool descriptions, project snapshot, session history, and the current request. The first few parts are almost unchanged within a session. If they are placed at the front of the prompt and kept byte-for-byte stable, server-side prompt caching can reuse that computation, reducing latency and cost.
Conversely, if the system instructions are modified every round, or the order of the tool list is changed arbitrarily, the cache hit rate will drop noticeably. This is a detail that is easy to overlook in orchestration layer design but has a significant impact.
3. Tool Design and Execution
Tools are the only way for an agent to affect the external environment. Common categories include reading files, searching code, editing files, running commands, and querying version history. Three points matter when designing tools:
- Each tool should have a single responsibility, clear parameters, and structured results.
- Permission boundaries should be set for write and execution operations, such as limiting the working directory and prohibiting deletion without confirmation.
- Tool output should be truncated or summarized to avoid a single large log exhausting the context window.
Error information must also be returned to the model. For example, when compilation fails, return the error location and the original error text so the model can correct the code accordingly.
4. Context Reduction
Long sessions continuously accumulate file contents, command output, and conversation records. As the context limit approaches, the orchestration layer must compress history. There are three common approaches: keep complete records for the most recent few rounds and replace earlier rounds with summaries; keep only conclusions for errors that have already been resolved; and keep only paths and modification times for large files that have been read repeatedly.
The compression strategy directly affects correctness. If a summary drops a key constraint, such as “do not modify public interfaces,” subsequent model operations may violate it. Therefore, key constraints should be explicitly recorded rather than relying on summaries to preserve them automatically.
5. Session Memory
Session memory refers to information saved across rounds and across sessions. It can be divided into three layers. The first layer is the working state of the current task, such as completed steps and to-do items. The second layer is project-level conventions, such as code style, testing requirements, and directories that must not be changed. The third layer is user preferences, such as communication language and confirmation style.
Memory should be stored as structured files or in a database and loaded as needed when the next session starts. Because code changes continuously, old memory may mislead the model, so it needs to be verified periodically.
6. Long-Task Coherence and Task Delegation
Complex tasks may require dozens or even hundreds of steps. To maintain consistent direction, the orchestration layer can maintain an explicit plan document and update its status after each completed step. When subtasks are relatively independent, they can also be handled by a separate model call, with only the conclusion returned to the main process, avoiding filling the main context with intermediate steps.
Delegation requires a clear interface. The input to a subtask should include completion criteria, and the output should be a verifiable result, such as a passing test log or a diff for a specific file, rather than a general description.
4. Engineering Trade-Offs
The design of coding agents involves multiple trade-offs:
- Autonomy and safety: automatically executing commands is efficient but carries a high risk of mistaken operations. Usually, read operations are opened up, while write and network access require confirmation.
- Context completeness and cost: more information leads to more accurate judgment, but latency and cost increase accordingly. Information should be loaded dynamically according to task needs.
- Compression level and traceability: more aggressive summaries leave more room in the window but increase the probability of losing details. Original records should be retained for key decisions.
- Generality and specialization: tools customized for a specific technology stack work better but cost more to maintain.
There is no universal answer to these trade-offs. They should be decided based on team size, codebase complexity, and compliance requirements.
5. Implementation Recommendations
To build a coding agent for a team, proceed in the following order:
- First implement a minimal control loop with only three tools: read file, search, and run tests. Confirm that the loop can reliably complete simple tasks.
- Add error handling and output truncation to each tool, and record complete logs to make it easier to review failure cases.
- Fix the format of system instructions and tool descriptions, and observe prompt cache hit rates.
- Introduce context compression and explicitly record key constraints.
- Add human confirmation before write-type tools, and gradually open permissions after the workflow stabilizes.
- Use a fixed set of representative tasks for regression testing, and rerun them after each change to the orchestration logic.
The effectiveness of an agent depends mainly on engineering design; model choice is only one part of it. Clarifying the responsibilities, boundaries, and failure modes of each module will significantly improve system reliability.
